BBampaa

Lessons › Python

Python lesson

Changing chosen rows

Musa and Grace work in Abuja, so only their Region changed. Ada and Tunde in Lagos kept South-West. One line fixes every matching row, however many there are.

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

Example

df.loc[test, column] = value changes that column, only on the rows where the test is True:

df.loc[df["Store"] == "Abuja", "Region"] = "North"
df

Output:

Name Store Region
0 Ada Lagos South-West
1 Musa Abuja North
2 Grace Abuja North
3 Tunde Lagos South-West

Key points

df.loc[test, "Region"] = "North"Change Region, only where the test is True.
The test firstWhich rows. After the comma, which column.
It changes dfNo df = needed: .loc writes straight into the table.
A new columnName a column that isn't there and .loc creates it.

Change chosen rows with df.loc[df["Store"] == "Abuja", "Region"] = "North".

Practice

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

1. Build a line that sets Region to North for the Abuja rows.
df.loc[df["Store"] == "Abuja", "Region"] = "North"
2. Set Region to North for every Abuja row, then show df.
df.loc[df["Store"] == "Abuja", "Region"] = "North"
df
3. Tunde has moved to Abuja. Change his Store, then show df.
df.loc[df["Name"] == "Tunde", "Store"] = "Abuja"
df
4. Add a column called Bonus: 50 for the Lagos staff and 0 for everyone else.
df["Bonus"] = 0
df.loc[df["Store"] == "Lagos", "Bonus"] = 50
5. Grace has moved to Lagos. Update her row, then show how many staff each store has.
df.loc[df["Name"] == "Grace", "Store"] = "Lagos"
df["Store"].value_counts()

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