虽然你可以使用[:,np.newaxis]
来重塑数组并添加维度,但你应该熟悉最基本的嵌套括号或列表表示法。请注意它与显示的匹配。
In [230]: np.array([[0],[6]])
Out[230]:
array([[0],
[6]])
In [231]: _.shape
Out[231]: (2, 1)
np.array
也接受一个ndmin
参数,但它会在开始处添加额外的维度(这是numpy
的默认位置)。
In [232]: np.array([0,6],ndmin=2)
Out[232]: array([[0, 6]])
In [233]: _.shape
Out[233]: (1, 2)
将某物制成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]])
< p >
sum
(以及相关函数)具有
keepdims
参数。请阅读文档。
In [236]: y.sum(axis=1,keepdims=True)
Out[236]:
array([[ 6],
[22],
[38]])
In [237]: _.shape
Out[237]: (3, 1)
empty 2nd dimension
不是很准确的术语,更像是不存在的第二维。
一个维度可以有0个项:
In [238]: np.ones((2,0))
Out[238]: array([], shape=(2, 0), dtype=float64)
如果你更熟悉最少有2d的MATLAB,你可能会喜欢np.matrix
子类。它采取措施确保大多数操作返回另一个2d矩阵:
In [247]: ym=np.matrix(y)
In [248]: ym.sum(axis=1)
Out[248]:
matrix([[ 6],
[22],
[38]])
矩阵的
sum
功能是:
np.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)
_collapse
位允许它为
ym.sum()
返回标量。
reshape()
方法,或者您也可以添加一个额外的维度。 - Ashwini Chaudhary