Skip to content

BUG: merge with CategoricalIndex for left_on/right_on #48464

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

Merged
merged 2 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ Groupby/resample/rolling

Reshaping
^^^^^^^^^
-
- Bug in :func:`join` when ``left_on`` or ``right_on`` is or includes a :class:`CategoricalIndex` incorrectly raising ``AttributeError`` (:issue:`48464`)
-

Sparse
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/reshape/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,9 @@ def _maybe_coerce_merge_keys(self) -> None:
if (len(lk) and not len(rk)) or (not len(lk) and len(rk)):
continue

lk = extract_array(lk, extract_numpy=True)
rk = extract_array(rk, extract_numpy=True)

lk_is_cat = is_categorical_dtype(lk.dtype)
rk_is_cat = is_categorical_dtype(rk.dtype)
lk_is_object = is_object_dtype(lk.dtype)
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/reshape/merge/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2655,6 +2655,18 @@ def test_mergeerror_on_left_index_mismatched_dtypes():
merge(df_1, df_2, on=["C"], left_index=True)


def test_merge_on_left_categoricalindex():
# GH#48464 don't raise when left_on is a CategoricalIndex
ci = CategoricalIndex(range(3))

right = DataFrame({"A": ci, "B": range(3)})
left = DataFrame({"C": range(3, 6)})

res = merge(left, right, left_on=ci, right_on="A")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the comment below the code change:

           # if either left or right is a categorical
            # then the must match exactly in categories & ordered

Apply here as well? Could you add a test where categories/ordered are different too?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

really shouldn't be relevant. its just a matter of CategoricalIndex vs Categorical

expected = merge(left, right, left_on=ci._data, right_on="A")
tm.assert_frame_equal(res, expected)


@pytest.mark.parametrize("dtype", [None, "Int64"])
def test_merge_outer_with_NaN(dtype):
# GH#43550
Expand Down