1

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

1 Answer 1

3

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.