计算非零值的平均值 [英] Computing average of non-zero values
本文介绍了计算非零值的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,从中我可以得到非零值的平均值.
I have lists from whose I what the average of non-zero values.
E.G
[2,2,0,0,0] -> 2
[1,1,0,1,0] -> 1
[0,0,0,9,0] -> 9
[2,3,0,0,0] -> 2.5
当前我正在这样做:
list_ = [1,1,0,1,0]
non_zero = [float(v) for v in list_ if v>0]
averge = sum(non_zero)/len(non_zero)
如何更有效地执行此操作?
How can I do this operation more efficiently?
推荐答案
If you start with a numpy array, you can use np.nonzero
to filter the array, then take the mean:
a = np.array([2,3,0,0,0])
average = a[np.nonzero(a)].mean()
您还可以通过布尔索引进行过滤,该索引似乎更快:
You could also filter by boolean indexing, which appears to be faster:
average = a[a!=0].mean()
您还可以使用a>0
轻松更改上述方法以过滤正值.
You could also easily change the method above to filter for positive values by using a>0
.
时间
使用以下设置:
a = np.random.randint(100, size=10**6)
我得到以下计时:
%timeit a[a!=0].mean()
100 loops, best of 3: 4.59 ms per loop
%timeit a[a.nonzero()].mean()
100 loops, best of 3: 9.82 ms per loop
这篇关于计算非零值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文