Let's say I have a numpy array where I would like to swap all the 1's to 0 and all the 0's to 1 (the array will have other values, and there is nothing special about the 0's and 1's). Of course, I can loop through the array and change the values one by one.
Is there an efficient method you can recommend using? Does the np.where()
method have an option for this operation?
Here's one way using np.where
, and taking the bitwise XOR
of a given value when it is either 0
or 1
:
np.where((a==0)|(a==1), a^1, a)
For example:
a = np.array([[0,1,2,1], [1,2,0,3]])
print(a)
array([[0, 1, 2, 1],
[1, 2, 0, 3]])
np.where((a==0)|(a==1), a^1, a)
array([[1, 0, 2, 0],
[0, 2, 1, 3]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With