Skip to content

BUG: Duplicate index level in pd.DataFrame.groupby.expanding #47181

Closed
@TomasTurlik

Description

@TomasTurlik

Pandas version checks

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

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

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd 
df = pd.DataFrame([1,2,3,4,5,6],index=pd.MultiIndex.from_tuples([('A','a'),('A','b'),('A','c'),('B','a'),('B','b'),('B','c')]))
df.index.rename(('level_0','level_1'),inplace=True)

df.groupby("level_1").mean()

#           0
# level_1     
# a        2.5
# b        3.5
# c        4.5

df.groupby("level_1").expanding().mean()

#                           0
# level_1 level_0 level_1     
# a       A       a        1.0
#         B       a        2.5
# b       A       b        2.0
#         B       b        3.5
# c       A       c        3.0
#         B       c        4.5

Issue Description

I am not sure that this is the expected behavior as intuitively I would expect the index of the returning dataframe to be the same when using groupby.expanding.mean and groupby.mean.
EDIT: I don't mean literally the same but similar, keeping in mind the nature of 1st one returning vector and second one returning scalar

Expected Behavior

I would expect the previous code snippet to produce

print(df.groupby("level_1").expanding().mean())

                  0
level_1 level_0     
a       A       1.0
        B       2.5
b       A       2.0
        B       3.5
c       A       3.0
        B       4.5

Installed Versions

INSTALLED VERSIONS

commit : 4bfe3d0
python : 3.8.10.final.0
python-bits : 64
OS : Linux
OS-release : 5.4.0-110-generic
Version : #124-Ubuntu SMP Thu Apr 14 19:46:19 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.4.2
numpy : 1.21.5
pytz : 2021.3
dateutil : 2.8.2
pip : 22.1
setuptools : 44.0.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.8.0
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.3
IPython : 8.0.1
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : 2022.02.0
gcsfs : None
markupsafe : 2.0.1
matplotlib : 3.5.1
numba : 0.55.1
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : 7.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.0
snappy : None
sqlalchemy : 1.4.31
tables : None
tabulate : 0.8.9
xarray : None
xlrd : None
xlwt : None
zstandard : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions