Python:使用算术进行正向填充
我有以下数据帧:Python:使用算术进行正向填充,python,pandas,dataframe,fillna,Python,Pandas,Dataframe,Fillna,我有以下数据帧: AAPL shares GOOG shares MSFT shares date 2019-01-01 NaN 10.0 NaN 2019-01-05 NaN NaN 15.0 2019-01-12 NaN NaN
AAPL shares GOOG shares MSFT shares
date
2019-01-01 NaN 10.0 NaN
2019-01-05 NaN NaN 15.0
2019-01-12 NaN NaN 7.0
2019-01-13 3.0 NaN NaN
2019-01-14 NaN -5.0 NaN
应用正向填充后:
print(df.set\u index('date').sort\u index().fillna(method='ffill').fillna(value=0))
我得到:
AAPL shares GOOG shares MSFT shares
date
2019-01-01 0.0 10.0 0.0
2019-01-05 0.0 10.0 15.0
2019-01-12 0.0 10.0 7.0
2019-01-13 3.0 10.0 7.0
2019-01-14 3.0 -5.0 7.0
我的问题是,有没有办法用简单的加法来填充?我想要的结果是:
AAPL shares GOOG shares MSFT shares
date
2019-01-01 0.0 10.0 0.0
2019-01-05 0.0 10.0 15.0
2019-01-12 0.0 10.0 22.0
2019-01-13 3.0 10.0 22.0
2019-01-14 3.0 5.0 22.0
您可以使用
cumsum
df.fillna(0).cumsum()
AAPLshares GOOGshares MSFTshares
date
2019-01-01 0.0 10.0 0.0
2019-01-05 0.0 10.0 15.0
2019-01-12 0.0 10.0 22.0
2019-01-13 3.0 10.0 22.0
2019-01-14 3.0 5.0 22.0
哦,我一开始误解了你的答案,看起来它有效!!我会在4分钟内接受你的回答,谢谢