madschm
madschm

Reputation: 39

Masking minimum value in every column

I have the following matrix:

matrix = np.arange(24).reshape(4,6) 

I want to mask the minimum values in each column. The solution below masks the minimum values in every row when axis=1, however when axis=0 it only masks the min value in the first column.

matrix_masked = np.ma.masked_where(matrix == np.resize(matrix.min(axis=0),[matrix.shape[0],1]),matrix)

Is there something else I should change?

Upvotes: 0

Views: 177

Answers (1)

Henry Ecker
Henry Ecker

Reputation: 35686

The sums don't need reshaped into columns find the correct values on axis 0.

So Try without the resize:

import numpy as np

np.random.seed(5)
matrix = np.random.randint(0, 100, size=(4, 6))

matrix_masked = np.ma.masked_where(matrix == matrix.min(axis=0), matrix)

print("Matrix")
print(matrix)
print("Masked Matrix")
print(matrix_masked)
Matrix
[[99 78 61 16 73  8]
 [62 27 30 80  7 76]
 [15 53 80 27 44 77]
 [75 65 47 30 84 86]]
Masked Matrix
[[99 78 61 -- 73 --]
 [62 -- -- 80 -- 76]
 [-- 53 80 27 44 77]
 [75 65 47 30 84 86]]

Or @Corralien's suggestion use MaskedArray:

matrix_masked = np.ma.MaskedArray(matrix, matrix == np.min(matrix, axis=0))

Upvotes: 1

Related Questions