Sub topic 8
Vectorized arithmetic and methods
This chapter assumes you can create a Series and a DataFrame, read a column with df["col"], and know what an Index is. Basic NumPy awareness helps but is not required.
What vectorized means
A vectorized operation applies to a whole Series or column at once. You do not write a Python loop. pandas hands the work to compiled code, which is much faster than iterating row by row. The code is also shorter and easier to read.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
pop_k = df["pop_m"] * 1000 # every value times 1000
share = df["pop_m"] / df["pop_m"].sum()
print(pop_k.tolist()) # [700.0, 10700.0, 3100.0, 2800.0]
print(share.round(2).tolist()) # [0.04, 0.58, 0.17, 0.15]The first line multiplies each value by a scalar. The second divides each value by a number computed from the whole column. A scalar is a single value, and pandas applies it to every element. This is called broadcasting.
Operators, comparisons, and methods
Arithmetic operators (+, -, *, /, **) work element by element. Comparison operators (>, ==) do the same and return a Series of True and False values. Those results are the boolean masks you use for filtering.
Many operations also exist as methods. Methods are useful when you need extra options, such as fill_value, which a bare operator cannot take.
| Task | Operator | Method |
|---|---|---|
| Add | `a + b` | `a.add(b)` |
| Subtract | `a - b` | `a.sub(b)` |
| Multiply | `a * b` | `a.mul(b)` |
| Divide | `a / b` | `a.div(b)` |
Reducing methods turn a column into one number: sum(), mean(), min(), max(), std(). Transforming methods return a Series of the same length: round(), abs(), cumsum(), clip().
import pandas as pd
s = pd.Series([4, -1, 9])
print(s.abs().tolist()) # [4, 1, 9]
print(s.cumsum().tolist()) # [4, 3, 12]
print(s.clip(lower=0).tolist()) # [4, 0, 9]
print(s.mean()) # 4.0On a DataFrame, reducing methods work on each column by default. Pass axis=1 to reduce across each row instead.
Common errors
- Looping when you do not need to. Code like
for x in df["pop_m"]: ...is slow on large data. Look for an operator or method first. - Mixing up a reduction and a transform.
s.sum()returns one value.s.cumsum()returns a Series. Check the result's shape if you are unsure. - Applying arithmetic to text columns. Multiplying a column of strings by a number repeats the strings. Dividing raises a
TypeError. Checkdf.dtypesfirst. - Forgetting that operations return new objects.
s.round(1)does not changes. Assign the result to keep it.
Exercise
Given s = pd.Series([2, 4, 6]), what does (s * 2).sum() return, and what does s.cumsum() return?
Show answer
(s 2).sum() returns 24, because s 2 is [4, 8, 12] and the sum is 24. s.cumsum() returns a Series with the values [2, 6, 12].
Exercise
Write one line that returns a boolean Series marking which values in df["pop_m"] exceed the column's mean.
Show answer
df["popm"] > df["popm"].mean()