Home > Net >  Numpy: nanargmin select indice of 0 if row contains all NaN
Numpy: nanargmin select indice of 0 if row contains all NaN

Time:03-02

Given the following matrix:

matrix = np.array([[0,np.nan,1],[np.nan,np.nan,np.nan],[1,2,3]])

I would like to obtain an array of min row values. In the case that a row contains all nan values, that indice for that row of all nan values should be 0. The reslting array should be.

array([0,0,0])

If I try to use np.argmin(matrix,axis=1) then the min indice is where np.nan occurs e.g:

array([1, 0, 0])

This is not desired, and if I use np.nanargmin(matrix,axis=1) I get raise ValueError("All-NaN slice encountered")

CodePudding user response:

Fill the NaNs with infinity using numpy.nan_to_num, then get the argmin:

np.argmin(np.nan_to_num(matrix, nan=float('inf')), axis=1)

output: array([0, 0, 0])

CodePudding user response:

you can convert your array into a masked array, where all np.nans are masked and then get the argmin of that array:

np.ma.masked_invalid(matrix).argmin(axis=1)

output: array([0, 0, 0], dtype=int64)

  • Related