2

I have a numpy array which stores a set of indices I need to access another numpy array.

I tried to use a for loop but it doesn't work as I expected.

The situation is like this:

>>> a
array([[1, 2],
       [3, 4]])
>>> c
array([[0, 0],
       [0, 1]])
>>> a[c[0]]
array([[1, 2],
       [1, 2]])
>>> a[0,0]         # the result I want
1

Above is a simplified version of my actual code, where the c array is much larger so I have to use a for loop to get every index.

1

2 Answers 2

3

Convert it to a tuple:

>>> a[tuple(c[0])]
1

Because list and array indices trigger advanced indexing. tuples are (mostly) basic slicing.

Sign up to request clarification or add additional context in comments.

Comments

1

Index a with columns of c by passing the first column as row's index and second one as column index:

In [23]: a[c[:,0], c[:,1]]
Out[23]: array([1, 2])

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.