先说重要的事这不是NumPy: calculate averages with NaNs removed的副本,我会解释为什么:
假设我有一个数组
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
。我能避免这种情况吗?原则上,我想忽略nans,所以我想有这样的东西:
a = array([1,2,4])
weights = [4,3,1]
output = average(a, weights=weights)
print output
1.75
6条答案
按热度按时间rhfm7lfc1#
或者,您可以像这样使用MaskedArray:
esbemjvw2#
首先找出不是
nan
的索引,然后将a
和weights
的过滤版本传递给numpy.average
:正如@mtrw在评论中建议的那样,在这里使用掩码数组而不是索引数组会更干净:
au9on6nz3#
我会提供另一种解决方案,这是更可扩展到更大的尺寸(例如,当做平均在不同的轴)。附加的代码与2D数组一起工作,其中可能包含nans,并且平均超过
axis=0
。vfhzx4xs4#
扩展@Ashwini和@Nicolas的答案,这里有一个版本,也可以处理所有数据值都是np.nan的边缘情况,并且设计用于pandas DataFrame而没有类型相关的问题:
vtwuwzda5#
上面的所有解决方案都很好,但没有处理权值中有nan的情况。为此,使用pandas:
oewdyzsn6#
既然你在寻找平均值,另一个想法是简单地用0替换所有的nan值:
这可以与平均函数的轴功能一起使用,但要小心,您的权重总和不为0。