【发布时间】:2021-05-10 20:10:19
【问题描述】:
我有一个 Pandas TimeSeries,想将 argmax 函数应用于滚动窗口。但是,由于从rolling_apply转换为float,如果我申请numpy.argmax(),我只能获得ndarray的切片的索引。有没有办法将滚动 argmax 应用于 Series/DataFrame?
Series.idxmax() 或 Series.argmax() 都返回一个 TimeStamp 对象,但
pandas.rolling_apply(Series, window=10,func=lambda x: pandas.Series(x).idxmax()) 只会返回 float64。
编辑: 这是一个例子:
import pandas as pd
import numpy as np
import pandas.io.data as web
import datetime
start = datetime.datetime(2001,1,1)
end = datetime.datetime.today()
close = web.DataReader('AAPL','yahoo',start,end).Close
close = close / close.shift(1) - 1
close.resample('W-MON').idxmax() # Timestamp object
close.resample('W-MON').argmax() # Timestamp object
pd.rolling_apply(close.resample('W-MON'), window=52, func=lambda x: pd.Series(x).argmax())
一种可行的方法是
ix = pd.rolling_apply(close, window=52, func=np.argmax)
ix = np.where(np.isnan(ix),0,ix)
ix = ix.astype(int)
new_index = close.index[52:].map(lambda x: close.index[np.argwhere(close.index==x)-52:np.argwhere(close.index==x)] [ix[np.argwhere(close.index==x)]])
pd.Series(new_index,index=close.index[52:]).apply(lambda x: x.flatten()[0])
但也许有一些“恐慌”的方式?
【问题讨论】:
-
请在此处提供一个示例输入系列并显示您的熊猫版本
-
而pandas版本是0.16.0