Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change 1's to 0 and 0's to 1 in numpy array without looping

Tags:

python

numpy

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?

like image 682
JustANoob Avatar asked Jun 14 '19 08:06

JustANoob


1 Answers

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]])
like image 68
yatu Avatar answered Oct 26 '22 06:10

yatu