Skip to content

Commit 9140647

Browse files
authored
BUG: raise when doing arithmetic on DataFrame and list of iterables (#37132)
1 parent 4c395b0 commit 9140647

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,7 @@ Numeric
371371
- Bug in :meth:`DataFrame.diff` with ``datetime64`` dtypes including ``NaT`` values failing to fill ``NaT`` results correctly (:issue:`32441`)
372372
- Bug in :class:`DataFrame` arithmetic ops incorrectly accepting keyword arguments (:issue:`36843`)
373373
- Bug in :class:`IntervalArray` comparisons with :class:`Series` not returning :class:`Series` (:issue:`36908`)
374+
- Bug in :class:`DataFrame` allowing arithmetic operations with list of array-likes with undefined results. Behavior changed to raising ``ValueError`` (:issue:`36702`)
374375

375376
Conversion
376377
^^^^^^^^^^

pandas/core/ops/__init__.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from pandas._typing import Level
1414
from pandas.util._decorators import Appender
1515

16-
from pandas.core.dtypes.common import is_list_like
16+
from pandas.core.dtypes.common import is_array_like, is_list_like
1717
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
1818
from pandas.core.dtypes.missing import isna
1919

@@ -311,6 +311,11 @@ def to_series(right):
311311
)
312312

313313
elif is_list_like(right) and not isinstance(right, (ABCSeries, ABCDataFrame)):
314+
# GH 36702. Raise when attempting arithmetic with list of array-like.
315+
if any(is_array_like(el) for el in right):
316+
raise ValueError(
317+
f"Unable to coerce list of {type(right[0])} to Series/DataFrame"
318+
)
314319
# GH17901
315320
right = to_series(right)
316321

pandas/tests/frame/test_arithmetic.py

+14
Original file line numberDiff line numberDiff line change
@@ -1577,3 +1577,17 @@ def test_arith_reindex_with_duplicates():
15771577
result = df1 + df2
15781578
expected = pd.DataFrame([[np.nan, 0, 0]], columns=["first", "second", "second"])
15791579
tm.assert_frame_equal(result, expected)
1580+
1581+
1582+
@pytest.mark.parametrize(
1583+
"to_add", [[pd.Series([1, 1])], [pd.Series([1, 1]), pd.Series([1, 1])]]
1584+
)
1585+
def test_arith_list_of_arraylike_raise(to_add):
1586+
# GH 36702. Raise when trying to add list of array-like to DataFrame
1587+
df = pd.DataFrame({"x": [1, 2], "y": [1, 2]})
1588+
1589+
msg = f"Unable to coerce list of {type(to_add[0])} to Series/DataFrame"
1590+
with pytest.raises(ValueError, match=msg):
1591+
df + to_add
1592+
with pytest.raises(ValueError, match=msg):
1593+
to_add + df

0 commit comments

Comments
 (0)