Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert binary numpy array

Tags:

python

numpy

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 = [0,1,0,1,1,0]

like image 690
inarighas Avatar asked Nov 27 '22 10:11

inarighas


2 Answers

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])
like image 128
yatu Avatar answered Dec 05 '22 15:12

yatu


Yes, you can use np.logical_not:

np.logical_not(x).astype(int)

Output:

array([0, 1, 0, 1, 1, 0])
like image 34
Scott Boston Avatar answered Dec 05 '22 14:12

Scott Boston