1

Let's say I have an array:

a = np.array([1,2,3,4,5])

And then I have a Boolean array

b = np.array([False, False, True, True, True])

I would like the values of 'True' in b to make the values in a = 0, otherwise, retain the values of a. In other words, I want something like:

c = a[b]

except this deletes any instances of 'False'. I would want the answer to be [1,2,0,0,0]

2 Answers 2

2

You can use np.where():

>>> np.where(b, 0, a)
array([1, 2, 0, 0, 0])
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to modify a in place, assigning to a indexed by the boolean array of matching length only replaces the values that are True:

>>> a[b] = 0
>>> a
array([1, 2, 0, 0, 0])

~ inverts a boolean array, so it's trivial to replace where the values are False instead:

>>> a[~b] = 0  # Assume we reinitialized a to the original state
>>> a
array([0, 0, 3, 4, 5])

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.