How to get values from a 2-d Array with indices

Question:

For example I have following 2-D array.

>>>np.array(((1,2),(3,4),(5,6))) 
>>>array([[1, 2],
          [3, 4],
          [5, 6]])

I want to get a element from each column. For example, I want to get 3 from 1st column, 6 from 2rd column.
How can do it with a indices[1,2]. 1 means 2rd element from 1st column, 2 means 3rd element from 2rd column

Asked By: Samuel

||

Answers:

You can do it with so-called fancy indexing:

In [57]: x = np.array(((1,2),(3,4),(5,6)))

# np.arange(x.shape[1]) gives [0,1], the column indices
# needed to select "one from each column"
In [58]: x[[1,2], np.arange(x.shape[1])]
Out[58]: array([3, 6])

Or you could use np.choose:

In [44]: np.choose([1,2], x)
Out[44]: array([3, 6])
Answered By: unutbu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.