1

This seems like a simple problem but I can't figure it out.

I have a numpy array of an arbitrary dimension (rank) N. I need to set a single element in the array to 0 given by the index values in a 1D array of length N. So for example:

import numpy as np
A=np.ones((2,2,2))
b=[1,1,1]

so at first I thought

A[b]=0

would do the job, but it did not. If I knew A had a rank of 3 it would be a simple case of doing this:

A[b[0],b[1],b[2]]=0

but the rank of A is not known until runtime, any thoughts?

1 Answer 1

3

Indexing in numpy has somewhat complicated rules. In your particular case this warning applies:

The definition of advanced indexing means that x[(1,2,3),] is fundamentally different than x[(1,2,3)]. The latter is equivalent to x[1,2,3] which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this is occurs.

Also recognize that x[[1,2,3]] will trigger advanced indexing, whereas x[[1,2,slice(None)]] will trigger basic slicing.

You want simple indexing (addressing a particular element), so you'll have to cast your list to a tuple:

A[tuple(b)] = 0

Result:

>>> A
array([[[ 1.,  1.],
        [ 1.,  1.]],

       [[ 1.,  1.],
        [ 1.,  0.]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful! I knew there would be some intuitive way to do it. Thanks again.

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.