Skip to content

Commit c28c589

Browse files
authored
BUG: Fix MultiIndex alignment issue in Dataframe-Series binary operat… (#61017)
* BUG: Fix MultiIndex alignment issue in Dataframe-Series binary operation in case of different levels * Add test and fix whatsnew
1 parent 928fb7e commit c28c589

File tree

3 files changed

+39
-4
lines changed

3 files changed

+39
-4
lines changed

Diff for: doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,7 @@ MultiIndex
707707
- :meth:`MultiIndex.insert` would not insert NA value correctly at unified location of index -1 (:issue:`59003`)
708708
- :func:`MultiIndex.get_level_values` accessing a :class:`DatetimeIndex` does not carry the frequency attribute along (:issue:`58327`, :issue:`57949`)
709709
- Bug in :class:`DataFrame` arithmetic operations in case of unaligned MultiIndex columns (:issue:`60498`)
710+
- Bug in :class:`DataFrame` arithmetic operations with :class:`Series` in case of unaligned MultiIndex (:issue:`61009`)
710711
-
711712

712713
I/O

Diff for: pandas/core/generic.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -9636,10 +9636,7 @@ def _align_series(
96369636

96379637
left = self._constructor_from_mgr(fdata, axes=fdata.axes)
96389638

9639-
if ridx is None:
9640-
right = other.copy(deep=False)
9641-
else:
9642-
right = other.reindex(join_index, level=level)
9639+
right = other._reindex_indexer(join_index, ridx)
96439640

96449641
# fill
96459642
fill_na = notna(fill_value)

Diff for: pandas/tests/frame/test_arithmetic.py

+37
Original file line numberDiff line numberDiff line change
@@ -832,6 +832,43 @@ def test_frame_multiindex_operations_part_align(self):
832832

833833
tm.assert_frame_equal(result, expected)
834834

835+
def test_frame_multiindex_operations_part_align_axis1(self):
836+
# GH#61009 Test DataFrame-Series arithmetic operation
837+
# with partly aligned MultiIndex and axis = 1
838+
df = DataFrame(
839+
[[1, 2, 3], [3, 4, 5]],
840+
index=[2010, 2020],
841+
columns=MultiIndex.from_tuples(
842+
[
843+
("a", "b", 0),
844+
("a", "b", 1),
845+
("a", "c", 2),
846+
],
847+
names=["scen", "mod", "id"],
848+
),
849+
)
850+
851+
series = Series(
852+
[0.4],
853+
index=MultiIndex.from_product([["b"], ["a"]], names=["mod", "scen"]),
854+
)
855+
856+
expected = DataFrame(
857+
[[1.4, 2.4, np.nan], [3.4, 4.4, np.nan]],
858+
index=[2010, 2020],
859+
columns=MultiIndex.from_tuples(
860+
[
861+
("a", "b", 0),
862+
("a", "b", 1),
863+
("a", "c", 2),
864+
],
865+
names=["scen", "mod", "id"],
866+
),
867+
)
868+
result = df.add(series, axis=1)
869+
870+
tm.assert_frame_equal(result, expected)
871+
835872

836873
class TestFrameArithmetic:
837874
def test_td64_op_nat_casting(self):

0 commit comments

Comments
 (0)