- A+

Category：Languages

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?

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]]) `