Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 818
lpl Avatar asked Dec 15 '10 21:12

lpl


People also ask

How do you access the elements of a NumPy Matrix?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do I access NumPy Ndarray?

N-Dimensional array(ndarray) in Numpy An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.


1 Answers

>>> 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.

like image 120
mtrw Avatar answered Sep 18 '22 09:09

mtrw