BBampaa

Lessons › Python

Python lesson

New columns

Maths on a column runs on every row at once. It's like writing a formula once and filling it down the whole column.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

One line creates a VAT column for all eight orders:

df["VAT"] = df["Revenue"] * 0.075
df.head()

Output:

Order Day Store Product Qty Revenue VAT
0 O101 Mon Lagos Earbuds 2 70 5.25
1 O102 Mon Abuja Charger 1 15 1.125
2 O103 Tue Lagos Phone case 3 24 1.7999999999999998
3 O104 Wed Lagos Earbuds 1 35 2.625
4 O105 Wed Abuja Earbuds 4 140 10.5

Key points

df["VAT"] = ...Create a new column. Every row gets its own answer.
df["Revenue"] * 0.075Maths on a column happens on every row.
df["Revenue"] / df["Qty"]Two columns can be combined, row by row.

Put together: df["Price"] = df["Revenue"] / df["Qty"].

Practice

Try each one in your head first, then open the answer.

1. Build a line that adds a column called Double: revenue times 2.
df["Double"] = df["Revenue"] * 2
2. Build a line that adds a column called Price: revenue divided by quantity.
df["Price"] = df["Revenue"] / df["Qty"]
3. Add a column called Price: revenue divided by quantity.
df["Price"] = df["Revenue"] / df["Qty"]
4. Add a column called VAT: revenue times 0.075.
df["VAT"] = df["Revenue"] * 0.075
5. Add a column called Bonus: quantity times 5.
df["Bonus"] = df["Qty"] * 5

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed