Data analysis with pandas · Lesson 9 of 15
Cleaning text and types
Tidy messy text with str methods, turn text into numbers with astype and to_numeric, and turn date strings into real dates with to_datetime.
Data typed by people is messy: extra spaces, mixed capitals, prices with a € sign, dates as text. pandas cannot add up "€3.50" or sort "5 Mar" as a date until you clean them. This lesson shows the usual fixes.
Text methods with .str
A text column has a .str part with the familiar string methods, applied to every value: .str.strip(), .str.lower(), .str.title(), .str.replace() and more. They work like str.strip(), str.title() and str.replace() on one string.
import pandas as pd
df = pd.DataFrame({"name": [" ana ", "BEN", "chloe ", "Dev"],
"city": ["porto", " Lyon", "LEEDS", "oslo "]})
df["name"] = df["name"].str.strip().str.title()
df["city"] = df["city"].str.strip().str.capitalize()
print(df)
print(df["name"].str.len().tolist())name city 0 Ana Porto 1 Ben Lyon 2 Chloe Leeds 3 Dev Oslo [3, 3, 5, 3]
Methods can be chained: strip first, then fix the capitals.
Text into numbers
Remove the symbols with str.replace (regex=False, the default since pandas 2.0, takes characters such as . and $ literally; writing it out makes that clear to the reader), then convert with astype(float). A decimal comma needs replacing with a dot first.
import pandas as pd
prices = pd.Series(["€3.50", "€12.00", "€0.99", "€7.25"])
clean = prices.str.replace("€", "", regex=False).astype(float)
print(clean)
print("Total:", clean.sum())
eu = pd.Series(["1,80", "6,45"])
print(eu.str.replace(",", ".", regex=False).astype(float).tolist())0 3.50 1 12.00 2 0.99 3 7.25 dtype: float64 Total: 23.74 [1.8, 6.45]
If some values cannot be read as numbers at all, astype stops with an error. pd.to_numeric(..., errors="coerce") turns those values into NaN instead, so you can find and handle them as in Missing data: isna, fillna, dropna.
import pandas as pd
qty = pd.Series(["3", "5", "n/a", "2", "?"])
nums = pd.to_numeric(qty, errors="coerce")
print(nums.tolist())
print("Bad values:", qty[nums.isna()].tolist())
print("Total:", int(nums.sum()))[3.0, 5.0, nan, 2.0, nan] Bad values: ['n/a', '?'] Total: 10
Text into dates
pd.to_datetime turns date strings into real dates. Give the pattern with format=: %Y is the year, %m the month, %d the day. Then the .dt part gives the year, month, weekday and more.
import pandas as pd
df = pd.DataFrame({"day": ["05/03/2026", "14/03/2026", "06/04/2026"],
"sales": [120, 95, 140]})
df["day"] = pd.to_datetime(df["day"], format="%d/%m/%Y")
print(df)
print(df["day"].dt.month.tolist())
print(df["day"].dt.day_name().tolist())day sales 0 2026-03-05 120 1 2026-03-14 95 2 2026-04-06 140 [3, 3, 4] ['Thursday', 'Saturday', 'Monday']
Dates print as year-month-day, whatever format they came in.
format=, pandas has to guess, and 05/03/2026 could be 5 March or 3 May. Always say which pattern your file uses.Types and duplicates
astype changes a column's type: astype("int64"), astype(str). drop_duplicates() removes repeated rows, a common problem when files are joined together.
import pandas as pd
df = pd.DataFrame({"code": [101, 102, 102, 103],
"item": ["pen", "pad", "pad", "ink"]})
df = df.drop_duplicates()
df["code"] = df["code"].astype(str)
print(df)
print(df.dtypes)code item 0 101 pen 1 102 pad 3 103 ink code object item object dtype: object
✎ Exercise
Clean the price column: remove the $ sign and spaces, turn it into numbers and print the total. Then make the item names lower case and print them as a list.
Hint: Chain .str.strip(), .str.replace("$", "", regex=False) and .astype(float).
import pandas as pd
df = pd.DataFrame({"item": ["Tea", "CAKE", "Milk"],
"price": ["$2.50 ", " $4.00", "$1.20"]})
# your code here
Expected output:
Total: 7.7 ['tea', 'cake', 'milk']
Show a solution
import pandas as pd
df = pd.DataFrame({"item": ["Tea", "CAKE", "Milk"],
"price": ["$2.50 ", " $4.00", "$1.20"]})
df["price"] = df["price"].str.strip().str.replace("$", "", regex=False).astype(float)
print("Total:", df["price"].sum())
print(df["item"].str.lower().tolist())Total: 7.7 ['tea', 'cake', 'milk']
Check yourself
1. Which line removes spaces around every name in a column?
String methods on a column go through .str.
2. What does pd.to_numeric(s, errors="coerce") do with the value "n/a"?
errors="coerce" replaces anything it cannot read with NaN.
3. Which format reads "25/12/2026"?
Day, then month, then the four-digit year.