我有以下 Python (NumPy),我想将其重构得更干净(并且可能更快):
temp = max(value for (x, y), value in np.ndenumerate(cm) if x * y < 100 and (x, y) != (0, 0) and not np.isnan(value))
我想我想做什么已经很清楚了。总而言之,我尝试根据二维数组的值和索引的某些条件来过滤二维数组的某些元素。
感谢任何帮助。
最佳答案
import numpy as np
from numpy.random import rand, randint
cm = rand(50, 100)
cm[randint(0, 50, 4000), randint(0, 100, 4000)] = np.nan
temp1 = max(value for (x, y), value in np.ndenumerate(cm) if x * y < 100 and (x, y) != (0, 0) and not np.isnan(value))
x, y = np.indices(cm.shape)
mask = (x * y < 100) & (x + y != 0) & (~np.isnan(cm))
temp2 = np.max(cm[mask])
assert temp1 == temp2
编辑
对于 max(x+y * 值)
:
np.max((x + y * cm)[mask])
或
np.max(x[mask] + y[mask] * cm[mask])
关于python - 有没有更好的方法来重写这个 NumPy 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21184609/