Python Pandas:使用算法进行正向填充

时间:2019-01-20 22:34:41

标签: python pandas dataframe fillna

我有以下DataFrame:

            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_index('date').sort_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

1 个答案:

答案 0 :(得分: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