Skip to content

BUG: MultiIndex intersection doesn't work with categorical dtypes #49337

Closed
@deepers

Description

@deepers

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

mi1 = pd.MultiIndex.from_frame(
    pd.DataFrame(dict(i1=pd.Series(["b", "a"]), i2=1)),
)
print(mi1)

# This index is the same except the left index labels belong to a categorical dtype
cat_dt = pd.CategoricalDtype(["b", "a"], ordered=True)
mi2 = pd.MultiIndex.from_frame(
    pd.DataFrame(dict(i1=pd.Series(["b", "a"], dtype=cat_dt), i2=1))
)
print(mi2)

# These behave as expected.
print(mi1.intersection(mi1[1:]))
print(mi1.intersection(mi2[1:]))

# These do not.
print(mi2.intersection(mi1[1:]))
print(mi2.intersection(mi2[1:]))

Issue Description

From the example you can see that index intersection doesn't work properly for MultiIndexes when there is a categorical dtype. I think what's happening is that the intersection method sees that mi2 is monotonic, so it passes the array [('b', 1), ('a', 1)] to inner_join_indexer(), which gets the wrong answer, because mi2 is only monotonic with respect to the categorical dtype.

Expected Behavior

All four intersections in the example should return the following.

MultiIndex([('a', 1)],
           names=['i1', 'i2'])

Installed Versions

INSTALLED VERSIONS

commit : 91111fd
python : 3.10.7.final.0
python-bits : 64
OS : Linux
OS-release : 5.19.16-200.fc36.x86_64
Version : #1 SMP PREEMPT_DYNAMIC Sun Oct 16 22:50:04 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_CA.UTF-8
LOCALE : en_CA.UTF-8

pandas : 1.5.1
numpy : 1.23.4
pytz : 2022.5
dateutil : 2.8.2
setuptools : 65.5.0
pip : 22.0.4
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 : 8.5.0
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.0
numba : None
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.3
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : 2022.10.0
xlrd : None
xlwt : None
zstandard : None
tzdata : 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