Sub topic 2
Replacing row arithmetic with column expressions
This chapter assumes you can write basic Python (functions, loops, dictionaries), build and index a pandas DataFrame and Series, and use NumPy arrays at a basic level. The earlier chapter explained why row loops are slow. This one covers how to rewrite them.
The core idea
Most row loops compute one value per row from other values in the same row. Each row's result depends only on that row, so you can write the formula once and apply it to the whole column.
In row["price"] * row["qty"], row["price"] is one number. In df["price"] * df["qty"], df["price"] is a whole column. The * operator multiplies the two columns element by element, pairing values that share an index label. pandas hands the work to NumPy, which runs a compiled loop over contiguous memory instead of running Python bytecode once per row.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
# Row loop
totals = []
for _, row in df.iterrows():
totals.append(row["price"] * row["qty"])
df["total_loop"] = totals
# Vectorised
df["total"] = df["price"] * df["qty"]
print(df)Both approaches give 30.0, 20.0 and 60.0. The vectorised version is shorter, and it also avoids building a Series object for every row, which iterrows does.
A translation recipe
You can convert most row loops mechanically.
The last step matters. The chapter on measuring covers it in detail, but the habit starts here: keep the loop version until you have confirmed that the two outputs are equal.
Operators that work on columns
Every arithmetic operator works column-wise: +, -, *, /, //, % and **. Comparison operators (<, >=, ==) work the same way and return a column of booleans. The next chapter uses those booleans as masks.
A scalar on one side is broadcast. pandas treats it as if it were repeated for every row.
df["discounted"] = df["total"] * 0.9 # scalar broadcast
df["unit_cost"] = 4.5 # assigning a scalar fills the column
df["margin"] = (df["price"] - df["unit_cost"]) * df["qty"]
print(df[["total", "discounted", "margin"]])The margins are 16.5, 15.5 and 42.0. Parentheses work as in ordinary arithmetic, so you can transcribe a formula from a spec almost unchanged.
The table below maps common loop idioms to their column forms.
| Loop idiom | Column expression |
|---|---|
| `row["a"] + row["b"]` | `df["a"] + df["b"]` |
| `row["a"] * 1.2` | `df["a"] * 1.2` |
| `math.sqrt(row["a"])` | `np.sqrt(df["a"])` |
| `round(row["a"], 2)` | `df["a"].round(2)` |
| `abs(row["a"] - row["b"])` | `(df["a"] - df["b"]).abs()` |
| `max(row["a"], 0)` | `df["a"].clip(lower=0)` |
| `row["a"] / row["b"]` | `df["a"] / df["b"]` |
Functions: use the NumPy and pandas versions
Functions from Python's math module accept a single number. Pass one a Series and it raises an error.
import math
import numpy as np
try:
math.sqrt(df["total"])
except TypeError:
print("math.sqrt cannot take a whole column")
df["root"] = np.sqrt(df["total"])
df["log_total"] = np.log(df["total"])NumPy functions such as np.sqrt, np.log, np.exp and np.abs are universal functions (ufuncs). A ufunc is a function that operates on every element of an array. pandas accepts them and returns a Series with the original index preserved. The same applies to Series methods such as .round(), .abs() and .clip().
The built-in max, min and abs have a related problem. max(df["a"], df["b"]) tries to compare two Series as single values and raises a ValueError. For an element-wise maximum, use np.maximum(df["a"], df["b"]).
Arithmetic across several columns
Sometimes a row formula combines many columns, such as a total across quarters. Chaining + works, but it becomes tedious. Select the columns as a smaller DataFrame and reduce across them with axis=1.
scores = pd.DataFrame({"q1": [1, 2], "q2": [3, 4], "q3": [5, 6]})
cols = ["q1", "q2", "q3"]
scores["total"] = scores[cols].sum(axis=1)
scores["mean"] = scores[cols].mean(axis=1)
scores["best"] = scores[cols].max(axis=1)axis=1 means "collapse the columns, leaving one value per row". The default, axis=0, collapses the rows and leaves one value per column. This is a frequent source of mistakes. If a sum comes back with one number per column, you left out axis=1.
To divide each of several columns by a per-row value, use the method form of the operator and name the axis.
shares = scores[cols].div(scores["total"], axis=0)
print(shares)Without axis=0, pandas would try to match the total Series against the column names. The result would be a frame of all NaN values.
Missing values and operator behaviour
Arithmetic operators propagate NaN. Reductions such as sum(axis=1) skip NaN by default. Your rewrite must match whichever behaviour the loop had.
a = pd.Series([1.0, np.nan, 3.0])
b = pd.Series([1.0, 1.0, 1.0])
print(a + b) # 2.0, NaN, 4.0
print(a.add(b, fill_value=0)) # 2.0, 1.0, 4.0fill_value replaces a missing value on one side before the operation. If both sides are missing, the result stays NaN. The method forms add, sub, mul and div all accept it.
A loop in plain Python usually fails differently. Adding float("nan") also gives nan, but a None in an object column raises a TypeError partway through. A vectorised version on a clean numeric dtype never reaches that situation. When you see an unexpected NaN count after a rewrite, check the dtype first.
Dtypes affect results
Division with / always returns floats, even for integer inputs. Floor division with // keeps integers when both sides are integers.
n = pd.Series([7, 8, 9])
print((n / 2).tolist()) # [3.5, 4.0, 4.5]
print((n // 2).tolist()) # [3, 4, 4]A column that looks numeric but has dtype object is the more serious problem. This happens when a CSV column contains a stray string such as "n/a". Operators on object columns fall back to a slow per-element Python path, or they concatenate strings with +. Check df.dtypes before rewriting, and convert with pd.to_numeric(df["col"], errors="coerce") if needed. A later chapter covers dtypes and memory in more detail.
Assigning results safely
Assign the new column directly on the frame with df["new"] = expression. Two habits prevent most warnings.
- Do not assign into a slice, as in
df[df["qty"] > 1]["total"] = .... Select and assign in a single.loccall, or work on an explicit.copy(). - Do not build the column with a Python list unless you must. A list has no index, so pandas assigns it by position. A Series assigns by index label.
If you want to add a column without modifying the original frame, use assign, which returns a new DataFrame and lets you chain steps.
result = (
df[["price", "qty"]]
.assign(total=lambda d: d["price"] * d["qty"])
.assign(tax=lambda d: d["total"] * 0.2)
)
print(result)The lambda receives the intermediate frame, so the second step can use the total column created by the first.
Common errors
ValueError: The truth value of a Series is ambiguous. You used a Series where Python expects a single boolean, for exampleif df["a"] > 0:. Use a mask ornp.whereinstead. The next two chapters cover them.TypeErrorfrommathfunctions. Use the NumPy equivalent.- All-
NaNresult after dividing a frame by a Series. Addaxis=0to the method form, for exampledf.div(s, axis=0). - A sum with one value per column. You omitted
axis=1. - Results that differ from the loop by tiny amounts. Floating-point operations can group differently. Compare with
np.allcloserather thanequalswhen floats are involved.
Exercise
A DataFrame orders has columns price (float), qty (int) and discount (a fraction such as 0.1). A loop computes row["price"] * row["qty"] * (1 - row["discount"]) for each row. Write the column expression that replaces it. Then name the argument you need if you also want each of the three quarter columns q1, q2, q3 divided by a total column.
Show answer
orders["net"] = orders["price"] * orders["qty"] * (1 - orders["discount"]). The scalar 1 is broadcast across the discount column. To divide the quarter columns by total, use orders[["q1", "q2", "q3"]].div(orders["total"], axis=0). The argument is axis=0, which makes pandas match the total values to rows instead of to column names.
Exercise
a = pd.Series([2.0, np.nan, 4.0]) and b = pd.Series([1.0, 5.0, np.nan]). What does a + b return, and how do you get 2.0 + 1.0 = 3.0, 5.0 and 4.0 instead?
Show answer
a + b returns 3.0, NaN, NaN because the operator propagates missing values. a.add(b, fill_value=0) returns 3.0, 5.0, 4.0 because each missing value is replaced with 0 before the addition.