得到一个像下面这样的数据框,它的索引是 [date,assetName]如何在 10 天内添加带有开盘价的新列?日期索引列的数据类型是时间戳('2007-02-01 00:00:00+0000', tz='UTC')from datetime import datetimeimport pandas as pddatetime_object = datetime.strptime('Feb 1 2007', '%b %d %Y')market_df = pd.DataFrame({'date': [ datetime.strptime('Feb 1 2007', '%b %d %Y') ,datetime.strptime('Feb 1 2007', '%b %d %Y') ,datetime.strptime('Feb 1 2007', '%b %d %Y') ,datetime.strptime('Feb 11 2007', '%b %d %Y') ,datetime.strptime('Feb 11 2007', '%b %d %Y') ,datetime.strptime('Feb 11 2007', '%b %d %Y') ], 'assetName': ['AAPL', 'GOOGL', 'AMZN','AAPL', 'GOOGL', 'AMZN'], 'open': [20, 30.9, 40, 22.3, 35, 45], 'close': [20.5, 30.6, 40.5,22.3,35,45], })market_df = market_df.set_index(['date','assetName']) 如何使用新列“price_in_10_days”获取此数据框date assetName open close price_in_10_days2007-02-01 AAPL 20.0 20.5 22.32007-02-01 GOOGL 30.9 30.6 35.02007-02-01 AMZN 40.0 40.5 45.02007-02-11 AAPL 22.3 22.3 NaN2007-02-11 GOOGL 35.0 35.0 NaN2007-02-11 AMZN 45.0 45.0 NaN
1 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
我相信你需要创建DatetimeIndexby unstack,然后shift是10几天和最后stack:
market_df['price_in_10_days'] = market_df['open'].unstack().shift(-1, freq='10D').stack()
print (market_df)
open close price_in_10_days
date assetName
2007-02-01 AAPL 20.0 20.5 22.3
GOOGL 30.9 30.6 35.0
AMZN 40.0 40.5 45.0
2007-02-11 AAPL 22.3 22.3 NaN
GOOGL 35.0 35.0 NaN
AMZN 45.0 45.0 NaN
添加回答
举报
0/150
提交
取消