Skip to content

BUG: Using df.groupby().rolling() when grouping by a MultiIndex level causes the MultiIndex to lose levels #41316

Closed
@Xnot

Description

@Xnot
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


When grouping a DataFrame which has a MultiIndex using the level parameter for groupby, performing any rolling operation will cause all MultiIndex levels except the one it was grouped by to be lost. This bug has been present since at least 1.1.5.

import pandas as pd

print(pd.__version__)
df = pd.DataFrame({"idx1": [1] * 5 + [2] * 5, "idx2": range(10), "value": range(10)})
df = df.set_index(["idx1", "idx2"])
test = df.groupby(level=0).rolling(2).mean()
print(test.index)

On version 1.2.4:

>>>1.2.4
>>>MultiIndex([(1,),
           (1,),
           (1,),
           (1,),
           (1,),
           (2,),
           (2,),
           (2,),
           (2,),
           (2,)],
          names=['idx1'])

On version 1.0.5:

>>>1.0.5
>>>MultiIndex([(1, 1, 0),
            (1, 1, 1),
            (1, 1, 2),
            (1, 1, 3),
            (1, 1, 4),
            (2, 2, 5),
            (2, 2, 6),
            (2, 2, 7),
            (2, 2, 8),
            (2, 2, 9)],
           names=['idx1', 'idx1', 'idx2'])

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 2cb9652
python : 3.9.4.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : Intel64 Family 6 Model 158 Stepping 10, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 1.2.4
numpy : 1.20.2
pytz : 2021.1
dateutil : 2.8.1
pip : 21.0.1
setuptools : 54.1.2
Cython : None
pytest : 6.2.4
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : 3.0.7
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : 1.4.13
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions