如何访问NumPy多维数组的第i列?

筅森魡賤 提交于 2020-02-28 01:50:28

假设我有:

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节(索引)对此进行了介绍。 这很快,至少以我的经验而言。 它肯定比循环访问每个元素要快得多。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!