Cleaning Wrong Format
A column should hold one kind of value in one format. Problems appear when it doesn't: dates written in several styles, numbers stored as text with currency signs or thousands separators, or "yes"/"Yes"/"Y" all meaning the same thing. Until these are fixed, pandas can't sort, compare or calculate correctly.
Spotting the problem with dtypes
The first clue is usually the dtype. A column of prices that shows up as object means pandas found something that isn't a number:
import pandas as pd
orders = pd.DataFrame({
"order": ["A-1", "A-2", "A-3", "A-4"],
"amount": ["12.50", "$8.00", "1,250.00", "19.99"],
"paid": ["yes", "Yes", "Y", "no"],
})
print(orders.dtypes)
print(orders["amount"].sum())order object
amount object
paid object
dtype: object
12.50$8.001,250.0019.99
Adding text "numbers" just glues the strings together, clearly not what we want.
Text to numbers
Strip the unwanted characters with the .str string methods, then convert with pd.to_numeric():
import pandas as pd
orders = pd.DataFrame({
"order": ["A-1", "A-2", "A-3", "A-4"],
"amount": ["12.50", "$8.00", "1,250.00", "19.99"],
})
orders["amount"] = pd.to_numeric(
orders["amount"].str.replace("quot;, "", regex=False)
.str.replace(",", "", regex=False)
)
print(orders)
print(orders["amount"].dtype, orders["amount"].sum()) order amount
0 A-1 12.50
1 A-2 8.00
2 A-3 1250.00
3 A-4 19.99
float64 1290.49
When some values can't be converted at all, errors="coerce" turns them into NaN instead of raising an error. You can then treat them as empty cells:
import pandas as pd
raw = pd.Series(["42", "17", "n/a", "8", "unknown"])
nums = pd.to_numeric(raw, errors="coerce")
print(nums)
print("Could not convert:", raw[nums.isna()].to_list())0 42.0
1 17.0
2 NaN
3 8.0
4 NaN
dtype: float64
Could not convert: ['n/a', 'unknown']
Mixed date formats
pd.to_datetime() converts text to real datetime values. If one column mixes formats, pass format="mixed" so pandas works out each value separately:
import pandas as pd
visits = pd.DataFrame({
"patient": ["P1", "P2", "P3", "P4"],
"visit": ["2024-03-05", "2024/03/07", "20240311", "March 14, 2024"],
})
visits["visit"] = pd.to_datetime(visits["visit"], format="mixed")
print(visits)
print(visits.dtypes) patient visit
0 P1 2024-03-05
1 P2 2024-03-07
2 P3 2024-03-11
3 P4 2024-03-14
patient object
visit datetime64[ns]
dtype: object
Now every value is a datetime64 and you can sort, subtract and filter by date.
Note: Ambiguous dates like
03/04/2024(March 4th or April 3rd?) are a classic trap. If you know the convention, say so withdayfirst=Trueor an explicit format such asformat="%d/%m/%Y".
Dates that can't be parsed
As with numbers, errors="coerce" turns values that aren't dates into NaT. Then you decide: drop those rows, or fix them by hand if there are only a few:
import pandas as pd
log = pd.DataFrame({
"event": ["start", "pause", "resume", "stop"],
"when": ["2024-07-01", "not recorded", "2024-07-03", "2024-07-04"],
})
log["when"] = pd.to_datetime(log["when"], errors="coerce")
print(log)
print(log.dropna(subset=["when"])) event when
0 start 2024-07-01
1 pause NaT
2 resume 2024-07-03
3 stop 2024-07-04
event when
0 start 2024-07-01
2 resume 2024-07-03
3 stop 2024-07-04
Inconsistent labels
Text categories often differ only in spelling or case. Normalise them with .str.strip() and .str.lower(), then map variants onto one value:
import pandas as pd
paid = pd.Series(["yes", "Yes", " Y", "no", "NO ", "n"])
cleaned = paid.str.strip().str.lower().map({"yes": True, "y": True, "no": False, "n": False})
print(pd.DataFrame({"raw": paid, "clean": cleaned})) raw clean
0 yes True
1 Yes True
2 Y True
3 no False
4 NO False
5 n False
Test yourself
What does pd.to_numeric(s, errors="coerce") do with the value "n/a"?
- Raises a ValueError
- Converts it to 0
- Converts it to NaN
- Leaves it as text
A price column has dtype object. What is the most likely reason?
- The prices are very large
- Some values contain non-numeric characters such as
$or, - pandas always stores prices as objects
- The column has no missing values
Which argument lets pd.to_datetime handle a column where each value may use a different date format?
- format="any"
- format="mixed"
- infer=True
- dayfirst=True