python - 有没有更好的方法来重写这个 NumPy 片段

标签 python numpy refactoring

我有以下 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/

相关文章:

python - 在 Python 中编写一个无限和(具有积分的函数)

java - 降低代码的复杂性

C - 客户端如何使用/访问多个实现?

python - 以下 Python 代码有什么问题?

python - 根据 SNR 在图像上添加白噪声

python - 如何使用 python 查找输入图像的直方图?

python - Coursera ML - 在 python 中实现正则化逻辑回归成本函数

python - 获取最大值出现的轴上的索引

Java - 调用对象的 get 方法比使用本地对象慢吗?

python - 为什么我无法在 Anaconda 中安装 Prettytable?