熊猫-Groupby的滚动平均值

时间:2019-03-05 15:33:05

标签: python pandas

我是熊猫新手。 我有一个要查看Horse结果的数据框。 我正在尝试为每匹马在最近30天的列中获得位置完成结果的滚动平均值。这是来自数据帧的两匹马的示例:

        Horse            Position  OR   RaceDate    Weight
125283  cookie ring             4  59.0 2016-04-25  52.272727
126134  a boy named sue         7  46.0 2016-05-31  54.090909
137654  a boy named sue         4  49.0 2017-01-25  57.727273
138434  a boy named sue         8  48.0 2017-02-04  55.909091
138865  a boy named sue         2  48.0 2017-02-10  51.363636
140720  a boy named sue         3  50.0 2017-03-10  54.545455
141387  a boy named sue         7  49.0 2017-03-22  59.545455
143850  cookie ring             11  54.0 2017-05-25 56.818182
144203  cookie ring             9  54.0 2017-06-03  50.000000

因此,我需要对每匹马进行分组,然后对90天应用滚动平均值。我正在通过调用以下命令进行操作:

df['PositionAv90D'] = df.set_index('RaceDate').groupby('Horse').rolling("90d")['Position'].mean().reset_index()

但是这将返回一个包含3列的数据帧,并且仍然被索引到Horse中。此处的示例:

0          a b celebration 2011-08-24       3.000000
1          a b celebration 2011-09-15       4.500000
2          a b celebration 2012-05-29       4.000000
3        a beautiful dream 2016-10-21       2.333333
4        a big sky brewing 2008-04-11       2.000000
5        a big sky brewing 2008-07-08       7.500000
6        a big sky brewing 2008-08-11      10.000000
7        a big sky brewing 2008-09-20       9.000000
8        a big sky brewing 2008-12-30       4.333333
9        a big sky brewing 2009-01-21       3.666667
10       a big sky brewing 2009-02-20       3.777778

我需要一个索引与原始数据帧相同的列。

你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

使用set_index()将删除原始索引,因此请首先使用reset_index(),这将创建一个名为“ index”的新列,其中包含原始索引。然后在最后插入reset_index()(仅创建索引0、1、2 ...等)时,请使用set_index('index')返回到原始

因此,如果您执行以下操作,我认为它会起作用:

df['PositionAv90D'] = df.reset_index().set_index('RaceDate').groupby('Horse').rolling("90d")['Position'].mean().set_index('index')

一个简单的数据示例可以很好地对其进行测试,很难根据您提供的数据进行重新创建

编辑1:

由于您要切换索引,因此拆分起来会更容易一些,请参见下文,我创建了一些示例数据,我认为这些数据与您所获得的类似:

df = pd.DataFrame({'foo': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'bar': [1, 1, 1, 2, 2, 2, 3, 3, 3],
                   'baz': [11, 12, 13, 14, 15, 16, 17, 18, 19]},
                  index = [14, 15, 16, 17, 18, 19, 20, 21, 22])

df.reset_index(inplace=True)    # This gives us index 0,1,2... and a new col 'index'
df.set_index('baz', inplace=True)    # Replace with date in yours
# This next bit does the groupby and rolling, which will give a df 
# with a multi index of foo and baz, then reset_index(0) to remove the foo index level
# so that it matches the original df index so that you can add it as a new column
df['roll'] = df.groupby('foo')['bar'].rolling(3).sum().reset_index(0,drop=True)
df.reset_index(inplace=True)    # brings baz back into the df as a column
df.set_index('index', inplace=True)   # sets the index back to the original

这将在原始df中为您提供带有滚动值的新列。在我的示例中,由于窗口仅以idx =窗口大小开始,因此每个组中的前2个值都有NaN。因此,根据您的情况,每组的前89天为NaN。您可能需要添加其他步骤,才能从生成的DataFrame中仅选择最近30天