Reputation: 23
I'm searching for an efficient way to do this with 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).
So in this case, the output should be:
[[False, True, True]
[False, False, True]
[True, True, True]]
Is there any efficient way to do this in numpy?
Upvotes: 1
Views: 984
Reputation: 4929
Use:
a1 > a2.max(axis=1, keepdims=True)
where a1
is your first array, and a2
the second one.
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.
Upvotes: 2