假设我有:
test = numpy.array([[1, 2], [3, 4], [5, 6]])
test[i]
获取数组的第i行(例如[1, 2]
)。 如何访问第ith列? (例如[1, 3, 5]
)。 另外,这将是一项昂贵的操作吗?
#1楼
如果您想一次访问多个列,则可以执行以下操作:
>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
[3, 5],
[6, 8]])
#2楼
>>> test[:,0]
array([1, 3, 5])
该命令为您提供了行向量,如果您只想在其上循环,就可以了,但是如果您要与其他尺寸为3xN的数组进行堆叠,则可以
ValueError: all the input arrays must have same number of dimensions
而
>>> test[:,[0]]
array([[1],
[3],
[5]])
为您提供列向量,以便您可以进行串联或hstack操作。
例如
>>> np.hstack((test, test[:,[0]]))
array([[1, 2, 1],
[3, 4, 3],
[5, 6, 5]])
#3楼
>>> test
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> ncol = test.shape[1]
>>> ncol
5L
然后,您可以通过以下方式选择第二至第四列:
>>> test[0:, 1:(ncol - 1)]
array([[1, 2, 3],
[6, 7, 8]])
#4楼
您还可以转置并返回一行:
In [4]: test.T[0]
Out[4]: array([1, 3, 5])
#5楼
>>> test[:,0]
array([1, 3, 5])
同样,
>>> test[1,:]
array([3, 4])
使您可以访问行。 NumPy参考资料的第1.4节(索引)对此进行了介绍。 这很快,至少以我的经验而言。 它肯定比循环访问每个元素要快得多。
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3164217