2015-04-01 86 views
0

我有一个熊猫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” 的方式?

+1

请在这里举一个例子输入串联,并显示您的大熊猫版本 – Jeff 2015-04-01 15:10:40

+0

和熊猫的版本是0.16.0 – poeticcapybara 2015-04-01 20:57:04

回答

2

这没有实现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 
+0

其实我一直在寻找的只是返回“s.idxmax()”而不是“s.loc [[s.idxmax()]]”。它只需要30行744行= / – poeticcapybara 2015-04-03 09:55:06