Python Pandas: 用算术前向填充
Python Pandas: Forward Fill with Arithmetic
我有以下数据框:
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
您可以查看 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
我有以下数据框:
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
您可以查看 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