我有一个 Pandas TimeSeries 并且想将 argmax 函数应用于滚动窗口。但是,由于从rolling_apply 转换为float,如果我应用numpy.argmax()
,我只能获得ndarray 切片的索引。有没有办法将滚动 argmax 应用于系列/数据帧?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])
但也许有一些“ panic ”的方式?
最佳答案
这个不是ATM实现的,不过没那么难,看问题here
这是一种解决方法,基本上是“手动”应用,实际上应该非常有效。
In [59]: rc = close.resample('W-MON')
In [60]: def f(rc, i, l):
s = rc.iloc[(i*l):((i+1)*l)]
try:
return s.loc[[s.idxmax()]]
except:
return None
....:
In [61]: pd.concat([ f(rc, i, 52) for i in range(len(rc)) ])
Out[61]:
Date
2001-06-25 0.034350
2002-02-04 0.017548
2003-05-05 0.031083
2004-10-18 0.044588
2005-05-23 0.022959
...
2011-08-29 0.018310
2012-03-19 0.017339
2013-09-23 0.017571
2014-04-28 0.023196
2015-02-16 0.015051
Name: Close, dtype: float64
关于python - 在 Pandas 中滚动 argmax,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29391787/