Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum non-zero value in each row of 2d numpy array [duplicate]

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.]
like image 311
Usman Tariq Avatar asked Jan 25 '23 20:01

Usman Tariq


2 Answers

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.])
like image 100
Scott Boston Avatar answered Jan 27 '23 09:01

Scott Boston


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]
like image 26
Ehsan Avatar answered Jan 27 '23 10:01

Ehsan