30

I have a one-dimensional NumPy array that consists of zeroes and ones like so:

array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

I'd like a quick way to just "flip" the values such that zeroes become ones, and ones become zeroes, resulting in a NumPy array like this:

array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Is there an easy one-liner for this? I looked at the fliplr() function, but this seems to require NumPy arrays of dimensions two or greater. I'm sure there's a fairly simple answer, but any help would be appreciated.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
kylerthecreator
  • 1,509
  • 3
  • 15
  • 32
  • **Note:** Python has bools, and so does NumPy. Use them, not `0`/`1`, or `'0'`/`'1'`. – AMC Feb 15 '20 at 01:49

5 Answers5

102

There must be something in your Q that i do not understand...

Anyway

In [2]: from numpy import array

In [3]: a = array((1,0,0,1,1,0,0))

In [4]: b = 1-a

In [5]: print a ; print b
[1 0 0 1 1 0 0]
[0 1 1 0 0 1 1]

In [6]: 
gboffi
  • 22,939
  • 8
  • 54
  • 85
  • 4
    Nice and simple indeed, +1. The only potential issue is that it isn't easy to do in-place. Just because of that I prefer using bitwise XOR, `a = a ^ 1`, which lets you do `a ^= 1`. – Jaime Nov 12 '14 at 16:43
  • 1
    Why choose this over `numpy.logical_not()`, or `~`? Especially since OP is clearly using boolean values. – AMC Feb 15 '20 at 01:58
14

A sign that you should probably be using a boolean datatype

a = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.bool)
# or
b = ~a
b = np.logical_not(a)
YXD
  • 31,741
  • 15
  • 75
  • 115
7

another superfluous option:

numpy.logical_not(a).astype(int)
John Greenall
  • 1,670
  • 11
  • 17
2
answer = numpy.ones_like(a) - a
heltonbiker
  • 26,657
  • 28
  • 137
  • 252
1

I also found a way to do it:

In [1]: from numpy import array

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

In [3]: b = (~a.astype(bool)).astype(int)


In [4]: print(a); print(b)
[1 1 1 1 1 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]

Still, I think that @gboffi's answer is the best. I'd have upvoted it but I don't have enough reputation yet :(

Mikolaj Buchwald
  • 160
  • 4
  • 14
  • Welcome to Stack Overflow! If a question is already answered - especially if it's from 3 years ago(!) - please don't add a solution that you know is inferior than the one that was selected. Good luck! – GalAbra Jan 28 '18 at 19:25