Skip to content

BUG: df.MultiIndex.levels continues to return the index of the original df after mutation #59829

@lawrencefchan

Description

@lawrencefchan

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, 'a', 'foo'], [2, 'b', 'bar']]).set_index([0, 1])
print(df.index.levels[0])  # returns Index([1, 2], dtype='int64', name=0)

d1 = df.head(1)
print(d1.index.levels[0])  # returns Index([1, 2], dtype='int64', name=0)

d2 = df.drop((1, 'a'))
print(d2.index.levels)  # returns FrozenList([[1, 2], ['a', 'b']])

Issue Description

df.MultiIndex.levels continues to return the index of the original df, even after mutation.

In the examples above, rows are removed but .index.levels continues to return the index of the original dataframe.

Expected Behavior

As d1 and d2 have a single row, expected output of:

  • d1: d1.index.levels[0] should be Index([1], dtype='int64', name=0).
  • d2: d2.index.levels should be FrozenList([[2], ['b']])

I was able to get the expected output by

d3 = df.head(1).reset_index().set_index([0, 1])
print(d3)
print(d3.index.levels[0])  # returns [1] as expected

Installed Versions

INSTALLED VERSIONS

commit : d9cdd2e
python : 3.11.6.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19045
machine : AMD64
processor : Intel64 Family 6 Model 154 Stepping 4, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_Australia.1252

pandas : 2.2.2
numpy : 2.1.1
pytz : 2024.2
dateutil : 2.9.0.post0
setuptools : 65.5.0
pip : 23.2.1
Cython : None
pytest : None
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
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions