Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

sql server - python: how to fill the missing value by moving average after groupby?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...