kylerthecreator
kylerthecreator

Reputation: 1569

Flipping zeroes and ones in one-dimensional NumPy array

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.

Upvotes: 34

Views: 29949

Answers (5)

Mikolaj Buchwald
Mikolaj Buchwald

Reputation: 270

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 :(

Upvotes: 1

YXD
YXD

Reputation: 32511

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)

Upvotes: 15

John Greenall
John Greenall

Reputation: 1690

another superfluous option:

numpy.logical_not(a).astype(int)

Upvotes: 7

heltonbiker
heltonbiker

Reputation: 27575

answer = numpy.ones_like(a) - a

Upvotes: 2

gboffi
gboffi

Reputation: 25023

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]: 

Upvotes: 108

Related Questions