Skip to content

BUG: fix Dataframe.join with categorical index leads to unexpected reordering #47881

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
Jul 28, 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,7 @@ Reshaping
- Bug in :meth:`DataFrame.pivot_table` with ``sort=False`` results in sorted index (:issue:`17041`)
- Bug in :meth:`concat` when ``axis=1`` and ``sort=False`` where the resulting Index was a :class:`Int64Index` instead of a :class:`RangeIndex` (:issue:`46675`)
- Bug in :meth:`wide_to_long` raises when ``stubnames`` is missing in columns and ``i`` contains string dtype column (:issue:`46044`)
- Bug in :meth:`DataFrame.join` with categorical index results in unexpected reordering (:issue:`47812`)

Sparse
^^^^^^
Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4682,6 +4682,7 @@ def join(
not isinstance(self, ABCMultiIndex)
or not any(is_categorical_dtype(dtype) for dtype in self.dtypes)
)
and not is_categorical_dtype(self.dtype)
):
# Categorical is monotonic if data are ordered as categories, but join can
# not handle this in case of not lexicographically monotonic GH#38502
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/reshape/merge/test_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,21 @@ def test_join_datetime_string(self):
)
tm.assert_frame_equal(result, expected)

def test_join_with_categorical_index(self):
# GH47812
ix = ["a", "b"]
id1 = pd.CategoricalIndex(ix, categories=ix)
id2 = pd.CategoricalIndex(reversed(ix), categories=reversed(ix))

df1 = DataFrame({"c1": ix}, index=id1)
df2 = DataFrame({"c2": reversed(ix)}, index=id2)
result = df1.join(df2)
expected = DataFrame(
{"c1": ["a", "b"], "c2": ["a", "b"]},
index=pd.CategoricalIndex(["a", "b"], categories=["a", "b"]),
)
tm.assert_frame_equal(result, expected)


def _check_join(left, right, result, join_col, how="left", lsuffix="_x", rsuffix="_y"):

Expand Down