Skip to content

BUG: DataFrame.join with left or right empty not respecting sort=True #56443

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
Dec 11, 2023
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/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ These are bug fixes that might have notable behavior changes.

In previous versions of pandas, :func:`merge` and :meth:`DataFrame.join` did not
always return a result that followed the documented sort behavior. pandas now
follows the documented sort behavior in merge and join operations (:issue:`54611`, :issue:`56426`).
follows the documented sort behavior in merge and join operations (:issue:`54611`, :issue:`56426`, :issue:`56443`).

As documented, ``sort=True`` sorts the join keys lexicographically in the resulting
:class:`DataFrame`. With ``sort=False``, the order of the join keys depends on the
Expand Down
36 changes: 23 additions & 13 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4576,9 +4576,6 @@ def join(
pother, how=how, level=level, return_indexers=True, sort=sort
)

lindexer: np.ndarray | None
rindexer: np.ndarray | None

# try to figure out the join level
# GH3662
if level is None and (self._is_multi or other._is_multi):
Expand All @@ -4592,25 +4589,38 @@ def join(
if level is not None and (self._is_multi or other._is_multi):
return self._join_level(other, level, how=how)

lidx: np.ndarray | None
ridx: np.ndarray | None

if len(other) == 0:
if how in ("left", "outer"):
join_index = self._view()
rindexer = np.broadcast_to(np.intp(-1), len(join_index))
return join_index, None, rindexer
if sort and not self.is_monotonic_increasing:
lidx = self.argsort()
join_index = self.take(lidx)
else:
lidx = None
join_index = self._view()
ridx = np.broadcast_to(np.intp(-1), len(join_index))
return join_index, lidx, ridx
elif how in ("right", "inner", "cross"):
join_index = other._view()
lindexer = np.array([])
return join_index, lindexer, None
lidx = np.array([], dtype=np.intp)
return join_index, lidx, None

if len(self) == 0:
if how in ("right", "outer"):
join_index = other._view()
lindexer = np.broadcast_to(np.intp(-1), len(join_index))
return join_index, lindexer, None
if sort and not other.is_monotonic_increasing:
ridx = other.argsort()
join_index = other.take(ridx)
else:
ridx = None
join_index = other._view()
lidx = np.broadcast_to(np.intp(-1), len(join_index))
return join_index, lidx, ridx
elif how in ("left", "inner", "cross"):
join_index = self._view()
rindexer = np.array([])
return join_index, None, rindexer
ridx = np.array([], dtype=np.intp)
return join_index, None, ridx

if self.dtype != other.dtype:
dtype = self._find_common_type_compat(other)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/methods/test_combine_first.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def test_combine_first(self, float_frame, using_infer_string):
tm.assert_frame_equal(comb, float_frame)

comb = DataFrame().combine_first(float_frame)
tm.assert_frame_equal(comb, float_frame)
tm.assert_frame_equal(comb, float_frame.sort_index())

comb = float_frame.combine_first(DataFrame(index=["faz", "boo"]))
assert "faz" in comb.index
Expand Down
6 changes: 4 additions & 2 deletions pandas/tests/frame/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,10 +629,12 @@ def test_arith_flex_frame_corner(self, float_frame):

# corner cases
result = float_frame.add(float_frame[:0])
tm.assert_frame_equal(result, float_frame * np.nan)
expected = float_frame.sort_index() * np.nan
tm.assert_frame_equal(result, expected)

result = float_frame[:0].add(float_frame)
tm.assert_frame_equal(result, float_frame * np.nan)
expected = float_frame.sort_index() * np.nan
tm.assert_frame_equal(result, expected)

with pytest.raises(NotImplementedError, match="fill_value"):
float_frame.add(float_frame.iloc[0], fill_value=3)
Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/reshape/merge/test_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,8 @@ def test_join_empty(left_empty, how, exp):
expected = DataFrame(columns=["B", "C"], dtype="int64")
if how != "cross":
expected = expected.rename_axis("A")
if how == "outer":
expected = expected.sort_index()

tm.assert_frame_equal(result, expected)

Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/series/test_logical_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ def test_logical_operators_bool_dtype_with_empty(self):
s_empty = Series([], dtype=object)

res = s_tft & s_empty
expected = s_fff
expected = s_fff.sort_index()
tm.assert_series_equal(res, expected)

res = s_tft | s_empty
expected = s_tft
expected = s_tft.sort_index()
tm.assert_series_equal(res, expected)

def test_logical_operators_int_dtype_with_int_dtype(self):
Expand Down Expand Up @@ -397,11 +397,11 @@ def test_logical_ops_label_based(self, using_infer_string):
empty = Series([], dtype=object)

result = a & empty.copy()
expected = Series([False, False, False], list("bca"))
expected = Series([False, False, False], list("abc"))
tm.assert_series_equal(result, expected)

result = a | empty.copy()
expected = Series([True, False, True], list("bca"))
expected = Series([True, True, False], list("abc"))
tm.assert_series_equal(result, expected)

# vs non-matching
Expand Down