Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert 0 and 1 in a binary array

Tags:

python

numpy

Is there a function in Numpy to invert 0 and 1 in a binary array? If

a = np.array([0, 1, 0, 1, 1])

I would like to get:

b = [1, 0, 1, 0, 0]

I use:

b[a==0] = 1
b[a==1] = 0

but maybe it already exist something in Numpy to do this.

like image 421
floflo29 Avatar asked Aug 26 '16 11:08

floflo29


3 Answers

you can simply do:

In[1]:b=1-a
In[2]:b
Out[2]: array([1, 0, 1, 0, 0])

or

In[22]:b=(~a.astype(bool)).astype(int)
Out[22]: array([1, 0, 1, 0, 0])
like image 86
shivsn Avatar answered Oct 13 '22 22:10

shivsn


A functional approach:

>>> np.logical_not(a).astype(int)
array([1, 0, 1, 0, 0])
like image 39
Mazdak Avatar answered Oct 13 '22 22:10

Mazdak


In Python 3, suppose

a = [1]
a.append(a[0]^1)
print(a)

Output will be:

[1,0]

Thus if you apply a loop:

for i in range(len(a)):
    a.append(a[i]^1)

all the elements of the list will be inverted.

like image 37
WasimKhan Avatar answered Oct 13 '22 22:10

WasimKhan