20

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.

floflo29
  • 2,261
  • 2
  • 22
  • 45
  • 6
    you can simply do `b=1-a`. – shivsn Aug 26 '16 at 11:05
  • possible duplicate of http://stackoverflow.com/questions/13728708/inverting-a-numpy-boolean-array-using – danidee Aug 26 '16 at 11:06
  • **Note:** Python has bools, and so does NumPy. Use them, not `0`/`1`, or `'0'`/`'1'`. – AMC Feb 15 '20 at 02:10
  • Does this answer your question? [Flipping zeroes and ones in one-dimensional NumPy array](https://stackoverflow.com/questions/26890477/flipping-zeroes-and-ones-in-one-dimensional-numpy-array) – AMC Feb 15 '20 at 02:10

4 Answers4

44

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])
shivsn
  • 7,680
  • 1
  • 26
  • 33
14

A functional approach:

>>> np.logical_not(a).astype(int)
array([1, 0, 1, 0, 0])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
4

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.

petezurich
  • 9,280
  • 9
  • 43
  • 57
WasimKhan
  • 41
  • 1
  • Hi @WasimKhan, thank you for your answer. Could you please improve clarity with [markdown editing](https://stackoverflow.com/editing-help)? – Leonard Aug 12 '20 at 05:36
1

Another funny approach:

b = 2**a % 2

It works since 2**0 = 1.

Lucas Meier
  • 369
  • 3
  • 6