New Columns: Calculations, apply and np.where
Most insights come from calculated columns: amount = qty × price, a size label, a delivery zone. Column maths is fast and clear; np.where and map handle labels; apply handles complex rules but is slower.
Calculated columns
Example
Labels from conditions
Example
map and apply
Example
apply with axis=1 is easy to write but slow on big tables. Prefer column maths and np.where when you can - they work on the whole column at once.assign: several columns in one go
Example
Key points
- Create columns with column maths.
- np.where and pd.cut make labels; map uses a dictionary.
- Prefer vectorised operations over apply.
📝 Test yourself
1. What does np.where(cond, a, b) give?
2. What does df.apply(f, axis=1) do?
3. Fill in the method that swaps values using a dictionary:
df["zone"] = df["city"].(zones)
