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

2024-04-25 14:56:52 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有:

test = numpy.array([[1, 2], [3, 4], [5, 6]])

test[i]获取数组的行(例如[1, 2])。如何访问列?(例如[1, 3, 5])。另外,这会不会是一个昂贵的手术?


Tags: testnumpy数组array手术
3条回答
>>> test[:,0]
array([1, 3, 5])

同样地

>>> test[1,:]
array([3, 4])

允许您访问行。这在NumPy reference的1.4节(索引)中介绍。这很快,至少以我的经验来看。它当然比访问循环中的每个元素快得多。

>>> 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]])

如果一次要访问多个列,可以执行以下操作:

>>> 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]])

相关问题 更多 >