pythonnumpy

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


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")


Solution

  • 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])