【问题标题】:Python pandas rolling mean without the window num fixed没有固定窗口编号的 Python pandas 滚动平均值
【发布时间】:2017-03-02 02:22:18
【问题描述】:

我希望添加两列 [std_dev, mean],其中的平均值样本会随着特定位置的日期继续而扩大。

location   date              temp    std_dev    mean
NY         2014-02-01        60      
NY         2014-02-02        55      
NY         2014-02-03        70      
NY         2014-02-04        80      
LA         2014-02-01        80      
LA         2014-02-02        85      
LA         2014-02-03        75       

我找到了一篇解释滚动平均值/标准的帖子,我能够将其应用于表格。但是,我收到 std_dev 错误,因为位置的大小不是固定值。如何在不固定的情况下引用窗口大小?

pandas rolling on a shifted dataframe

df['mean'] = df.groupby('location')['temp'].apply(pd.rolling_mean,4,min_periods=2).shift(1)

df['std_dev'] = df.groupby('location')['temp'].apply(pd.rolling_std,4,min_periods=2).shift(1)

非常感谢任何帮助!

【问题讨论】:

    标签: python pandas dataframe mean


    【解决方案1】:

    我认为您正在寻找expanding,例如

    >>> df
       temp location
    0    60       NY
    1    55       NY
    2    70       NY
    3    80       NY
    4    80       LA
    5    85       LA
    6    75       LA
    
    >>> expander = df.groupby('location').temp.expanding(min_periods=2)
    
    >>> orderify = lambda x: x.reset_index(level=0, drop=True).sort_index()
    
    >>> df['mean'], df['std'] = map(orderify, [expander.mean(), expander.std()])
    
    >>> df
      location  temp       mean        std
    0       NY    60        NaN        NaN
    1       NY    55  57.500000   3.535534
    2       NY    70  61.666667   7.637626
    3       NY    80  66.250000  11.086779
    4       LA    80        NaN        NaN
    5       LA    85  82.500000   3.535534
    6       LA    75  80.000000   5.000000
    

    注意:在expander 上使用.agg 会很好,但从0.19.2 版开始,groupby.rolling 或@987654329 上没有复杂的agg @,所以这是不可能的。见

    【讨论】:

    • 注意:我希望喜欢使用agg 更好地做到这一点,就像expander.agg(['mean', 'std']).. 但不支持IIUC。
    • 从 0.19.0 开始扩展对 .agg 的支持
    • @Jeff 我在 0.19.2,expander.agg(['mean', 'std'])->“Column(s) temp already selected”出现错误。我是不是用错了?
    • In [1]: pd.__version__ Out[1]: '0.19.2' In [2]: pd.Series(range(3)).expanding(2).agg(['sum','mean']) Out[2]: sum mean 0 NaN NaN 1 1.0 0.5 2 3.0 1.0
    猜你喜欢
    • 1970-01-01
    • 2016-05-01
    • 2019-09-09
    • 2020-12-19
    • 2018-05-11
    • 2018-05-23
    • 2020-07-12
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多