问题是因为比较a == a.min(axis=1) 是将每个列 与每一行的最小值进行比较,而不是将每一行与最小值进行比较。这是因为a.min(axis=1) 返回一个向量而不是矩阵,其行为类似于Nx1 数组。因此,在广播时,== 运算符以列方式执行操作以匹配维度。
a == a.min(axis=1)
# array([[ True, False, False],
# [False, False, False],
# [False, False, True]], dtype=bool)
解决此问题的一种可能方法是将 resize 的结果 a.min(axis=1) 转换为列向量(例如 3 x 1 2D 数组)。
a == np.resize(a.min(axis=1), [a.shape[0],1])
# array([[ True, False, False],
# [ True, False, False],
# [False, False, True]], dtype=bool)
或者更简单地说,正如@ColonelBeuvel 所展示的那样:
a == a.min(axis=1)[:,None]
现在将其应用于您的整行代码。
a_masked = np.ma.masked_where(a == np.resize(a.min(axis=1),[a.shape[0],1]), a)
# masked_array(data =
# [[-- 11 5]
# [-- 9 9]
# [5 7 --]],
# mask =
# [[ True False False]
# [ True False False]
# [False False True]],
# fill_value = 999999)