0

Lets say I have a numpy array as below:

array([ 1. ,  2. ,  0. ,  3.4,  0. ,  1.1])

Now I want to get indices of all the elements which are zero. Reason being I want to get those indices and then for a different array I want to convert the elements on same indices to zero.

To get indices of non zero I know we can use nonzero or argwhere.

np.nonzero(a)

(array([0, 1, 3, 5]),)

Then lets say I have array b I can use the above indices list and convert all the elements of array b with same indices to zero like below:

b[np.nonzero(a)]=0

This is fine but it is for non zero indices. How to get for zero indices.

1 Answer 1

4

If you just want to use the result for indexing purposes, it's more efficient to make a boolean array than an array of indices:

a == 0

You can index with that the same way you would have used the array of indices:

b[a == 0] = 0

If you really want an array of indices, you can call np.nonzero on the boolean array:

np.nonzero(a == 0)

np.where also works.

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.