stock_code merge_date MT
0 2 2007-07 0.715415
1 2 2007-08 NaN
2 2 2007-09 NaN
3 2 2007-10 NaN
4 2 2007-11 NaN
5 2 2007-12 NaN
6 2 2008-01 0.728448
7 2 2008-02 NaN
8 2 2008-03 NaN
9 2 2008-04 NaN
10 2 2008-05 NaN
11 2 2008-06 NaN
12 2 2008-07 0.569378
13 2 2008-08 NaN
14 2 2008-09 NaN
Above is a snapshot of the data available.
I would to like to fill the missing value by moving averages(MA) after groupby with a window of 6. I want the last filled NaN to consider in filling next one. So that, every filled NaN can be different since eighth block.
I have tried this:
mda["MT"] = mda.groupby("stock_code")['MT'].apply(lambda x: x.fillna(x.rolling(6, 1).mean()))
However, this dint worked out well for.
stock_code merge_date MT
0 2 2007-07 0.715415
1 2 2007-08 0.715415
2 2 2007-09 0.715415
3 2 2007-10 0.715415
4 2 2007-11 0.715415
5 2 2007-12 0.715415
6 2 2008-01 0.728448
7 2 2008-02 0.728448
8 2 2008-03 0.728448
9 2 2008-04 0.728448
10 2 2008-05 0.728448
11 2 2008-06 0.728448
12 2 2008-07 0.569378
13 2 2008-08 0.569378
14 2 2008-09 0.569378
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…