Sub topic 3
Computing new columns with vectorized operations
This chapter assumes you can build a DataFrame, select a column by name, and assign to a new column name. Earlier chapters covered those steps.
The working model
A DataFrame column is a Series. When you apply an operator to a Series, pandas runs the operation across every row in compiled code and returns a new Series. This is called a vectorized operation. You don't write a loop, and the result is usually much faster than a Python loop.
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"] >= 5
df["sale_price"] = (df["price"] * 0.9).round(2)
print(df)The first line multiplies price and qty row by row. The second compares each qty to 5 and gives a boolean column. The third multiplies by a scalar. A scalar is a single value, and pandas applies it to every row.
Operators you can use
| Kind | Operators | Result | Column |
|---|---|---|---|
| Arithmetic | `+ - * / // % **` | Numeric Series | |
| Comparison | `== != < <= > >=` | Boolean Series | |
| Logical | `&` `\ | ` `~` | Boolean Series |
| Methods | `.round()`, `.abs()`, `.clip()` | Series of the same length |
Common errors
Using `and` and `or`
Python's and, or, and not expect a single truth value. A Series has many, so pandas raises a ValueError. Use &, |, and ~, and wrap each comparison in parentheses, because & binds more tightly than > or ==.
df["bulk_and_cheap"] = (df["qty"] >= 5) & (df["price"] < 5)Index alignment
When you combine two Series, or assign one to a column, pandas matches rows by index label, not by position. Labels that don't match produce NaN.
bonus = pd.Series([100, 200], index=[0, 2])
df["bonus"] = bonus
print(df["bonus"])Row 1 gets NaN because bonus has no label 1. The column also becomes float, because integers can't hold NaN. If you want position-based behavior, convert the right side with .to_numpy(). The length must then match exactly, or pandas raises a ValueError.
df["rank_points"] = pd.Series([3, 2, 1]).to_numpy() * 10Division and text
Dividing by zero doesn't raise an error. A float division gives inf, or NaN for 0 / 0. Check for these values if you divide by a column that can contain zeros.
Operators also follow the column's dtype. + on two string columns concatenates them, and * on a string column fails. If numbers were read in as text, "3" + "4" gives "34" rather than 7. Convert the column first. The next chapters cover conversion.
Combining columns
Expressions can mix columns, scalars, and methods. Compute intermediate values on separate lines if one expression gets hard to read.
df["subtotal"] = df["price"] * df["qty"]
df["tax"] = df["subtotal"] * 0.2
df["grand_total"] = df["subtotal"] + df["tax"]Each line sees the columns created by the lines before it. That is the main difference from assign(), which the next chapter covers.
Exercise
You run df["flag"] = df["qty"] > 5 and df["price"] < 20 and get a ValueError. Rewrite the line so it works, and say why the original failed.
Show answer
Use df["flag"] = (df["qty"] > 5) & (df["price"] < 20). The and keyword needs one True or False value, but each comparison produces a whole Series. The & operator combines the two Series row by row, and the parentheses are required because & binds more tightly than the comparison operators.