Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: MultiIndex.levels[x] of sliced DataFrame returns values from the non-sliced index #55148

Closed
3 tasks done
ilCatania opened this issue Sep 15, 2023 · 6 comments
Closed
3 tasks done

Comments

@ilCatania
Copy link

ilCatania commented Sep 15, 2023

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

@ilCatania ilCatania added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 15, 2023
@rhshadrach
Copy link
Member

Thanks for the report. MultiIndex makes no guarantee that the levels are only those which are present in the values. Users can create a MultiIndex such as

index = MultiIndex(
    levels=[[0, 1, 2], ['x', 'y']],
    codes=[[0, 0, 0], [0, 0, 0]],
)

where I think it's expected that the levels have more than just the values that are present. When pandas slices, it only updates the codes for performance.There is remove_unused_levels available.

@rhshadrach rhshadrach added MultiIndex Closing Candidate May be closeable, needs more eyeballs and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 16, 2023
@ilCatania
Copy link
Author

Thanks @rhshadrach, good to know. I've added this info to the StackOverflow question.

@trianta2
Copy link

trianta2 commented Oct 3, 2023

Given the creation of two bug reports on this topic, it's probably worth noting this design choice explicitly in the MultiIndex.levels docstring, which is currently empty.

@rhshadrach
Copy link
Member

That sounds like a good idea to me @trianta2. Would you be interested in putting up a PR for this?

@rhshadrach rhshadrach reopened this Oct 4, 2023
@rhshadrach rhshadrach added Docs and removed Bug Closing Candidate May be closeable, needs more eyeballs labels Oct 4, 2023
@trianta2
Copy link

trianta2 commented Oct 5, 2023

@datapythonista
Copy link
Member

I'll close this in favor of #55435 which I think it's more accurate on what needs to be done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants