Cleaning Wrong Data
Sometimes a value is in the right format but is simply wrong: a parcel that weighs -2 kg, an exam score of 1040 out of 100, a typo that turned 61 into 16. pandas can't know what is wrong on its own; you supply the rules about what is plausible, and pandas helps you find and fix the values that break them.
Finding suspicious values
Start with describe(): the min and max rows reveal impossible extremes immediately.
import pandas as pd
parcels = pd.DataFrame({
"parcel": ["P01", "P02", "P03", "P04", "P05", "P06"],
"weight_kg": [2.4, 0.8, -1.5, 3.1, 250.0, 1.2],
"days": [2, 3, 1, 40, 2, 4],
})
print(parcels.describe()) weight_kg days
count 6.000000 6.000000
mean 42.666667 8.666667
std 101.584480 15.383974
min -1.500000 1.000000
25% 0.900000 2.000000
50% 1.800000 2.500000
75% 2.925000 3.750000
max 250.000000 40.000000
A negative weight is impossible, and 250 kg is far beyond what this courier accepts (say the limit is 30 kg). A delivery time of 40 days also looks wrong when the rest take a few days.
Replacing a single value
If you know the correct value, set it with loc[row, column]:
import pandas as pd
parcels = pd.DataFrame({
"parcel": ["P01", "P02", "P03", "P04", "P05", "P06"],
"weight_kg": [2.4, 0.8, -1.5, 3.1, 250.0, 1.2],
"days": [2, 3, 1, 40, 2, 4],
})
# The courier confirmed P04 was delivered in 4 days, not 40
parcels.loc[parcels["parcel"] == "P04", "days"] = 4
print(parcels) parcel weight_kg days
0 P01 2.4 2
1 P02 0.8 3
2 P03 -1.5 1
3 P04 3.1 4
4 P05 250.0 2
5 P06 1.2 4
Replacing values by rule
For big tables you can't check each value. Instead, write a rule. Here any weight above the 30 kg limit is capped at 30, and negative weights become missing (we don't know the true value):
import numpy as np
import pandas as pd
parcels = pd.DataFrame({
"parcel": ["P01", "P02", "P03", "P04", "P05", "P06"],
"weight_kg": [2.4, 0.8, -1.5, 3.1, 250.0, 1.2],
})
parcels.loc[parcels["weight_kg"] > 30, "weight_kg"] = 30
parcels.loc[parcels["weight_kg"] < 0, "weight_kg"] = np.nan
print(parcels) parcel weight_kg
0 P01 2.4
1 P02 0.8
2 P03 NaN
3 P04 3.1
4 P05 30.0
5 P06 1.2
clip() does the capping in one step, limiting values to a range:
import pandas as pd
scores = pd.Series([88, 104, 67, -5, 92], name="score")
print(scores.clip(lower=0, upper=100).to_list())[88, 100, 67, 0, 92]
Removing rows
When a row is beyond repair, drop it. The cleanest way is to keep the rows that pass your rules with a boolean filter:
import pandas as pd
parcels = pd.DataFrame({
"parcel": ["P01", "P02", "P03", "P04", "P05", "P06"],
"weight_kg": [2.4, 0.8, -1.5, 3.1, 250.0, 1.2],
"days": [2, 3, 1, 4, 2, 4],
})
valid = parcels["weight_kg"].between(0, 30)
print(parcels[valid])
print("Removed:", parcels.loc[~valid, "parcel"].to_list()) parcel weight_kg days
0 P01 2.4 2
1 P02 0.8 3
3 P04 3.1 4
5 P06 1.2 4
Removed: ['P03', 'P05']
between(0, 30) is shorthand for (s >= 0) & (s <= 30), and ~ inverts a mask, which is handy for listing what you removed. The alternative is df.drop(index_labels), which removes rows by their index label.
Outliers with the IQR rule
When there's no hard limit, a common statistical rule marks values far from the middle half of the data as outliers. With Q1 and Q3 the 25th and 75th percentiles and IQR = Q3 − Q1, anything below Q1 − 1.5·IQR or above Q3 + 1.5·IQR is suspicious:
import pandas as pd
minutes = pd.Series([31, 28, 35, 30, 33, 29, 120, 32, 27, 34])
q1, q3 = minutes.quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"Q1={q1} Q3={q3} IQR={iqr} range=({low}, {high})")
print("Outliers:", minutes[(minutes < low) | (minutes > high)].to_list())Q1=29.25 Q3=33.75 IQR=4.5 range=(22.5, 40.5)
Outliers: [120]
Tip: An outlier is not automatically wrong. A 120-minute commute might be a real day with a train strike. Investigate before you delete.
Test yourself
Which method limits all values of a Series to the range 0–100?
- s.limit(0, 100)
- s.clip(0, 100)
- s.between(0, 100)
- s.range(0, 100)
What does df.loc[df["age"] > 120, "age"] = None do?
- Drops rows with age over 120
- Sets the age to missing in rows where it is over 120
- Sets every age to None
- Raises an error
With Q1 = 10 and Q3 = 20, what is the upper fence of the 1.5·IQR rule?
- 30
- 35
- 25
- 40