【问题标题】:apply to a rolling window function loses column names应用于滚动窗口函数会丢失列名
【发布时间】:2021-10-30 11:13:52
【问题描述】:

我有一个接受dataframe 的函数:

def max_dd(df):
    print(df)

    return None

如果我在将print df.head() 传递给max_dd 之前,它看起来像这样:

print(df.head())

            Close
Date
2010-08-10   7.95
2010-08-11   7.67
2010-08-12   7.72
2010-08-13   7.64
2010-08-16   7.59

但是,如果我现在将 df 传递给 max_dd

new = df.rolling(45).apply(max_dd)

函数打印:

Date
2010-08-10    7.95
2010-08-11    7.67
2010-08-12    7.72
2010-08-13    7.64
2010-08-16    7.59

为什么它丢失了Close 列名,我该如何找回它?

【问题讨论】:

    标签: python pandas rolling-computation


    【解决方案1】:

    Rolling.apply func 不接收 DataFrame 作为参数,而是接收 Series:

    def max_dd(df):
        print(df)
        print(type(df))
    
        return None
    
    new = df.rolling(45).apply(max_dd)
    

    输出:

    Date
    2010-08-10    7.95
    2010-08-11    7.67
    2010-08-12    7.72
    2010-08-13    7.64
    2010-08-16    7.59
    dtype: float64
    <class 'pandas.core.series.Series'>  # <- Not a DataFrame but a Series
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多