[SciPy-user] calculate average by excluding NaN value in Array

josef.pktd at gmail.com josef.pktd at gmail.com
Mon Mar 30 08:46:38 EDT 2009


On Mon, Mar 30, 2009 at 6:44 AM, David Cournapeau
<david at ar.media.kyoto-u.ac.jp> wrote:
> David Cournapeau wrote:
>> Ch B Komaki wrote:
>>
>>> Dear Sirs/Madams
>>> I wanna calculate average of some lists, but having Nan value makes
>>> difficult to calculate average of data , I wanna exclude the position
>>> has NaN.It should calculate  average of  the others instead  ;
>>> for example;
>>>
>>>
>>
>> nanmean should do what you want,
>>
>>
>
> which is in scipy.stats:
>
> import numpy as np
> from scipy.stats import nanmean
>
> nanmean(np.array([1, 2, 3, np.nan])) # should return 2.
>
> David


If you need to do more work with arrays that have nans or missing
values, then using masked arrays is more convenient and powerful.

e.g. numpy.ma.mean
help(numpy.ma)

Josef



More information about the SciPy-User mailing list