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

Viewed 1474

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.]
4 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.])

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]
# example data
x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])

# set all the values inside the maxtrix which are equal to 0, to *inf*
# np.inf represents a very large number
# inf, stands for infinity
x[x==0] = np.inf

# grep the lowest value, in each array (now that there is no 0 value anymore)
np.min(x, axis=1)

I solved this way that's time complexity is o(n^2) .

import numpy as np
x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])

for i in range(len(x)) :
    small=x[i][i]
    for j in x[i] :
        if (j!=0 and j<small):
            small=j
    print(small)
Related