Fix Python – How do I access the ith column of a NumPy multidimensional array?

Question

Asked By – lpl

Given:

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

test[i] gives the ith row (e.g. [1, 2]). How do I access the ith column? (e.g. [1, 3, 5]). Also, would this be an expensive operation?

Now we will see solution for issue: How do I access the ith column of a NumPy multidimensional array?


Answer

To access column 0:

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

To access row 0:

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

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.

This question is answered By – mtrw

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0