[英]Mask minimum values in matrix rows
I have this 3x3 matrix:我有这个 3x3 矩阵:
a=array([[ 1, 11, 5],
[ 3, 9, 9],
[ 5, 7, -3]])
I need to mask the minimum values in each row in order to calculate the mean of each row discarding the minimum values.我需要屏蔽每行中的最小值,以便计算每行丢弃最小值的平均值。 Is there a general solution?有没有通用的解决方案? I have tried with我试过
a_masked=np.ma.masked_where(a==np.ma.min(a,axis=1),a)
Which masks the minimum value in first and third row, but not the second row?哪个屏蔽了第一行和第三行的最小值,而不是第二行?
I would appreciate any help.我将不胜感激任何帮助。 Thanks!谢谢!
The issue is because the comparison a == a.min(axis=1)
is comparing each column to the minimum value of each row rather than comparing each row to the minimum values.问题是因为比较a == a.min(axis=1)
是将每一列与每一行的最小值进行比较,而不是将每一行与最小值进行比较。 This is because a.min(axis=1)
returns a vector rather than a matrix which behaves similarly to an Nx1
array.这是因为a.min(axis=1)
返回一个向量而不是一个矩阵,其行为类似于Nx1
数组。 As such, when broadcasting, the ==
operator performs the operation in a column-wise fashion to match dimensions.因此,在广播时, ==
运算符以列方式执行操作以匹配维度。
a == a.min(axis=1)
# array([[ True, False, False],
# [False, False, False],
# [False, False, True]], dtype=bool)
One potential way to fix this is to resize
the result of a.min(axis=1)
into column vector (eg a 3 x 1 2D array).解决此问题的一种潜在方法是将a.min(axis=1)
的结果resize
为列向量(例如 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)
Or more simply as @ColonelBeuvel has shown:或者更简单地如@ColonelBeuvel 所示:
a == a.min(axis=1)[:,None]
Now applying this to your entire line of code.现在将其应用于您的整行代码。
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)
What is with the min() function? min() 函数有什么用?
For every Row just do min(row) and it gives you the minimum of this list in your Case a row.对于每一行,只需执行 min(row) ,它就会在您的案例中为您提供此列表中的最小值一行。 Simply append this minimum in a list for all Minimum.只需将此最小值附加到所有最小值的列表中。
minList=[]最小列表=[]
for i in array: minList.append(min(i))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.