Home > Software design >  Python Boolean array set index value of True to 0
Python Boolean array set index value of True to 0

Time:09-14

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]

CodePudding user response:

You can use np.where():

>>> np.where(b, 0, a)
array([1, 2, 0, 0, 0])

CodePudding user response:

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])
  • Related