Eric
Eric

Reputation: 837

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

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

Upvotes: 1

Views: 85

Answers (1)

mozway
mozway

Reputation: 260490

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

Upvotes: 1

Related Questions