将 rolling() 应用于 groupby pandas 对象时会复制多索引

Multiindex duplicated when rolling() applied on a groupby pandas object

我有一个错误:

x.field.rolling(window=5,min_periods=1).mean() 其中 x 是一个 pandas.core.groupby.groupby.DataFrameGroupBy 对象。

我尝试了此 page 中提出的解决方案。所以我这样做了:

x.field.apply(lambda x: x.rolling(window=5,min_periods=1).mean())

与上面介绍的网页相反,我仍然得到同样的错误。

+---------+---------+-------+--------------------+
| machin  | machin  | truc  | a column of series |
+---------+---------+-------+--------------------+
| machin1 | machin1 | truc1 | 1                  |
|         |         | truc2 | 2                  |
|         |         | truc3 | 3                  |
|         |         | truc4 | 4                  |
| machin2 | machin2 | truc1 | 100                |
|         |         | truc2 | 99                 |
|         |         | truc3 | 98                 |
+---------+---------+-------+--------------------+

如您所见,列索引 'machin' 是重复的,而在使用滚动方法之前它显示正确。

例如让我们写x.field.apply(lambda x: x+1)。它returns:

+---------+-------+--------------------+
| machin  | truc  | a column of series |
+---------+-------+--------------------+
| machin1 | truc1 | 2                  |
|         | truc2 | 3                  |
|         | truc3 | 4                  |
|         | truc4 | 5                  |
| machin2 | truc1 | 101                |
|         | truc2 | 100                |
|         | truc3 | 99                 |
+---------+-------+--------------------+

所以没有重复,没有错误。它表明这确实是 rolling() 方法的一个问题。

这里有一些代码可以帮助你重现我的计算

import pandas as pd

#creation of records
rec=[{'machin':'machin1',
    'truc':['truc1','truc2','truc3','truc4'],
    'a column':[1,2,3,4]},
    {'machin':'machin2',
    'truc':['truc1','truc2','truc3'],
    'a column':[100,99,98]}]

#creation of pandas dataframe
df=pd.concat([pd.DataFrame(rec[0]),pd.DataFrame(rec[1])])

#creation of multi-index
df.set_index(['machin','truc'],inplace=True)

#creation of a groupby object
x=df.groupby(by='machin')

#rolling computation. Note that to do x.field or x['field'] is the same, and gives same bug as I checked.
x['a column'].rolling(window=5,min_periods=1).mean()

#rolling with apply and lambda, gives same bug
x['a column'].apply(lambda x:x.rolling(window=5,min_periods=1).mean())

#making apply and lambda alone gives no bug
a=x['a column'].apply(lambda x: x+1)

我试过的其他解决方案

我试图重置系列的索引,doc here

a.reset_index(name='machin')

它引发了一个异常:ValueError: cannot insert machin, already exists

虽然您可以在多索引的名称值中看到 'machin':

a.index
MultiIndex(levels=[['machin1', 'machin2'], ['machin1', 'machin2'],  ['truc1', 'truc2', 'truc3', 'truc4']],
       labels=[[0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 3, 0, 1, 2]],
       names=['machin', 'machin', 'truc'])

我也试过 drop,doc here:

a.drop(index='machin')
a.drop(index=0)

它引发异常:KeyError: 'machin'KeyError: 0

我的版本

Python 3.7.1(默认,2018 年 12 月 14 日,19:28:38)在 anaconda 环境中,甚至在终端中:[GCC 7.3.0] :: Anaconda, Inc. on linux

pandas 0.23.4

使用groupbygroup_keys参数:

df.groupby('machin', group_keys=False).rolling(window=5, min_periods=1).mean()

或者,您可以使用 reset_index:

删除滚动插入的第 0 级
df.groupby('machin').rolling(window=5, min_periods=1).mean().reset_index(level=0, drop=True)   

任一输出:

               a column
machin  truc           
machin1 truc1       1.0
        truc2       1.5
        truc3       2.0
        truc4       2.5
machin2 truc1     100.0
        truc2      99.5
        truc3      99.0