Python lesson
Removing spaces with .str.strip()
' ada obi' becomes 'ada obi'. Invisible spaces would otherwise stop names from matching.
Try this lesson free →Example
This customer list has stray spaces. .str applies a text method to every value in a column at once:
df["Name"] = df["Name"].str.strip()
dfName City Revenue
0 ada obi lagos 70
1 TUNDE BAKARE ABUJA 15
2 grace eze abuja NaN
3 Musa Bello Kano 40
4 Musa Bello Kano 40Key points
.strApplies a text method to every value in the column.
.str.strip()Removes the spaces at the start and end of each value.
df["Name"] = ...Store the result back in the column, or the change is lost.
Put together: df["Name"] = df["Name"].str.strip().
Practice
1. Build a line that removes the extra spaces from the Name column.
df["Name"] = df["Name"].str.strip()2. Build a line that removes the extra spaces from the City column.
df["City"] = df["City"].str.strip()3. Remove the extra spaces from the Name column, then show the first 2 rows.
df["Name"] = df["Name"].str.strip()
df.head(2)4. Remove the extra spaces from the City column, then show how many different cities there are.
df["City"] = df["City"].str.strip()
df["City"].nunique()5. Remove the extra spaces from both Name and City, one line each.
df["Name"] = df["Name"].str.strip()
df["City"] = df["City"].str.strip()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 →