pandas filling nans by mean of before and after non-nan values

后端 未结 2 1529
栀梦
栀梦 2020-12-05 23:33

I would like to fill df\'s nan with an average of adjacent elements.

Consider a dataframe:

df = pd.DataFrame({\'val\': [1,n         


        
2条回答
  •  离开以前
    2020-12-06 00:21

    Althogh in case of multiple nan's in a row it doesn't produce the exact output you specified, other users reaching this page may actually prefer the effect of the method interpolate():

    df = df.interpolate()
    
    print(df)
         val
    0    1.0
    1    2.5
    2    4.0
    3    5.0
    4    7.5
    5   10.0
    6    1.0
    7    2.0
    8    5.0
    9    6.3
    10   7.7
    11   9.0
    

提交回复
热议问题