How to compare values in val
against arr
based on operators o
?
import numpy as np
from operator import gt, lt
val = np.array([[3,7,1], [4,8,5], [5,10,3]])
arr = np.array([[1,2,3,4,5], [6,7,8,9,10], [9,7,5,3,1]])
o = (gt, gt, lt)
# [3,7,1]
# (3 gt [1,2,3,4,5]) & (7 gt [6,7,8,9,10] & (1 lt [9,7,5,3,1])
# [True, True, False, False, False] & [True, False, False, False, False] & [True, True, True, True, False]
# => [True, False, False, False, False]
# [4,8,5]
# (4 gt [1,2,3,4,5]) & (8 gt [6,7,8,9,10] & (5 lt [9,7,5,3,1])
# => [True, True, False, False, False]
# [5,10,3]
# (5 gt [1,2,3,4,5]) & (10 gt [6,7,8,9,10]) & (3 lt [9,7,5,3,1])
# => [True, True, True, False, False]
result = np.array([[True, False, False, False, False],
[True, True, False, False, False],
[True, True, True, False, False]])
For each val_i
, operator o_j
is applied between val_i_j
and all elements in arr_j
. The resulting vectors are compared with __rand__
.
Current solution seems too difficult.
out = []
for i in range(len(val)):
m = o[0](val[i][0], arr[0])
print(val[i][0], m)
for j in range(len(o)):
if j > 0:
m &= o[j](val[i][j], arr[j])
print(val[i][j], m)
out.append(list(mask))
CodePudding user response:
You can try this:
import numpy as np
val = np.array([[3,7,1], [4,8,5], [5,10,3]])
arr = np.array([[1,2,3,4,5], [6,7,8,9,10], [9,7,5,3,1]])
o = (np.greater, np.greater, np.less)
out = np.logical_and.reduce([o[i](val[:, i, None], arr[i]) for i in range(len(o))])
print(out)
It gives:
[[ True False False False False]
[ True True False False False]
[ True True True False False]]