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?
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
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))
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With