考虑到:

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

Test [i]给出第i行(例如[1,2])。如何访问第I列?(例如[1,3,5])。还有,这手术会很贵吗?


当前回答

你也可以转置并返回一行:

In [4]: test.T[0]
Out[4]: array([1, 3, 5])

其他回答

>>> test
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

>>> ncol = test.shape[1]
>>> ncol
5L

然后你可以这样选择第2 - 4列:

>>> test[0:, 1:(ncol - 1)]
array([[1, 2, 3],
       [6, 7, 8]])

这不是多维的。它是二维数组。您想要访问所需列的位置。

test = numpy.array([[1, 2], [3, 4], [5, 6]])
test[:, a:b]  # you can provide index in place of a and b

访问列0:

>>> test[:, 0]
array([1, 3, 5])

访问第0行:

>>> test[0, :]
array([1, 2])

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

要获得几个独立的列,只需:

> test[:,[0,2]]

你会得到第0列和第2列

你也可以转置并返回一行:

In [4]: test.T[0]
Out[4]: array([1, 3, 5])