我有一个熊猫TimeSeries,并希望将argmax函数应用于滚动窗口。但是,由于casting从rolling_apply浮动,如果我应用numpy.argmax()
,我只能获得ndarray片的索引。有没有办法将滚动argmax应用于Series/DataFrame?在熊猫中滚动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])
但也许有一些 “pandonic” 的方式?
请在这里举一个例子输入串联,并显示您的大熊猫版本 – Jeff 2015-04-01 15:10:40
和熊猫的版本是0.16.0 – poeticcapybara 2015-04-01 20:57:04