我有daily_data
数据如下:
Close
Date
2022-06-01 148.710007
2022-05-31 148.839996
2022-05-27 149.639999
2022-05-26 143.779999
2022-05-25 140.520004
2022-05-24 140.360001
2022-05-23 143.110001
2022-05-20 137.589996
2022-05-19 137.350006
2022-05-18 140.820007
...
我然后做一个滚动百分比变化计算,sampleStr
= '180 D':
dfSeries = daily_data['Close'].rolling(resampleStr).apply(lambda x : (x[0] - x[-1])/x[0])
如果我打印这个,我得到这个:
Date
2022-06-01 0.000000
2022-05-31 -0.000874
2022-05-27 -0.006254
2022-05-26 0.033152
2022-05-25 0.055074
2022-05-24 0.056150
2022-05-23 0.037657
2022-05-20 0.074776
2022-05-19 0.076390
2022-05-18 0.053056
2022-05-17 -0.003564
2022-05-16 0.021317
2022-05-13 0.010759
2022-05-12 0.041356
2022-05-11 0.014861
2022-05-10 -0.039002
然而,我想将columns
添加到此以进行完整性检查,我想将x[0]
的日期(实际上我认为这已经存在),x[-1]
的日期,x[0]
的关闭和x[-1]
的关闭添加到dfSeries
。
我该怎么做?
似乎你只需要使用pd.concat
与shift
ed列
例如,如果您的窗口是3
,您可以执行
pd.concat([df['Close'].rolling(3).apply(lambda x : (x[0] - x[-1])/x[0]).reset_index(),
df.reset_index()['Date'].shift(-3).rename('Date in T-3'),
df.reset_index()['Close'].shift(-3).rename('Close in T-3')],
axis=1
)
表示您正在连接三个对象。第一个,是你在原帖中提供的结果;第二个是移位的Date
列;最后一个是移位的Close
列。