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 →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"
dfName Store Region
0 Ada Lagos South-West
1 Musa Abuja North
2 Grace Abuja North
3 Tunde Lagos South-WestKey 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
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"
df3. Tunde has moved to Abuja. Change his Store, then show df.
df.loc[df["Name"] == "Tunde", "Store"] = "Abuja"
df4. Add a column called Bonus: 50 for the Lagos staff and 0 for everyone else.
df["Bonus"] = 0
df.loc[df["Store"] == "Lagos", "Bonus"] = 505. 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 →