Warm tip: This article is reproduced from serverfault.com, please click

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

(python - How to access the ith column of a NumPy multidimensional array?)

发布于 2010-12-15 21:27:41

假设我有:

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

test[i]获取数组的第 i行(例如[1, 2])。如何访问第i列?(例如[1, 3, 5])。另外,这会是一项昂贵的操作吗?

Questioner
lpl
Viewed
0
361 2016-01-20 17:06:10
>>> test[:,0]
array([1, 3, 5])

相似地,

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

允许你访问行。这在NumPy 参考的第 1.4 节(索引)中有介绍这很快,至少根据我的经验。这肯定比访问循环中的每个元素要快得多。