Skip to content

BUG: DataFrame.join(other) raises InvalidIndexError if column index is CategoricalIndex #61675

Open
@tvoipio

Description

@tvoipio

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

cat_data = pd.Categorical([15, 16, 17, 18], categories=pd.Series(list(range(3, 24)), dtype="Int64"), ordered=True)
df1 = pd.DataFrame({"hr": cat_data, "values1": "a b c d".split()}).set_index("hr")
df2 = pd.DataFrame({"hr": cat_data, "values2": "xyzzy foo bar ...".split()}).set_index("hr")
df1.columns = pd.CategoricalIndex([4], dtype=cat_data.dtype, name="other_hr")
df2.columns = pd.CategoricalIndex([3], dtype=cat_data.dtype, name="other_hr")

print(pd.__version__)

# Clunky, but works
df_joined_1 = df1.reset_index(level="hr").merge(df2.reset_index(level="hr"), on="hr").set_index("hr")

# Works on 1.4.4 and nightly (3.0.0.dev0+2177.g8a1d5a06f9), not 2.2.3 or 2.3.0
df_joined_2 = df1.join(df2)

# returns True... assuming we got this far
df_joined_1.equals(df_joined_2)

Issue Description

joining two DataFrames which have a CategoricalIndex as columns (for example, due to having pivoted on a categorical column) results in an InvalidIndexError (see below) on Pandas versions 2.2.3 and 2.3.0. The same code works with 1.4.4 (from which I am trying to migrate to 2.x) and nightly.

While the issue does not manifest in nightly, I am still reporting it in the hopes of getting it fixed in future 2.x releases.

Expected Behavior

Code executes successfully and the last statement returns True

Installed Versions

Pandas 1.4.4 (works)

INSTALLED VERSIONS ------------------ commit : ca60aab python : 3.10.16.final.0 python-bits : 64 OS : Darwin OS-release : 24.5.0 Version : Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041 machine : arm64 processor : arm byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8

pandas : 1.4.4
numpy : 1.23.5
pytz : 2025.2
dateutil : 2.9.0.post0
setuptools : 80.7.1
pip : 25.1.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 : 8.36.0
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
markupsafe : None
matplotlib : 3.10.3
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.2
pandas_gbq : None
pyarrow : 8.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : 2.0.41
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None

Pandas 2.2.3 (does not work)

INSTALLED VERSIONS ------------------ commit : 0691c5c python : 3.12.9 python-bits : 64 OS : Darwin OS-release : 24.5.0 Version : Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041 machine : arm64 processor : arm byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8

pandas : 2.2.3
numpy : 2.2.4
pytz : 2025.1
dateutil : 2.9.0.post0
pip : 24.3.1
Cython : None
sphinx : None
IPython : 9.0.2
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : 3.1.6
lxml.etree : None
matplotlib : 3.10.1
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.5
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : 19.0.1
pyreadstat : None
pytest : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.15.2
sqlalchemy : 2.0.39
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.1
qtpy : None
pyqt5 : None

Pandas 2.3.0 (does not work)

INSTALLED VERSIONS ------------------ commit : 2cc3762 python : 3.12.9 python-bits : 64 OS : Darwin OS-release : 24.5.0 Version : Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041 machine : arm64 processor : arm byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8

pandas : 2.3.0
numpy : 2.3.0
pytz : 2025.2
dateutil : 2.9.0.post0
pip : 25.1.1
Cython : None
sphinx : None
IPython : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : None
lxml.etree : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : 20.0.0
pyreadstat : None
pytest : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.2
qtpy : None
pyqt5 : None

Pandas nightly (works)

INSTALLED VERSIONS ------------------ commit : 8a1d5a0 python : 3.12.9 python-bits : 64 OS : Darwin OS-release : 24.5.0 Version : Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041 machine : arm64 processor : arm byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8

pandas : 3.0.0.dev0+2177.g8a1d5a06f9
numpy : 2.4.0.dev0+git20250617.32f4afa
dateutil : 2.9.0.post0
pip : 25.1.1
Cython : None
sphinx : None
IPython : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : None
lxml.etree : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
psycopg2 : None
pymysql : None
pyarrow : None
pyiceberg : None
pyreadstat : None
pytest : None
python-calamine : None
pytz : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.2
qtpy : None
pyqt5 : None

Error traceback

On Pandas 2.3.3:

Traceback (most recent call last):
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/indexes/base.py", line 3812, in get_loc
    return self._engine.get_loc(casted_key)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "pandas/_libs/index.pyx", line 167, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 175, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index_class_helper.pxi", line 86, in pandas._libs.index.MaskedInt64Engine._check_type
KeyError: slice(None, None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/frame.py", line 10764, in join
    return merge(
           ^^^^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/reshape/merge.py", line 184, in merge
    return op.get_result(copy=copy)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/reshape/merge.py", line 888, in get_result
    result = self._reindex_and_concat(
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/reshape/merge.py", line 837, in _reindex_and_concat
    left = self.left[:]
           ~~~~~~~~~^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/frame.py", line 4080, in __getitem__
    and key in self.columns
        ^^^^^^^^^^^^^^^^^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/indexes/category.py", line 368, in __contains__
    return contains(self, key, container=self._engine)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/arrays/categorical.py", line 230, in contains
    loc = cat.categories.get_loc(key)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/voipiti/.pyenv/versions/pd23-312/lib/python3.12/site-packages/pandas/core/indexes/base.py", line 3818, in get_loc
    raise InvalidIndexError(key)
pandas.errors.InvalidIndexError: slice(None, None, None)

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions