I have a 2D numpy array with 'n' unique values. I want to produce a binary matrix, where all values are replaced with 'zero' and a value which I specify is assigned as 'one'.
For example, I have an array as follows and I want all instances of 35 to be assigned 'one':
array([[12, 35, 12, 26],
[35, 35, 12, 26]])
I am trying to get the following output:
array([[0, 1, 0, 0],
[1, 1, 0, 0]])
what is the most efficient way to do it in Python?
import numpy as np
x = np.array([[12, 35, 12, 26], [35, 35, 12, 26]])
(x == 35).astype(int)
will give you:
array([[0, 1, 0, 0],
[1, 1, 0, 0]])
The == operator in numpy performs an element-wise comparison, and when converting booleans to ints True is encoded as 1 and False as 0.
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