5

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]

4 Answers 4

19

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]) 
Sign up to request clarification or add additional context in comments.

1 Comment

why 1-x? won't some 0 become -1?? is it because of the binary type? e.g. uint8?
5

Yes, you can use np.logical_not:

np.logical_not(x).astype(int) 

Output:

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

Comments

5

Or using XOR:

y = [n ^ 1 for n in x] 

Comments

2

Here's one way:

y = (x == 0).astype(int) 

Alternatively:

y = 0 + (x == 0) 

Output:

[0 1 0 1 1 0] 

Notes:

  1. (x == 0) gives a boolean array where False appears in the place of 1, and True appears in the place of 0.
  2. Calling the method astype(int), or adding scalar 0 to the matrix, converts False to 0 and True to 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.