9. Data Cleaning A–Z in pandas
9.4 Outliers
# fictional: delivery mins > 120 treated as bad sensor / typo
df.loc[df["mins"] > 120, "mins"] = np.nan
df["mins"] = df["mins"].fillna(df["mins"].median())
Cleaning checklist
- Normalise column names.
- Strip / title-case categories (city, status).
to_numericfor amounts; coerce junk to NaN.- Decide fill vs drop for missing cities.
drop_duplicateson business key (order_id).- Cap or null out impossible mins / amounts.
df.to_csv("data/orders_clean.csv", index=False).- Re-run
info()and compare row counts before/after.
What you should see. One row for BLK-2; Amount 1299 as number; Mins 999 becomes median; City null → Unknown or dropped per your rule — document the rule.
Ravindra Bagale's Tip
Before you change an outlier, count how many rows match your rule, for example (df["mins"] > 120).sum(), and write the rule down. Do not run dropna() on the whole DataFrame, because one empty city can throw away a row whose amount is still useful. Decide column by column and use dropna(subset=["amount"]) only where a missing value really makes the row useless.
Ravindra Bagale's Tip – मराठी
Outlier बदलण्याआधी तुमच्या rule ला किती rows जुळतात ते मोजा, उदाहरणार्थ (df["mins"] > 120).sum(), आणि तो rule लिहून ठेवा. संपूर्ण DataFrame वर dropna() चालवू नका, कारण एका रिकाम्या city मुळे अशी row जाऊ शकते जिची amount अजूनही उपयोगी आहे. Column नुसार निर्णय घ्या, आणि missing value मुळे row खरंच निरुपयोगी होत असेल तिथेच dropna(subset=["amount"]) वापरा.
Ravindra Bagale's Tip – हिंदी
Outlier बदलने से पहले गिनो कि आपके rule से कितनी rows मेल खाती हैं, जैसे (df["mins"] > 120).sum(), और वह rule लिखकर रखो। पूरे DataFrame पर dropna() मत चलाओ, क्योंकि एक खाली city की वजह से ऐसी row चली जा सकती है जिसकी amount अब भी काम की है। Column के हिसाब से फ़ैसला करो, और जहाँ missing value से row सच में बेकार हो जाती है वहीं dropna(subset=["amount"]) लगाओ।
Practice task
Clean the sample so only real Maharashtra course cities remain (drop Unknown if you filled it). Export orders_clean.csv and print df["city"].value_counts().
Thodkyaat sangaycha tar (quick recap)
- Rename → standardise text → numeric coerce → missing strategy → duplicates → outliers → export
- Never silent-drop without a count log
Samajla ka? Aata pudhe jaauya dates, times (IST) and text.