有条件的脾气暴躁 [英] Numpy mean with condition
本文介绍了有条件的脾气暴躁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有在纯python中计算平均速度的算法:
I have algorithm of calculating average speed in pure python:
speed = [...]
avg_speed = 0.0
speed_count = 0
for i in speed:
if i > 0: # I dont need zeros
avg_speed += i
speed_count += 1
if speed_count == 0:
return 0.0
return avg_speed / speed_count
有什么方法可以用Numpy重写此功能吗?
Is there any way to rewrite this functions with Numpy?
推荐答案
import numpy as np
def avg_positive_speed(speed):
s = np.array(speed)
positives = s > 0
if positives.any():
return s[positives].mean()
else:
return 0.
speed = [1., 2., 0., 3.]
print avg_positive_speed(speed)
# prints 2.0
print avg_positive_speed([0., 0.])
# prints 0.0
这篇关于有条件的脾气暴躁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文