Home > front end >  Python: How to sum entries in a list with `nan` entries and find mean
Python: How to sum entries in a list with `nan` entries and find mean

Time:07-08

I have a list with nan entries

import numpy as np
a = [1, 2, 3, 4, 5, 6]
b = [nan, 2, 3, nan, 5, 6]
c = [nan, 2, 3, 4, 5, 6]

data = [a,b,c]

I want to find the mean of items in the list by summing the ith entries in the list and dividing by the mean of all its non-NaN elements.

mean = np.mean(data) 

doesn't work since nan entries are found.

For instance in MATLAB mean([a;b;c],'omitnan') option is found.

Is there a similar function in Python?

Suggestions will be really helpful

CodePudding user response:

I think it is answer that you looking for.

np.nanmean(data,axis=1)

The np.nanmean is used to calculate the mean of array ignoring the NaN value.

https://www.geeksforgeeks.org/python-numpy-nanmean-function/

CodePudding user response:

Numpy offers a convenient function for that! Namely, nanmean(), that ignores any np.nan entries when computing the mean, i.e.

import numpy as np

np.nanmean(a)
>4.0
np.nanmean(b)
>4.0
np.nanmean(c)
>4.0

Moreover, nansum(), nanmin(), nanmax() etc. offer nan-insensitive analogues to sum(), min(), and max().

  • Related