Python lesson
Fixing capitals with .str
strip first, then title: ' lagos' becomes 'Lagos', and both Abujas now match.
Try this lesson free →Example
lagos, ABUJA, abuja: to pandas these are all different. .str.title() fixes the capitals on every value:
df["City"] = df["City"].str.strip().str.title()
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
.str.title()Capitalise each word: ada obi becomes Ada Obi.
.str.upper() .str.lower()All capitals, or all small letters.
.str.strip().str.title()Chain them: remove the spaces first, then fix the capitals.
Cleaning comes before analysis: 'abuja' and 'ABUJA' would otherwise count as two different cities.
Practice
1. Build a line that fixes the capitals in the City column.
df["City"] = df["City"].str.title()2. Build a line that makes every Name all capitals.
df["Name"] = df["Name"].str.upper()3. Clean the Name column: remove the extra spaces, then make it title case.
df["Name"] = df["Name"].str.strip().str.title()4. Clean the City column: remove the extra spaces, then make it title case.
df["City"] = df["City"].str.strip().str.title()5. Make every City all small letters.
df["City"] = df["City"].str.lower()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 →