首页 > 解决方案 > 第一次出现日期时间索引

问题描述

我有一个名为 Rolling_Max 的 DateTime 索引数据框。它给出了从 2011 年 1 月 1 日到 21 年 1 月 1 日每天的过去 2520 天最大值(价格)。如何向其中添加一个列,其中包含每个最大值首次出现的日期?

dfsp = pdr.get_data_yahoo('^GSPC', start='2011-01-01', end='2021-01-01')['Adj Close']
window = 2520
Roll_Max = dfsp.rolling(window, min_periods=1).max()

第二行应该有另一列写着“2011-01-03”

标签: pythonpandasnumpydatetime

解决方案


你可以试试这个,假设价格是 pd.Series

price_argmax = price.reset_index(drop=True).rolling(2520, min_periods=130).apply(lambda x: x.index[x.argmax()])
price_argmax = pd.Series(price.index[price_argmax.dropna().astype("int")], index = price.index[price_argmax.dropna().index]).reindex(price.index)

如果你需要这个速度很快,那么你可能想用 numba/numpy 编写一个循环。


推荐阅读