Python Tutorial
Pandas Cleaning Wrong Data
Wrong data is a valid type but an impossible value — a year of 20250, a negative age.
Replace or Drop
Set a cell by index, or drop rows that fail a rule.
import pandas as pd
df = pd.DataFrame({"Duration": [60, 60, 450, 45], "Pulse": [110, 117, 104, 109]})
df.loc[2, "Duration"] = 45
print(df)
for i in df.index:
if df.loc[i, "Duration"] > 120:
df.drop(i, inplace=True)
print(df)📘 Real-World Deep Dive
Knowing <strong>Pandas Cleaning Wrong (pandas)</strong> well is what turns pandas from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Pandas Cleaning Wrong that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import pandas as pd
df = pd.DataFrame({"date": ["2026-01-01", "01/02/2026", "yesterday"]})
df["date"] = pd.to_datetime(df["date"], errors="coerce")
print(df)Expected Output
(see source)Common mistakes
- A
DataFrameindexing pattern likedf[df.col > 5]returns a copy — use.loc[row_mask, col]for assignment to avoidSettingWithCopyWarning. - Pandas infers
objectdtype for CSVs with mixed numeric/text columns; cast withpd.to_numeric/astype("category")for big speed/memory wins. df.iterrows()is O(n) and slow; iterate withdf.itertuples()or vectorise column-wise.- Treating Pandas Cleaning Wrong as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Enable the Arrow backend:
pd.read_csv("…", engine="pyarrow", dtype_backend="pyarrow")for faster, type-stable reads. - Use
categoricaldtype for columns with low-cardinality strings — sort/join/group-by speed up dramatically. - Switching a hot loop from row-wise Python to
df.eval("…")/df.query("…")often gives 5–50×. - When working with pandas, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.