简体   繁体   English

检查矩阵中的所有值是否大于另一个矩阵中的匹配行

[英]Checking for all values in a matrix if they are greater than a matching row in another matrix

I'm searching for an efficient way to do this with numpy.我正在寻找一种使用 numpy 执行此操作的有效方法。 For example, I have the following matrix:例如,我有以下矩阵:

[[1, 2, 2]
 [2, 3, 4]
 [3, 4, 5]] 

and a second matrix, with the same amount of rows as the first one (not necessarily the same amount of columns though):和第二个矩阵,其行数与第一个矩阵相同(但列数不一定相同):

[[1, 1]
 [2, 3]
 [1, 1]]

So for each value in the first matrix, id like to evaluate if it's greater than the whole row of the second matrix in the same row position (for example, for the first value in the first matrix, 1, I'd like to check if it's greater than all the values in the first row of the 2nd matrix, so greater than [1 1] which is false. For the 2nd value in the first row, 2, I'd like to check if it's greater than all values in the first row in the second matrix, which is true, and so on).因此,对于第一个矩阵中的每个值,id 想评估它是否大于同一行 position 中第二个矩阵的整行(例如,对于第一个矩阵中的第一个值,1,我想检查如果它大于第二个矩阵的第一行中的所有值,那么大于 [1 1] 这是错误的。对于第一行中的第二个值 2,我想检查它是否大于所有值在第二个矩阵的第一行,这是真的,依此类推)。

So in this case, the output should be:所以在这种情况下,output 应该是:

[[False, True, True]
 [False, False, True]
 [True, True, True]]

Is there any efficient way to do this in numpy?在 numpy 中是否有任何有效的方法可以做到这一点?

Use:利用:

a1 > a2.max(axis=1, keepdims=True)

where a1 is your first array, and a2 the second one.其中a1是您的第一个数组,而a2是第二个数组。

Output: Output:

array([[False,  True,  True],
       [False, False,  True],
       [ True,  True,  True]])

The logic here is to reduce the second array to get the maximum value per row (while keeping its dimension), because if it's greater than the maximum value, it's greater then the whole row.这里的逻辑是减少第二个数组以获得每行的最大值(同时保持其维度),因为如果它大于最大值,则大于整行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM