Home > Enterprise >  Pandas column fill N/As with rolling mean
Pandas column fill N/As with rolling mean

Time:12-30

I have a pandas dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame({
                   'id': [1,2,3,4,5],
                   'rate': [0.5,0.4,0.5,np.nan,np.nan],
                  })

I'd like to replace NaNs in rate column with rolling mean of previous 3 values.

Expected output:

enter image description here

CodePudding user response:

You can try rolling to replace isna() values.

df.loc[df.rate.isna(),'rate'] = df['rate'].rolling(3, min_periods=1).mean()

CodePudding user response:

Try round rolling mean except remember the python behaviour of round() which is the fact that most decimal fractions can’t be represented exactly as a float

df =df.assign(rate=round(df['rate'].rolling(3,1).mean(),1))
  • Related