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

How to access the ith column of a NumPy multidimensional array?

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

Suppose I have:

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

test[i] gets me ith line of the array (eg [1, 2]). How can I access the ith column? (eg [1, 3, 5]). Also, would this be an expensive operation?

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

Similarly,

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

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.