I am looking for a way to binarize numpy N-d array based on the threshold using only one expression. So I have something like this:
np.random.seed(0) np.set_printoptions(precision=3) a = np.random.rand(4, 4) threshold, upper, lower = 0.5, 1, 0
a is now:
array([[ 0.02 , 0.833, 0.778, 0.87 ], [ 0.979, 0.799, 0.461, 0.781], [ 0.118, 0.64 , 0.143, 0.945], [ 0.522, 0.415, 0.265, 0.774]])
Now I can fire these 2 expressions:
a[a>threshold] = upper a[a<=threshold] = lower
and achieve what I want:
array([[ 0., 1., 1., 1.], [ 1., 1., 0., 1.], [ 0., 1., 0., 1.], [ 1., 0., 0., 1.]])
But is there a way to do this with just one expression?
Python Numpy – Create One Dimensional Array One dimensional array contains elements only in one dimension. In other words, the shape of the numpy array should contain only one value in the tuple. To create a one dimensional array in Numpy, you can use either of the array(), arange() or linspace() numpy functions.
We can create a 2D array by passing a list to the array() function of NumPy.
We may consider np.where
:
np.where(a>threshold, upper, lower) Out[6]: array([[0, 1, 1, 1], [1, 1, 0, 1], [0, 1, 0, 1], [1, 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