Search code examples
pythonaveragenan

How to take average between NaN values?


I have a simple list that contains numbers and NaN values. Is there a way to take the AVG between two NaN values? an example could be like this:

list = [NaN, 5, 6, 7, NaN, NaN, NaN, 6, 2, 8, 5, 4, NaN, NaN]

and I would expect an output like

Output = [6,5] 

Solution

  • Use the groupby from itertools -

    import numpy as np
    from itertools import groupby
    NaN = np.nan
    lst = [NaN, 5, 6, 7, NaN, NaN, NaN, 6, 2, 8, 5, 4, NaN, NaN]
    [np.mean(list(g)) for k, g in groupby(lst, key=lambda x: x is not NaN) if k]
    # [6.0, 5.0]