I'm trying to find the smallest non-zero value in each row of a 2d numpy array but haven't been to find an elegant solution. I've looked at some other posts but none address the exact same problem e.g.
Minimum value in 2d array or Min/Max excluding zeros but in 1d array.
For example for the given array:
x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])
the answer would be:
[1., 4., 2.]
One way to do this is to re-assign the zeros to the np.inf, then take min per row:
np.where(x>0, x, np.inf).min(axis=1)
Output:
array([1., 4., 2.])
Masked arrays are designed exactly for these kind of purposes. You can leverage masking zeros from array (or ANY other kind of mask you desire) and do pretty much most of the stuff you do on regular arrays on your masked array now:
import numpy.ma as ma
mx = ma.masked_array(x, mask=x==0)
mx.min(1)
output:
[1.0 4.0 2.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