Home > Back-end >  How do I manipulate elements in a numpy array with a boolean array?
How do I manipulate elements in a numpy array with a boolean array?

Time:01-21

For instance, if I have

true_false = np.array([[True, False], [True, False]])
to_change = np.array([[10, 10], [10, 10]])

and I want to multiply the values in to_change that are True in the true_false array by 20, how would I do this without iterating through to_change?

I tried doing this by iterating through to_change and then indexing true_false which worked but I would like to do this faster without iteration.

CodePudding user response:

Simply use boolean indexing:

to_change[true_false] *= 20

Updated to_change:

array([[200,  10],
       [200,  10]])
  • Related