如何访问NumPy多维数组的第i列?
给定:
test = np.array([[1, 2], [3, 4], [5, 6]])
test[i]
可以得到第 i 行的数据(比如说 [1, 2]
)。那么我该怎么获取第 i 列的数据呢?(比如说 [1, 3, 5]
)。另外,这样的操作会不会很耗费资源呢?
10 个回答
93
如果你想一次访问多个列,可以这样做:
>>> 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]])
104
>>> test[:,0]
array([1, 3, 5])
这个命令会给你一个行向量,如果你只是想遍历它,那没问题,但如果你想把它和一个维度为3xN的其他数组横向拼接,就会遇到问题。
ValueError: all the input arrays must have same number of dimensions
而
>>> test[:,[0]]
array([[1],
[3],
[5]])
则会给你一个列向量,这样你就可以进行拼接或者横向拼接的操作。
例如:
>>> np.hstack((test, test[:,[0]]))
array([[1, 2, 1],
[3, 4, 3],
[5, 6, 5]])
986
使用:
test = np.array([[1, 2], [3, 4], [5, 6]])
要访问第0列:
>>> test[:, 0]
array([1, 3, 5])
要访问第0行:
>>> test[0, :]
array([1, 2])
这部分内容在NumPy参考文档的第1.4节(索引)中有介绍。根据我的经验,这种方法很快。比起在循环中一个一个地访问每个元素,这种方法肯定要快得多。