Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy swap multiple elements in an array

I have a numpy array containing a random spread of 1s and 0s. I want to replace all the 1s with a 0 and all the zeros with a 1.

arr[arr == 0] = 2
arr[arr == 1] = 0
arr[arr == 2] = 1

I'm currently having to use a temporary value (2 in this case) in order to avoid all the 0s becoming 1s and then subsequently making the entire array full of 0s. Is there a more elegant/efficient way to do this?

like image 374
Legatro Avatar asked Nov 19 '18 21:11

Legatro


People also ask

How do you swap rows and columns in NumPy array?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.


2 Answers

You can calculate and store your Boolean indexers before overwriting any values:

ones = a == 1
zeros = a == 0

a[ones] = 0
a[zeros] = 1

The solution also works if you have values other than 0 and 1.


If you don't need an in place solution, you can use np.where:

a = np.where(ones, 0, np.where(zeros, 1, a))
like image 172
jpp Avatar answered Sep 29 '22 02:09

jpp


Here's a solution that's very specific to your problem, but should also be very fast. Given the array:

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

You can subtract 1 from all the values and multiply by negative 1:

>>> (a-1)*-1
array([[0, 1, 1, 0],
       [0, 0, 0, 1]])
like image 31
sacuL Avatar answered Sep 29 '22 02:09

sacuL