本文介绍了获取平均值以避免在python中使用numpy的nan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算避免nan的数组(A)的平均值?
How to calculate mean value of an array (A) avoiding nan?
import numpy as np
A = [5 nan nan nan nan 10]
M = np.mean(A[A!=nan]) does not work
Any idea?
推荐答案
>>> import numpy as np
>>> A = np.array([5, np.nan, np.nan, np.nan, np.nan, 10])
>>> np.isnan(A)
array([False, True, True, True, True, False], dtype=bool)
>>> ~np.isnan(A)
array([ True, False, False, False, False, True], dtype=bool)
>>> A[~np.isnan(A)]
array([ 5., 10.])
>>> A[~np.isnan(A)].mean()
7.5
因为您无法将nan
与nan
进行比较:
because you cannot compare nan
with nan
:
>>> np.nan == np.nan
False
>>> np.nan != np.nan
True
>>> np.isnan(np.nan)
True
这篇关于获取平均值以避免在python中使用numpy的nan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!