Sub topic 2
Replacing row arithmetic with column expressions
This chapter assumes you know basic Python (functions, loops, dictionaries), how to build and index a pandas DataFrame and Series, and the basics of NumPy arrays. Here you will turn row-by-row arithmetic into expressions on whole columns.
The working model
A pandas column is a Series backed by a typed array, usually a NumPy array. An operator such as * on two Series runs once, in compiled code, over every element. A Python loop runs the interpreter once per row and builds a Series object for each row when you use iterrows.
Applying one operation to many values at once is called vectorisation. When you write df["price"] * df["qty"], you describe the result for all rows. You do not describe how to step through them.
From loop to column expression
Start with a loop that computes a line total for each 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"]Both versions give the same numbers. The second has no loop, no list to fill and no assignment from a Python list. The result is a new Series that shares the DataFrame's index.
The same idea works for every arithmetic operator: +, -, *, /, //, % and **. You can combine them in a single expression.
df["discounted"] = df["price"] * df["qty"] * 0.9 - 2.0Broadcasting scalars
In * 0.9 and - 2.0, a single number is combined with every element of a column. This is called broadcasting: pandas (through NumPy) stretches the scalar to match the column's length. You never write a loop to apply a constant.
Broadcasting also applies to several columns at once.
df[["price", "qty"]] * 2This returns a DataFrame with both columns doubled.
Comparisons and functions are column-wise too
Comparison operators work on whole columns and return a column of booleans.
df["price"] > 12The result is False, True, True. Later chapters use these boolean columns to filter and to choose values.
NumPy functions also accept columns directly. For example, np.sqrt(df["price"]) and np.log(df["total"]) return Series with the same index. Prefer these over math.sqrt inside a loop, because the functions in the math module only accept single numbers.
Common errors
- Using
row[...]inside a column expression. Writedf["price"], notrow["price"]. There is norowvariable when you work on whole columns. - Using Python's
and,orandnoton columns. These raiseValueError: The truth value of a Series is ambiguous. Use&,|and~, and put each comparison in parentheses. - Using
mathfunctions on a Series.math.sqrt(df["price"])raises aTypeError. Usenp.sqrtinstead. - Assigning a list of the wrong length. A list must match the number of rows. A Series result avoids this problem, because pandas matches it to the index.
mask = (df["price"] > 12) & (df["qty"] >= 3)What happens when the indexes differ
When you combine two Series, pandas matches elements by index label, not by position. If the labels differ, the unmatched positions become NaN. This matters when you combine columns from different DataFrames. A later chapter covers index alignment in detail. For now, remember that columns of one DataFrame always share an index, so expressions like the ones above are safe.
Exercise
A DataFrame orders has columns net (float) and tax_rate (float, such as 0.2). Write one line that adds a column gross equal to net plus the tax on it, without a loop.
Show answer
orders["gross"] = orders["net"] (1 + orders["tax_rate"]). Equivalent: orders["net"] + orders["net"] orders["tax_rate"]. Both operate on whole columns and return a Series aligned with the index.
Exercise
Why does if df["price"] > 12 and df["qty"] >= 3: raise an error, and how do you write the combined condition on columns?
Show answer
Python's and needs a single True or False, but a Series holds many values, so pandas raises "The truth value of a Series is ambiguous". Use the element-wise operator with parentheses: (df["price"] > 12) & (df["qty"] >= 3).