Skip to content

BUG: join not working correctly with MultiIndex and one dimension categorical #38621

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 7 commits into from
Jan 13, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ Groupby/resample/rolling
Reshaping
^^^^^^^^^

-
- Bug in :meth:`DataFrame.join` not assigning values correctly when having :class:`MultiIndex` where at least one dimension is from dtype ``Categorical`` with non-alphabetically sorted categories (:issue:`38502`)
-

Sparse
Expand Down
11 changes: 10 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3683,7 +3683,16 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False)
return self._join_non_unique(
other, how=how, return_indexers=return_indexers
)
elif self.is_monotonic and other.is_monotonic:
elif (
self.is_monotonic
and other.is_monotonic
and (
not isinstance(self, ABCMultiIndex)
Copy link
Contributor

Choose a reason for hiding this comment

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

can you check _is_lexsorted instead rather than this specific check.

Copy link
Member Author

Choose a reason for hiding this comment

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

Same issue as with is_monotonic, depends on the categories too.

or not any(is_categorical_dtype(dtype) for dtype in self.dtypes)
)
):
# Categorical is monotonic if data are ordered as categories, but join can
# not handle this in case of not alphabetically monotonic GH#38502
Copy link
Member

Choose a reason for hiding this comment

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

is alphabetical really the issue? what about numeric or dt64 Categoricals?

Copy link
Member Author

Choose a reason for hiding this comment

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

Hm bad wording probably. If the object is lexicographically ordered everything is fine. Monotonic in the sense of categorical monotonic is the problem

Copy link
Member Author

Choose a reason for hiding this comment

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

I will add tests for different types of Categorical.s

Copy link
Member Author

@phofl phofl Dec 24, 2020

Choose a reason for hiding this comment

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

Added float, int and timestamps.

Edit: They are all failling without the changes

try:
return self._join_monotonic(
other, how=how, return_indexers=return_indexers
Expand Down
31 changes: 30 additions & 1 deletion pandas/tests/reshape/merge/test_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest

import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series, concat, merge
from pandas import Categorical, DataFrame, Index, MultiIndex, Series, concat, merge
import pandas._testing as tm
from pandas.tests.reshape.merge.test_merge import NGROUPS, N, get_test_data

Expand Down Expand Up @@ -815,3 +815,32 @@ def test_join_cross(input_col, output_cols):
result = left.join(right, how="cross", lsuffix="_x", rsuffix="_y")
expected = DataFrame({output_cols[0]: [1, 1, 3, 3], output_cols[1]: [3, 4, 3, 4]})
tm.assert_frame_equal(result, expected)


def test_join_multiindex_not_alphabetical_categorical():
# GH#38502
left = DataFrame(
{
"first": ["A", "A"],
"second": Categorical(["Y", "X"], categories=["Y", "X"]),
"value": [1, 2],
}
).set_index(["first", "second"])
right = DataFrame(
{
"first": ["A", "A", "B"],
"second": Categorical(["Y", "X", "X"], categories=["Y", "X"]),
"value": [3, 4, 5],
}
).set_index(["first", "second"])
result = left.join(right, lsuffix="_left", rsuffix="_right")

expected = DataFrame(
{
"first": ["A", "A"],
"second": Categorical(["Y", "X"], categories=["Y", "X"]),
"value_left": [1, 2],
"value_right": [3, 4],
}
).set_index(["first", "second"])
tm.assert_frame_equal(result, expected)