From 6c111460b806ea48d0a022c8de3a57d7460751a6 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Fri, 16 Feb 2024 20:09:33 +0100 Subject: [PATCH] REGR: Behavior differs when adding Series to frame between matching and non matching index --- doc/source/whatsnew/v2.2.1.rst | 1 + pandas/core/generic.py | 2 +- pandas/tests/frame/test_arithmetic.py | 12 ++++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 5e814ec2a1b92..bd4bf2bb2771d 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -37,6 +37,7 @@ Fixed regressions - Fixed regression in :meth:`Index.join` raising ``TypeError`` when joining an empty index to a non-empty index containing mixed dtype values (:issue:`57048`) - Fixed regression in :meth:`Series.pct_change` raising a ``ValueError`` for an empty :class:`Series` (:issue:`57056`) - Fixed regression in :meth:`Series.to_numpy` when dtype is given as float and the data contains NaNs (:issue:`57121`) +- Fixed regression in arithmetic methods not sorting columns when indexes are equal (:issue:`57462`) .. --------------------------------------------------------------------------- .. _whatsnew_221.bug_fixes: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 149fbf7feb0dd..6bedc8cb05f41 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9645,7 +9645,7 @@ def _align_series( fdata = self._mgr join_index = self.axes[1] lidx, ridx = None, None - if not join_index.equals(other.index): + if not join_index.equals(other.index) or join == "outer": join_index, lidx, ridx = join_index.join( other.index, how=join, level=level, return_indexers=True ) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 3cf6d31390c2f..5e6b5223e2b2a 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -2108,3 +2108,15 @@ def test_mixed_col_index_dtype(): result = df1 + df2 expected = DataFrame(columns=list("abc"), data=1.0, index=[0]) tm.assert_frame_equal(result, expected) + + +def test_arithmetic_alignment(): + df = DataFrame({"x": [], "a": []}) + other = Series(dtype=float) + expected = DataFrame({"a": [], "x": []}) + tm.assert_frame_equal(df + other, expected) + + df = DataFrame({"x": [1], "a": [2]}) + other = Series([3, 4], index=["x", "a"]) + expected = DataFrame({"a": [6], "x": [4]}) + tm.assert_frame_equal(df + other, expected)