Invert Binary Numpy Array
is there a kind of 'logical no' for numpy arrays (of numbers of course). For example, consider this array: x = [1,0,1,0,0,1] i am looking for an easy way to compute its 'inverse' y
Solution 1:
For an array of 1s
and 0s
you can simply subtract the values in x
from 1
:
x = np.array([1,0,1,0,0,1])
1-x
# array([0, 1, 0, 1, 1, 0])
Or you could also take the bitwise XOR
of the binary values in x
with 1
:
x^1
# array([0, 1, 0, 1, 1, 0])
Solution 2:
Solution 3:
Or using XOR:
y = [n ^ 1 for n in x]
Solution 4:
Here's one way:
y = (x == 0).astype(int)
Alternatively:
y = 0 + (x == 0)
Output:
[0 1 0 1 1 0]
Notes:
(x == 0)
gives a boolean array whereFalse
appears in the place of1
, andTrue
appears in the place of0
.- Calling the method
astype(int)
, or adding scalar0
to the matrix, convertsFalse
to0
andTrue
to1
Post a Comment for "Invert Binary Numpy Array"