Description
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
from pandas.testing import assert_index_equal, assert_extension_array_equal
dates = pd.date_range("2022-01-01", "2022-01-04")
names = ["Alice", "Bob"]
idx = pd.MultiIndex.from_product([dates, names], names=["dates", "names"])
data = pd.DataFrame(
index=idx,
data=[
["x1", "y1"],
["p1", "q1"],
["x2", "y2"],
["p2", "q2"],
["x3", "y3"],
["p3", "q3"],
["x4", "y4"],
["p4", "q4"],
],
columns=["v1", "v2"],
)
slice_dates = pd.date_range("2022-01-02", "2022-01-03", name="dates")
sliced = data.loc[slice_dates]
# this works
assert_extension_array_equal(
sliced.index.get_level_values(0).to_series().unique(), slice_dates.array
)
# but this doesnt
assert_index_equal(sliced.index.levels[0], slice_dates)
Issue Description
I have a DataFrame
with a MultiIndex
and slice it by a subset of its level 0 values using .loc[]
. When I call .index.levels[0]
on the sliced DataFrame
, the resulting index also includes values from the original, pre-sliced index. However the DataFrame
is correctly sliced. See also this StackOverflow question from 2014.
Expected Behavior
the levels of the MultiIndex
should be aligned with the actual values in the DataFrame
.
Installed Versions
INSTALLED VERSIONS
commit : 965ceca
python : 3.10.10.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.90.1-microsoft-standard-WSL2
Version : #1 SMP Fri Jan 27 02:56:13 UTC 2023
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : en_US.UTF-8
pandas : 2.0.2
numpy : 1.25.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 65.5.0
pip : 23.2.1
Cython : None
pytest : 7.3.2
hypothesis : 6.79.2
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
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None