Sub topic 3
Computing new columns with vectorized operations
This chapter assumes you can build a DataFrame, select a column by name, and write basic Python expressions. You should know that df["price"] returns a Series. NumPy knowledge helps but is not required.
A vectorized operation is an expression that works on a whole column at once. You don't write a loop over rows. pandas applies the operation to every element in compiled code and returns a new Series. Most derived columns are built this way, so the details matter: how operators behave, how rows are matched up, and what happens to missing values.
The working model
An operator between Series produces a new Series of the same length. Nothing changes in the original columns. The result changes the DataFrame only when you assign it to a column name.
Arithmetic between columns and scalars
The arithmetic operators are +, -, *, /, // (floor division), % (remainder) and ** (power). Between two columns, they work row by row. Between a column and a single number, the number is broadcast, meaning it is applied to every row.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df["total"] = df["price"] * df["qty"]
df["total_with_tax"] = df["total"] * 1.2
df["price_cents"] = df["price"] * 100
df["batches_of_4"] = df["qty"] // 4
df["leftover"] = df["qty"] % 4
print(df)The total column holds 15.0, 36.0 and 60.0. A new column can use any column that already exists, including one you created a line earlier.
Dtype results
The result dtype follows normal NumPy rules. int * float gives float64. int / int always gives float64, even when the division is exact. // on two integer columns stays integer. If you need a particular type, convert it explicitly (a later chapter covers astype).
Division by zero
Dividing by zero does not raise an exception. It returns infinity or NaN:
import pandas as pd
s = pd.Series([1, 0, -1])
print(s / 0)This prints inf, NaN and -inf. An inf in a derived column can break later statistics without any warning, so check denominators when a ratio is involved.
Comparisons and boolean columns
Comparison operators (==, !=, <, <=, >, >=) return a boolean Series. You can store it as a flag column or use it as a filter mask.
Combine conditions with & (and), | (or) and ~ (not). Wrap every comparison in parentheses.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df["total"] = df["price"] * df["qty"]
df["is_bulk"] = df["qty"] >= 3
df["big_cheap"] = (df["total"] > 30) & (df["qty"] < 5)
df["not_pen"] = ~(df["item"] == "pen")
print(df)big_cheap is False, True, True. Boolean columns are useful on their own, and they can also be summed or averaged. df["is_bulk"].sum() counts the True values, and df["is_bulk"].mean() gives their share.
Why `and` and `or` fail
Python's and, or and not ask whether the whole Series is true or false, and that has no answer. pandas raises an error:
import pandas as pd
df = pd.DataFrame({"a": [1, 5], "b": [4, 2]})
try:
df["flag"] = (df["a"] > 2) and (df["b"] > 3)
except ValueError as err:
print(err)The message says that the truth value of a Series is ambiguous. Use &, | and ~ instead.
Index alignment
When you combine two Series, pandas matches rows by index label, not by position. Labels present in only one Series produce NaN.
import pandas as pd
a = pd.Series([1, 2, 3], index=["x", "y", "z"])
b = pd.Series([10, 20, 30], index=["y", "z", "w"])
print(a + b)
print(a.add(b, fill_value=0))The first result has NaN for w and x, 12.0 for y and 23.0 for z. The method form add accepts fill_value, which substitutes a value for a missing side before computing. The second result is 30.0, 1.0, 12.0 and 23.0 for w, x, y and z.
The other operators have method forms too:
| Operator | Method | Operator | Method |
|---|---|---|---|
| `+` | `add` | `//` | `floordiv` |
| `-` | `sub` | `%` | `mod` |
| `*` | `mul` | `**` | `pow` |
| `/` | `div` | `==` | `eq` |
Use the method form when you need fill_value, or when a chain reads better with it, such as df["price"].mul(df["qty"]).
Alignment also applies on assignment. Within one DataFrame the index is shared, so row order rarely matters. It does matter when the right-hand side comes from a different object:
import pandas as pd
df = pd.DataFrame({"price": [1.5, 12.0, 30.0]})
other = df.sort_values("price", ascending=False)
df["aligned"] = other["price"]
df["positional"] = other["price"].to_numpy()
print(df)aligned matches the original prices row for row, because labels are used. positional is 30.0, 12.0, 1.5, because .to_numpy() drops the labels and the values land by position. Use .to_numpy() only when you really mean position. A frame with duplicate index labels can also fail or multiply rows during alignment, so call reset_index(drop=True) first if your index has repeats.
Functions on whole columns
Many calculations are already available as Series methods: abs(), round(2), clip(lower, upper), cumsum(), diff(), shift(), rank(), and pct_change(). NumPy universal functions (functions that apply to each element) accept a Series and return a Series with the same index.
import numpy as np
import pandas as pd
df = pd.DataFrame({"price": [1.5, 12.0, 30.0], "qty": [10, 3, 2]})
df["total"] = df["price"] * df["qty"]
df["log_total"] = np.log(df["total"])
df["share"] = (df["total"] / df["total"].sum()).round(3)
df["running_total"] = df["total"].cumsum()
df["change"] = df["total"].diff()
df["capped_qty"] = df["qty"].clip(upper=5)
print(df)share uses a column-level result, df["total"].sum(), which is a single number that is broadcast against every row. This pattern, a column divided by an aggregate of itself, is common. Per-group aggregates need groupby().transform(), which a later chapter covers.
diff() leaves NaN in the first row, since the first row has no predecessor. shift() and pct_change() do the same. Expect those missing values.
Missing values and mixed types
NaN propagates through arithmetic: 5 + NaN is NaN. Comparisons with NaN are False, including NaN != 5's sibling case NaN == NaN. If a column has missing values, the derived boolean column silently records False for those rows. Check with isna() first when that distinction matters. A later chapter covers missing values in more detail.
An integer column that contains NaN is stored as float64. Text columns need conversion before arithmetic. If a column of numbers was read as strings, df["price"] * 2 repeats the strings instead of doubling the numbers. Convert it with pd.to_numeric first.
Common errors
- Length mismatch. Assigning a list or array whose length differs from the number of rows raises
ValueError: Length of values ... does not match length of index. Series are aligned by label, and plain lists must match exactly. - Parentheses omitted in boolean expressions, described above.
- Unexpected NaN from combining Series with different indexes.
- Overwriting by accident.
df["price"] = df["price"] * 100replaces the original column. Give derived values a new name when you need the original. - Loops where a vector would do.
forloops over rows work but are often tens to hundreds of times slower than the vectorized form, and they are longer to read.
Exercise
A DataFrame has columns "a" and "b". You want a boolean column "both" that is True when a is greater than 10 and b is less than 5. A colleague writes df["both"] = df["a"] > 10 and df["b"] < 5. What goes wrong, and what is the correct line?
Show answer
Python's and tries to convert a whole Series to a single True or False, so pandas raises "ValueError: The truth value of a Series is ambiguous". The correct line is df["both"] = (df["a"] > 10) & (df["b"] < 5), with & for element-wise and, and parentheses around each comparison.
Exercise
s1 = pd.Series([1, 2], index=["a", "b"]) and s2 = pd.Series([10, 20], index=["b", "c"]). What does s1 + s2 return, and how would you get 1.0, 12.0 and 20.0 for a, b and c instead?
Show answer
s1 + s2 matches by label, so it returns NaN for a, 12.0 for b, and NaN for c. Use s1.add(s2, fill_value=0), which treats a missing side as 0 and gives 1.0, 12.0 and 20.0.