当 roll() 应用于 groupby pandas 对象时,多索引重复

Avy*_*Wam 5 python pandas rolling-computation pandas-groupby

我有一个错误:

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

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

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                 |
+---------+---------+-------+--------------------+
Run Code Online (Sandbox Code Playgroud)

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

例如我们写x.field.apply(lambda x: x+1). 它返回:

+---------+-------+--------------------+
| machin  | truc  | a column of series |
+---------+-------+--------------------+
| machin1 | truc1 | 2                  |
|         | truc2 | 3                  |
|         | truc3 | 4                  |
|         | truc4 | 5                  |
| machin2 | truc1 | 101                |
|         | truc2 | 100                |
|         | truc3 | 99                 |
+---------+-------+--------------------+
Run Code Online (Sandbox Code Playgroud)

所以没有重复,没有错误。这表明这确实是方法的问题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)
Run Code Online (Sandbox Code Playgroud)

我尝试过的其他解决方案

我尝试重置该系列的索引,文档在这里

a.reset_index(name='machin')
Run Code Online (Sandbox Code Playgroud)

它引发了一个异常: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'])
Run Code Online (Sandbox Code Playgroud)

我也尝试过 drop,这里是文档

a.drop(index='machin')
a.drop(index=0)
Run Code Online (Sandbox Code Playgroud)

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

我的版本

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

熊猫0.23.4

ALo*_*llz 5

使用group_keys的参数groupby

df.groupby('machin', group_keys=False).rolling(window=5, min_periods=1).mean()
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下命令删除滚动插入的第 0 层reset_index

df.groupby('machin').rolling(window=5, min_periods=1).mean().reset_index(level=0, drop=True)   
Run Code Online (Sandbox Code Playgroud)

输出为:

               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
Run Code Online (Sandbox Code Playgroud)

  • 第一个选项对我不起作用。但第二个效果很好。谢谢。 (2认同)