From 490bbbde81306dd430f0e9def9e8ef145f4eaa55 Mon Sep 17 00:00:00 2001 From: Nitish Satyavolu Date: Mon, 10 Feb 2025 09:12:26 -0800 Subject: [PATCH] BUG: Fix bug in DataFrame binary op not respecting fill_value in case of MultiIndex columns --- pandas/core/frame.py | 11 ++++++++--- pandas/tests/frame/test_arithmetic.py | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 57a7b9467a05e..3199733cfb85f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8029,10 +8029,15 @@ def _should_reindex_frame_op(self, right, op, axis: int, fill_value, level) -> b return False if ( - isinstance(self.columns, MultiIndex) - or isinstance(right.columns, MultiIndex) - ) and not self.columns.equals(right.columns): + ( + isinstance(self.columns, MultiIndex) + or isinstance(right.columns, MultiIndex) + ) + and not self.columns.equals(right.columns) + and fill_value is None + ): # GH#60498 Reindex if MultiIndexe columns are not matching + # GH#60903 Don't reindex if fill_value is provided return True if fill_value is None and level is None and axis == 1: diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index aa2d5e9d23815..8239de3f39c20 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -2058,6 +2058,26 @@ def test_arithmetic_multiindex_column_align(): tm.assert_frame_equal(result, expected) +def test_arithmetic_multiindex_column_align_with_fillvalue(): + # GH#60903 + df1 = DataFrame( + data=[[1.0, 2.0]], + columns=MultiIndex.from_tuples([("A", "one"), ("A", "two")]), + ) + df2 = DataFrame( + data=[[3.0, 4.0]], + columns=MultiIndex.from_tuples([("B", "one"), ("B", "two")]), + ) + expected = DataFrame( + data=[[1.0, 2.0, 3.0, 4.0]], + columns=MultiIndex.from_tuples( + [("A", "one"), ("A", "two"), ("B", "one"), ("B", "two")] + ), + ) + result = df1.add(df2, fill_value=0) + tm.assert_frame_equal(result, expected) + + def test_bool_frame_mult_float(): # GH 18549 df = DataFrame(True, list("ab"), list("cd"))