Skip to content

Commit b22fc9f

Browse files
author
Shashwat1001
committed
DOC: Clarify broadcasting behavior when using lists in DataFrame arithmetic (GH18857)
1 parent d5f97ed commit b22fc9f

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

doc/source/user_guide/basics.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,11 @@ either match on the *index* or *columns* via the **axis** keyword:
209209
df.sub(column, axis="index")
210210
df.sub(column, axis=0)
211211
212+
Be careful when using raw Python lists in binary operations with DataFrames.
213+
Unlike NumPy arrays or Series, lists are not broadcast across rows or columns.
214+
Instead, pandas attempts to match the entire list against a single axis, which may lead to confusing results such as Series of arrays.
215+
To ensure proper broadcasting behavior, use a NumPy array or Series with explicit index or shape.
216+
See also: :ref:`numpy broadcasting <https://numpy.org/doc/stable/user/basics.broadcasting.html>`
212217
Furthermore you can align a level of a MultiIndexed DataFrame with a Series.
213218

214219
.. ipython:: python

doc/source/user_guide/dsintro.rst

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,19 @@ row-wise. For example:
650650
651651
df - df.iloc[0]
652652
653+
When using a Python list in arithmetic operations with a DataFrame, the behavior is not element-wise broadcasting.
654+
Instead, the list is treated as a single object and the operation is performed column-wise, resulting in unexpected output (e.g. arrays inside each cell).
655+
656+
.. ipython:: python
657+
658+
df = pd.DataFrame(np.arange(6).reshape(2, 3), columns=["A", "B", "C"])
659+
660+
df + [1, 2, 3] # Returns a Series of arrays, not a DataFrame
661+
662+
df + np.array([1, 2, 3]) # Correct broadcasting
663+
664+
df + pd.Series([1, 2, 3], index=["A", "B", "C"]) # Also correct
665+
653666
For explicit control over the matching and broadcasting behavior, see the
654667
section on :ref:`flexible binary operations <basics.binop>`.
655668

0 commit comments

Comments
 (0)