Home > Net >  Numpy: Fill matrix containing NaN's with minimum value from rows in the matrix
Numpy: Fill matrix containing NaN's with minimum value from rows in the matrix

Time:03-02

Given a matrix

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

Get a vector containing the minimum value for each row

vector_of_min_row_values = np.nanmin(matrix, axis=1)

How do you replace the NaN values in each row with the min values of the row. This should create a matrix like this:

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

CodePudding user response:

You could use numpy.where and reshaping of the numpy.nanmin output:

output_matrix = np.where(np.isnan(matrix), np.nanmin(matrix, 1)[:,None], matrix)

output:

array([[ 1.,  2.,  3.],
       [ 1.,  1.,  3.],
       [nan, nan, nan]])
  • Related