我有一个一维数组,我想获得超过某个阈值的所有值的平均值。在 excel 中,等价物是
= AVERAGEIF(range,">6")
在 python 中,我想出了这行工作正常,但我想知道是否有更好的方式来编写它
a = np.array([5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 1.0, 2.0, 3.0, 4.0])
indice = 6
b = sum(i for i in a if i > indice)/sum(a > indice)
print b
>>> 8.0
是否有任何更聪明的方法来做到这一点,或者使用一些 numpy 函数?
谢谢
请您参考如下方法:
这不是最直接的方法(@coldspeed 的回答解决了这个问题),但我只是为了好玩而尝试考虑替代方案。使用 np.average,将权重设置为 a > 6 的 bool 数组:
>>> np.average(a, weights=a>6)
8.0
