Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/numpy问题,数组/向量的第二维度为空_Python_Arrays_Numpy_Vector - Fatal编程技术网

Python/numpy问题,数组/向量的第二维度为空

Python/numpy问题,数组/向量的第二维度为空,python,arrays,numpy,vector,Python,Arrays,Numpy,Vector,我有一个似乎很简单的问题 遵守守则: In : x=np.array([0, 6]) Out: array([0, 6]) In : x.shape Out: (2L,) 这表明数组没有第二维度,因此x与x.T没有区别 如何使x具有尺寸(2L,1L)?这个问题的真正动机是我有一个数组y的形状[3L,4L],我希望y.sum(1)是一个可以转置的向量,等等。当你可以重塑数组,并用[:,np.newaxis]添加维度时,你应该熟悉最基本的嵌套括号,或者列表,表示法。注意它与显示的匹配程度 In [

我有一个似乎很简单的问题

遵守守则:

In : x=np.array([0, 6])
Out: array([0, 6])
In : x.shape
Out: (2L,)
这表明数组没有第二维度,因此
x
x.T
没有区别


如何使x具有尺寸(2L,1L)?这个问题的真正动机是我有一个数组
y
的形状
[3L,4L]
,我希望y.sum(1)是一个可以转置的向量,等等。

当你可以重塑数组,并用
[:,np.newaxis]
添加维度时,你应该熟悉最基本的嵌套括号,或者列表,表示法。注意它与显示的匹配程度

In [230]: np.array([[0],[6]])
Out[230]: 
array([[0],
       [6]])
In [231]: _.shape
Out[231]: (2, 1)
np.array
还接受一个
ndmin
参数,尽管它在开始处添加了额外的维度(numpy的默认位置)

制作2d形状的经典方法-重塑:

In [234]: y=np.arange(12).reshape(3,4)
In [235]: y
Out[235]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
sum
(和相关函数)有一个
keepdims
参数。阅读文档

In [236]: y.sum(axis=1,keepdims=True)
Out[236]: 
array([[ 6],
       [22],
       [38]])
In [237]: _.shape
Out[237]: (3, 1)
空的第二维度
不太合适。更像是一个不存在的第二维度

维度可以有0个术语:

In [238]: np.ones((2,0))
Out[238]: array([], shape=(2, 0), dtype=float64)
如果您更熟悉MATLAB,它至少有2d,您可能会喜欢
np.matrix
子类。它采取步骤确保大多数操作返回另一个二维矩阵:

In [247]: ym=np.matrix(y)
In [248]: ym.sum(axis=1)
Out[248]: 
matrix([[ 6],
        [22],
        [38]])
矩阵
用于:

np.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)

\u collapse
位允许它为
ym.sum()
返回一个标量。还有一点需要保留维度信息:

In [42]: X
Out[42]: 
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])

In [43]: X[1].shape
Out[43]: (2,)

In [44]: X[1:2].shape
Out[44]: (1, 2)

In [45]: X[1]
Out[45]: array([0, 1])

In [46]: X[1:2]  # this way will keep dimension
Out[46]: array([[0, 1]])

NumPy数组有一个
reformate()
方法,或者您也可以添加一个额外的维度。是否有方法将keepdims=True作为默认值?一次又一次的输入太多了。对我来说,对(2L,)数组进行转置应该会让numpy意识到你想要一个(1L,2L)数组这里是
np.matrix
类。我不知道keepdims,很好!
In [42]: X
Out[42]: 
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])

In [43]: X[1].shape
Out[43]: (2,)

In [44]: X[1:2].shape
Out[44]: (1, 2)

In [45]: X[1]
Out[45]: array([0, 1])

In [46]: X[1:2]  # this way will keep dimension
Out[46]: array([[0, 1]])