为什么对一行或一列进行切片会产生“无量纲数组”?例如:
import numpy as np
arr = np.zeros((10,10))
print arr.shape
# (10, 10)
但是当我只需要一列或一行时,我得到
print arr[:,0].shape
# (10,)
print arr[0,:].shape
# (10,)
代替
print arr[:,0].shape
# (10, 1)
print arr[0,:].shape
# (1, 10)
请您参考如下方法:
例如,您从 0 列和 0 行获取 np.arrays,它们是具有 1 维的 numpy.array。你可以像这样切片做一些小技巧:
In [103]: arr[:1,:].shape
Out[103]: (1, 10)
In [104]: arr[:,:1].shape
Out[104]: (10, 1)
编辑
来自 docs :
An integer,
i, returns the same values asi:i+1except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p-th element an integer (and all other entries:) returns the corresponding sub-array with dimension N - 1. If N = 1 then the returned object is an array scalar. These objects are explained in Scalars.
