python 在np数组维度上__兰德__

pkln4tw6  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(159)

如何基于运算符o比较valarr中的值?

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]])

对于每个val_i,在val_i_jarr_j中的所有元素之间应用运算符o_j。将得到的向量与__rand__进行比较。
目前的解决办法似乎太难了。

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))
kmbjn2e3

kmbjn2e31#

您可以尝试以下操作:

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)

它给出:

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

相关问题