← Learning Hub
Intermediate

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
You can edit this code.

Labels from conditions

Example
You can edit this code.

map and apply

Example
You can edit this code.
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
You can edit this code.
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)