Return 来自 pandas 滚动应用函数的多个值

Return multiple values from a pandas rolling apply function

我有一个 function 需要 return 多个值:

def max_dd(ser):
...

    compute i,j,dd

    return i,j,dd

如果我有这样的代码调用此函数并传入 series:

 date1, date2, dd = df.rolling(window).apply(max_dd)

但是,我得到一个错误:

pandas.core.base.DataError: No numeric types to aggregate

如果我 return 来自 max_dd 的单个值,一切都很好。我如何 return 来自已“apply”的函数的多个值?

滚动应用只能生成单个数值。滚动应用不支持多个 returns 甚至非数字 returns(就像像字符串一样简单的东西)。这个问题的任何答案都可以解决。

也就是说,一个可行的解决方法是利用 rolling 对象是可迭代的这一事实(从 pandas 1.1.0 开始)。

What’s new in 1.1.0 (July 28, 2020)

  • 使pandas.core.window.rolling.Rolling和pandas.core.window.expanding.Expanding可迭代(GH11704)

意味着可以利用滚动函数更快的分组和索引操作,但通过 python:

获得更灵活的行为
def some_fn(df_):
    """
    When iterating over a rolling window it disregards the min_periods
    argument of rolling and will produce DataFrames for all windows
    
    The input is also of type DataFrame not Series
    
    You are completely responsible for doing all operations here,
    including ignoring values if the input is not of the correct shape
    or format
    
    :param df_: A DataFrame produced by rolling
    :return: a column joined, and the max value within the window
    """
    return ','.join(df_['a']), df_['a'].max()


window = 5
results = pd.DataFrame([some_fn(df_) for df_ in df.rolling(window)])

示例数据帧和输出:

df = pd.DataFrame({'a': list('abdesfkm')})

df:

   a
0  a
1  b
2  d
3  e
4  s
5  f
6  k
7  m

result:

           0  1
0          a  a
1        a,b  b
2      a,b,d  d
3    a,b,d,e  e
4  a,b,d,e,s  s
5  b,d,e,s,f  s
6  d,e,s,f,k  s
7  e,s,f,k,m  s