首先,第一件事:这不是NumPy的副本:计算去除NaN的平均值,我将解释原因:
假设我有一个数组
a = array([1,2,3,4])
我想用权重取平均值
weights = [4,3,2,1]
output = average(a, weights=weights)
print output
2.0
好。因此,这非常简单。但是现在我有这样的事情:
a = array([1,2,nan,4])
当然,用通常的方法计算平均值nan
。我可以避免吗?原则上,我想忽略nan,所以我想要这样的东西:
a = array([1,2,4])
weights = [4,3,1]
output = average(a, weights=weights)
print output
1.75
先找项目无法索引nan
,然后通过的过滤版本a
,并weights
到numpy.average
:
>>> import numpy as np
>>> a = np.array([1,2,np.nan,4])
>>> weights = np.array([4,3,2,1])
>>> indices = np.where(np.logical_not(np.isnan(a)))[0]
>>> np.average(a[indices], weights=weights[indices])
1.75
正如@mtrw在评论中所建议的那样,在这里使用掩码数组而不是索引数组会更干净:
>>> indices = ~np.isnan(a)
>>> np.average(a[indices], weights=weights[indices])
1.75
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句