【问题标题】:How to calculate rolling mean on a GroupBy object using Pandas?如何使用 Pandas 计算 GroupBy 对象的滚动平均值?
【发布时间】:2015-10-18 14:23:15
【问题描述】:

如何使用 Pandas 计算 GroupBy 对象的滚动平均值?

我的代码:

df = pd.read_csv("example.csv", parse_dates=['ds'])
df = df.set_index('ds')
grouped_df = df.groupby('city')

grouped_df 的样子:

我想使用 Pandas 计算 GroupBy 对象中每个组的滚动平均值?

我试过 pd.rolling_mean(grouped_df, 3)。

这是我得到的错误:

AttributeError: 'DataFrameGroupBy' 对象没有属性 'dtype'

编辑:我是否可能使用 itergroups 并在迭代时计算每个组上每个组的滚动平均值?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以尝试遍历组

    In [39]: df = pd.DataFrame({'a':list('aaaaabbbbbaaaccccbbbccc'),"bookings":range(1,24)})
    In [40]: grouped = df.groupby('a')
    In [41]: for group_name, group_df in grouped:
       ....:     print group_name
       ....:     print pd.rolling_mean(group_df['bookings'],3)
       ....:     
    a
    0           NaN
    1           NaN
    2      2.000000
    3      3.000000
    4      4.000000
    10     6.666667
    11     9.333333
    12    12.000000
    dtype: float64
    b
    5           NaN
    6           NaN
    7      7.000000
    8      8.000000
    9      9.000000
    17    12.333333
    18    15.666667
    19    19.000000
    dtype: float64
    c
    13   NaN
    14   NaN
    15    15
    16    16
    20    18
    21    20
    22    22
    dtype: float64
    

    【讨论】:

      【解决方案2】:

      您希望左侧列中的日期和所有城市值作为单独的列。一种方法是在date 和city 上设置索引,然后取消堆栈。这相当于一个数据透视表。然后,您可以以通常的方式执行滚动平均值。

      df = pd.read_csv("example.csv", parse_dates=['ds'])
      df = df.set_index(['date', 'city']).unstack('city')
      rm = pd.rolling_mean(df, 3)
      

      我不建议使用函数,因为给定城市的数据可以简单地返回如下(: 返回所有行):

      df.loc[:, city]
      

      【讨论】:

      • 如何为每个城市或此“数据透视表”中的每一列应用函数?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 2021-11-08
      • 2015-07-03
      • 2021-06-04
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多