diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index c80195af413f7..01e4046e8b743 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -125,7 +125,7 @@ Reshaping ^^^^^^^^^ - A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`) -- +- :meth:`DataFrame.join` now suppresses the ``FutureWarning`` when the sort parameter is specified (:issue:`21952`) - Sparse diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5980e3d133374..2a93cd5937221 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7217,10 +7217,14 @@ def _join_compat( # join indexes only using concat if can_concat: if how == "left": - res = concat(frames, axis=1, join="outer", verify_integrity=True) + res = concat( + frames, axis=1, join="outer", verify_integrity=True, sort=sort + ) return res.reindex(self.index, copy=False) else: - return concat(frames, axis=1, join=how, verify_integrity=True) + return concat( + frames, axis=1, join=how, verify_integrity=True, sort=sort + ) joined = frames[0] diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index adace5e4784ae..220968d4b3d29 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -193,3 +193,32 @@ def test_join_left_sequence_non_unique_index(): ) tm.assert_frame_equal(joined, expected) + + +@pytest.mark.parametrize("sort_kw", [True, False, None]) +def test_suppress_future_warning_with_sort_kw(sort_kw): + a = DataFrame({"col1": [1, 2]}, index=["c", "a"]) + + b = DataFrame({"col2": [4, 5]}, index=["b", "a"]) + + c = DataFrame({"col3": [7, 8]}, index=["a", "b"]) + + expected = DataFrame( + { + "col1": {"a": 2.0, "b": float("nan"), "c": 1.0}, + "col2": {"a": 5.0, "b": 4.0, "c": float("nan")}, + "col3": {"a": 7.0, "b": 8.0, "c": float("nan")}, + } + ) + if sort_kw is False: + expected = expected.reindex(index=["c", "a", "b"]) + + if sort_kw is None: + # only warn if not explicitly specified + ctx = tm.assert_produces_warning(FutureWarning, check_stacklevel=False) + else: + ctx = tm.assert_produces_warning(None, check_stacklevel=False) + + with ctx: + result = a.join([b, c], how="outer", sort=sort_kw) + tm.assert_frame_equal(result, expected)