2

How do I transform a Boolean array into an iterable of indexes?

E.g.,

import numpy as np
import itertools as it
x = np.array([1,0,1,1,0,0])
y = x > 0
retval = [i for i, y_i in enumerate(y) if y_i] 

Is there a nicer way?

1 Answer 1

3

Try np.where or np.nonzero.

x = np.array([1, 0, 1, 1, 0, 0])
np.where(x)[0] # returns a tuple hence the [0], see help(np.where)
# array([0, 2, 3])
x.nonzero()[0] # in this case, the same as above.

See help(np.where) and help(np.nonzero).

Possibly worth noting that in the np.where page it mentions that for 1D x it's basically equivalent to your longform in the question.

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

1 Comment

I knew there was a better way! I looked at "np.index*", but didn't find anything.

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.