【问题标题】:Rolling argmax in pandas在熊猫中滚动 argmax
【发布时间】: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

标签: python pandas


【解决方案1】:

这不是ATM实现的,但是没那么难,看issuehere

这是一种变通方法,基本上是“手动”执行应用,实际上应该非常有效。

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

【讨论】:

  • 实际上我正在寻找的只是返回 's.idxmax()' 而不是 's.loc[[s.idxmax()]]'。仅 30 列 744 行就需要 1s =/
【解决方案2】:

仅当您使用 Numpy Extensions 库时,才能非常简单地获取 Pandas 数据帧的滚动 argmax。例如,可以像这样获得窗口大小为 3 的整数数据帧列的滚动 argmax:

import pandas as pd
import numpy as np

from numpy_ext import rolling_apply

def get_argmax (mx):
    return np.argmax(mx)
        

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))

window = 3
df['argmax_rolling3'] = rolling_apply(get_argmax, window, df.A.values)

这将产生如下示例输出:

    A      argmax_rolling3
0  34              NaN
1  65              NaN
2  65              1.0
3  42              0.0
4  57              0.0
5  30              1.0
6  95              2.0
7  16              1.0
8   7              0.0
9  98              2.0

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2021-03-19
    • 2018-07-30
    • 2018-06-26
    • 2017-03-30
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多