我有计算纯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 重写这个函数? 最佳答案
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
关于python - 有条件的 Numpy 均值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11084710/