Sub topic 8
Vectorized arithmetic and methods
This chapter assumes you can create a Series and a DataFrame, read their dtypes, and select data with loc, iloc, and boolean masks. It covers how pandas applies an operation to a whole column at once, which methods you will use most, and the mistakes that slow code down or give wrong answers.
What "vectorized" means
A vectorized operation applies to every element of a Series or column in one expression, with no Python for loop. When you write df["pop_m"] * 1000, pandas hands the work to compiled code (through NumPy) that loops over the underlying array in C.
This gives you two things:
- Short code. One expression replaces a loop and an accumulator list.
- Speed. Compiled loops are typically tens to hundreds of times faster than a Python loop over the same data.
import pandas as pd
pop_m = pd.Series([0.7, 10.7, 3.1, 2.8], index=["Oslo", "Lima", "Pune", "Rome"])
# Loop version: builds a list, then loses the labels
looped = [p * 1000 for p in pop_m]
# Vectorized version: keeps the index
pop_k = pop_m * 1000
print(looped)
print(pop_k)The loop returns a plain list. The vectorized expression returns a Series with the same index as the input. Keeping labels is a core feature, and the next chapter shows what happens when two Series have different labels.
Arithmetic and comparison operators
All the usual operators work on a Series and on DataFrame columns: +, -, *, /, //, %, **. Comparisons (>, ==, !=) return boolean Series, which you already use as masks.
A scalar is applied to every element. This is called broadcasting, because the single value is stretched to match the shape of the data.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"area_km2": [454, 2672, 331, 1285],
})
df["density"] = df["pop_m"] * 1_000_000 / df["area_km2"]
print(df[["city", "density"]].round(0))Here two columns combine row by row. The row for Oslo divides Oslo's population by Oslo's area. Pandas matches rows by index label, not by position. In this example both columns share the same index, so the two ways of matching agree.
Each operator also has a method form: add, sub, mul, div, floordiv, mod, pow. The method form accepts options the operator does not, such as fill_value (used in the next chapter) and axis (see below).
| Operator | Method | Notes |
|---|---|---|
| `a + b` | `a.add(b)` | `fill_value` available |
| `a - b` | `a.sub(b)` | |
| `a * b` | `a.mul(b)` | |
| `a / b` | `a.div(b)` | Division by zero gives `inf`, not an error |
| `a // b` | `a.floordiv(b)` | |
| `a ** b` | `a.pow(b)` |
Methods that act on whole columns
Beyond operators, Series and DataFrames have many vectorized methods. They fall into three groups.
Reductions collapse a column to one value: sum, mean, median, min, max, std, count, nunique. They skip missing values by default.
Transformations return an object of the same length: round, abs, clip, cumsum, diff, pct_change, rank, shift.
Element tests return booleans: between, isin, isna.
import pandas as pd
s = pd.Series([3, 8, 5, 12, 7], name="visits")
print(s.sum()) # 35
print(s.mean()) # 7.0
print(s.cumsum().tolist()) # [3, 11, 16, 28, 35]
print(s.diff().tolist()) # [nan, 5.0, -3.0, 7.0, -5.0]
print(s.clip(lower=5, upper=10).tolist()) # [5, 8, 5, 10, 7]
print(s.between(5, 8).tolist()) # [False, True, True, False, True]Note that diff produces NaN in the first position because there is no earlier value to subtract. That also turns the integer result into floats, since NaN is a float value in the default NumPy-backed dtypes.
Operating across a DataFrame: the axis argument
On a DataFrame, reductions work down each column by default. Pass axis=1 to work across each row instead.
import pandas as pd
scores = pd.DataFrame(
{"math": [90, 70, 85], "art": [60, 95, 80], "music": [75, 85, 90]},
index=["Ana", "Ben", "Chi"],
)
print(scores.mean()) # one value per subject
print(scores.mean(axis=1)) # one value per student
print(scores.max(axis=1))Arithmetic between a DataFrame and a Series has a related rule. By default the Series index is matched to the DataFrame's columns. To match it to the rows instead, use a method form with axis=0.
import pandas as pd
scores = pd.DataFrame(
{"math": [90, 70, 85], "art": [60, 95, 80]},
index=["Ana", "Ben", "Chi"],
)
bonus = pd.Series([5, 0, 10], index=["Ana", "Ben", "Chi"])
# scores + bonus would try to match bonus labels to column names and give all NaN
print(scores.add(bonus, axis=0))Boolean logic and string operations
Comparisons combine with & (and), | (or), and ~ (not). Each comparison needs its own parentheses, because & binds more tightly than > or ==.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
mask = (df["pop_m"] > 1) & (df["region"] == "EU")
print(df[mask])Python's and, or, and not do not work here. They ask whether the whole Series is true or false, and pandas raises ValueError: The truth value of a Series is ambiguous.
String columns have vectorized methods under the .str accessor, such as .str.upper(), .str.contains("o"), and .str.len(). These are convenient, but they still run a Python-level operation per element internally, so they are slower than numeric operations.
Choosing between vectorized code and apply
When no built-in method fits, Series.apply(func) and DataFrame.apply(func, axis=1) call a Python function per element or per row. They are flexible but run at loop speed.
A practical order of preference:
- A built-in operator or method (
*,clip,between). - A combination of those, such as
np.where(cond, a, b)orSeries.where. applywith a function, only when the logic cannot be expressed otherwise.
import numpy as np
import pandas as pd
df = pd.DataFrame({"pop_m": [0.7, 10.7, 3.1, 2.8]})
# Vectorized: runs in compiled code
df["size"] = np.where(df["pop_m"] >= 3, "large", "small")
# Equivalent with apply: same result, slower on large data
df["size_apply"] = df["pop_m"].apply(lambda p: "large" if p >= 3 else "small")
print(df)How the pieces fit
Common errors
- Using
and/orinstead of&/|, which raises the "truth value is ambiguous" error. - Forgetting parentheses around each comparison in a combined mask.
- Calling
df + serieswhen the Series holds one value per row, which produces all-NaN columns. - Expecting integer output from
difforshift, which return floats once NaN appears. - Reaching for
apply(axis=1)on a large DataFrame when an operator on whole columns would do. - Assuming reductions fail on missing values. They skip NaN by default, so
meanof[1, NaN, 3]is 2.0, not NaN. Passskipna=Falseto change this.
Exercise
A DataFrame df has numeric columns price and qty, and a Series discount indexed by the same row labels as df. Write one expression that computes a revenue Series equal to price * qty reduced by discount for each row, without a loop. Then say why df.sub(discount) would be wrong for this.
Show answer
Use revenue = df["price"] * df["qty"] - discount. Both sides are Series sharing the row index, so labels match row by row. df.sub(discount) defaults to axis=1, which matches the Series labels to the column names price and qty. Nothing aligns, so the result is NaN everywhere. It would also subtract from each column separately, which is not the revenue calculation.
Exercise
Given s = pd.Series([4, 9, 2, 7]), what do s.diff().tolist() and s.cumsum().tolist() return, and why is the first diff value not an integer?
Show answer
s.diff().tolist() returns [nan, 5.0, -7.0, 5.0] and s.cumsum().tolist() returns [4, 13, 15, 22]. The first diff value has no previous element, so it is NaN. NaN is a float, so the whole result is converted to float64.