Day 8 — Pandas Data Cleaning (Missing data & Duplicates)
เคฏเคน เคชूเคฐा static, Blogger-friendly chapter เคนै — เคนเคฐ section เคฎें theory + explaination + Python (pandas) code snippets + expected output tables เคฆिเค เคเค เคนैं, เคคाเคि เคเคช เคเคธเคो เคธीเคงे เค เคชเคจे เคฌ्เคฒॉเค เคฎें paste เคเคฐ เคे เคชเคข़ा/เคช्เคฐเคถिเค्เคทिเคค เคเคฐ เคธเคें।
เคธैเคฆ्เคงाเคจ्เคคिเค เคชเคฐिเคเคฏ — Pandas Data Cleaning เค्เคฏा เคนै?
เคชाเคเคฅเคจ เคฎें pandas
เคเค เคถเค्เคคिเคถाเคฒी เคฒाเคเคฌ्เคฐेเคฐी เคนै เคिเคธเคा เคช्เคฐเคฏोเค table-like data (DataFrame) เคे เคธाเคฅ เคिเคฏा เคाเคคा เคนै।Data Cleaning เคा เคฎเคคเคฒเคฌ เคนै: raw/real-world datasets เคฎें เคเคจे เคตाเคฒी เคเคฒเคคिเคฏों เคเคฐ inconsistencies เคो เค ीเค เคเคฐเคจा เคคाเคि analysis, visualization เคเคฐ machine learning models เคชเคฐ เคญเคฐोเคธा เคिเคฏा เคा เคธเคे।
- Missing values (NaN, None, blanks): detect เคเคฐเคจे เคे เคฒिเค
isnull()
, เคนเคाเคจे เคे เคฒिเคdropna()
, เคญเคฐเคจे เคे เคฒिเคfillna()
. - Duplicates: duplicate rows เคฏा duplicate identifiers — detect เคเคฐเคจे เคे เคฒिเค
duplicated()
, เคนเคाเคจे เคे เคฒिเคdrop_duplicates()
. - Consistency: data types เคธเคนी เคเคฐเคจा (
astype()
), strings clean เคเคฐเคจा (str.strip()
, lower/upper), เคเคฐ invalid values เคो replace เคเคฐเคจा।
เคเค เคธ्เคชเคท्เค เคเคฆाเคนเคฐเคฃ: เคฏเคฆि sales data เคฎें เคुเค rows เคी price
missing เคนै, เคคो total revenue เคเคฒเคค เคจिเคเคฒेเคा; เคฏा เคฏเคฆि เคเค customer เคी เคฐिเคॉเคฐ्เคก duplicate เคนै เคคो analysis เคฎें overcount เคนोเคा।
เค्เคฏों เคธीเคเคจा เคाเคนिเค? (Importance)
- Real-world data เคเคญी เคญी perfect เคจเคนीं เคนोเคคा — cleaning เคเคฐूเคฐी เคนै।
- Dirty data เคธे เคเคฒเคค insights เคเคฐ เคเคฒเคค business decisions เคนो เคธเคเคคे เคนैं।
- Machine learning models clean data เคชเคฐ เคนी เคธเคนी เคธीเคเคคे เคนैं — missing/duplicate data accuracy เคเคाเคคे เคนैं।
- เคช्เคฐैเค्เคिเคเคฒ data scientist เคฌเคจเคจे เคे เคฒिเค เคฏเคน เคธเคฌเคธे เคชเคนเคฒी skill เคนै।
- Data cleaning เคธे reporting, visualization เคเคฐ storage เคฌेเคนเคคเคฐ เคนोเคคे เคนैं।
เคเคนाँ เคเคฐ เคैเคธे เคเคธ्เคคेเคฎाเคฒ เคเคฐेंเคे?
Data cleaning เคนเคฐ เคเคเคน เคाเคฎ เคเคคा เคนै — e-commerce, banking, healthcare, survey data, education เคเคฆि। เคธाเคฎाเคจ्เคฏ workflow:
- Data load:
pd.read_csv()
,pd.read_excel()
- Inspect: shape,
head()
,info()
,describe()
, missing counts (isnull().sum()
) - Handle missing: drop เคฏा fill (mean/median/0/forward-fill/ custom)
- Handle duplicates: identify using
duplicated()
เคเคฐdrop_duplicates()
- Data type conversions, trimming strings, replace invalid values
- Final check เคเคฐ save
เค เคฌ เคเคชเคे เคนเคฐ เคช्เคฐเคถ्เคจ เคे เคตिเคธ्เคคृเคค เคเคตाเคฌ — เคนเคฐ เคเค เคे 5 เคเคฆाเคนเคฐเคฃ (Step-by-step + code + expected output)
Q1: "Pandas Data Cleaning เค्เคฏा เคนै?" — 5 Examples
เคจीเคे เคนเคฐ example เคोเคे dataframes เคे เคธाเคฅ เคฆिเคाเคฏा เคเคฏा เคนै — code เคชเคข़िเค เคเคฐ เคเคธเคे เคจीเคे expected output table เคฎौเคूเคฆ เคนै เคคाเคि beginner เคญी เคธเคฎเค เคธเคे เคि เค्เคฏा เคนोเคคा เคนै।
Example 1 — Missing values detection (identify เคเคฐเคจा)
import pandas as pd df = pd.DataFrame({ 'Name': ['Amit', 'Ravi', 'Sita', None], 'Age': [25, None, 30, 28] }) missing counts print(df) print(' Missing counts:') print(df.isnull().sum())
Expected output (table):
Name | Age |
---|---|
Amit | 25.0 |
Ravi | |
Sita | 30.0 |
28.0 |
Missing counts: Name: 1, Age: 1 — เคฏเคน เคฌเคคाเคคा เคนै เคिเคจ columns เคฎें NaN เคนै।
Example 2 — Fill missing with mean
# same df as above fill missing age with mean age mean_age = df['Age'].mean() df['Age'] = df['Age'].fillna(mean_age) print(df)
Expected: Age column เคे missing เคो average เคธे replace เคเคฐ เคฆेंเคे; Name เคा missing เค เคญी เคญी เคฐเคนेเคा เค เคเคฐ เคนเคฎ เคเคธे drop/replace เคจเคนीं เคเคฐเคคे।
Example 3 — Drop missing rows
# drop any row with at least one NaN clean = df.dropna() print(clean)
Expected: เคตो เคธाเคฐी rows เคนเคेंเคी เคिเคจเคฎें เคोเค NaN เคนै — เคेเคตเคฒ fully complete rows เคฌเคेंเคी।
Example 4 — Detect duplicates
df2 = pd.DataFrame({'id':[1,1,2,3],'val':[10,10,20,30]}) print(df2) print('duplicated mask:') print(df2.duplicated())
Expected: duplicated() boolean series เคฆेเคा — True เคตเคนां เคเคนां same row เคชเคนเคฒे เค เคुเคा เคนै।
Example 5 — Remove duplicates
df2_unique = df2.drop_duplicates() print(df2_unique)
Expected: duplicate row remove เคนो เคाเคเคी เคเคฐ unique rows เคฌเคेंเคी।
Q2: Pandas Data Cleaning เคा Use เค्เคฏा เคนै? — 5 Examples
Use-cases เคोเคे real-world contexts เคฎें — เคนเคฐ เคเค เคे เคธाเคฅ code + expected result:
Example 1 — Sales dataset: missing price -> fill with mean price
df_sales = pd.DataFrame({'product':['A','B','C','D'],'price':[100, None, 150, None]}) fill missing df_sales['price'] = df_sales['price'].fillna(df_sales['price'].mean()) print(df_sales)
Expected: B เคเคฐ D เคी price average เคธे replace เคนो เคाเคเคी — เคिเคธเคธे total revenue calculate เคเคฐเคจा meaningful เคนोเคा।
Example 2 — Hospital: duplicate patient records เคนเคाเคจा
df_pat = pd.DataFrame({'patient_id':[101,102,101,103],'name':['R','S','R','T'],'age':[30,25,30,40]}) remove duplicates based on patient_id df_pat_unique = df_pat.drop_duplicates(subset=['patient_id']) print(df_pat_unique)
Expected: patient_id 101 duplicate entry remove เคนोเคी — accurate patient count เคฎिเคฒेเคा।
Example 3 — School: missing marks -> fill with 0 (absent)
df_marks = pd.DataFrame({'student':['A','B','C'],'marks':[80, None, 90]}) df_marks['marks'] = df_marks['marks'].fillna(0) print(df_marks)
Expected: B เคा marks 0 set เคนोเคा, เคिเคธเคธे class average calculate เคเคฐเคจा straightforward เคนोเคा।
Example 4 — Banking: missing transaction amounts -> drop those rows
df_tx = pd.DataFrame({'tx_id':[1,2,3,4],'amount':[200,None,500,None]}) df_tx_clean = df_tx.dropna(subset=['amount']) print(df_tx_clean)
Expected: เคेเคตเคฒ valid transactions เคฐเคนेंเคी; null amounts ignore เคนो เคाเคँเคी।
Example 5 — E-commerce: duplicate orders remove by order_id
df_orders = pd.DataFrame({'order_id':[1001,1002,1001,1003],'customer':['X','Y','X','Z'],'value':[500,300,500,400]}) df_orders = df_orders.drop_duplicates(subset=['order_id']) print(df_orders)
Expected: duplicate order 1001 remove — correct order count เคเคฐ total revenue เคฎिเคฒेเคी।
Q3: เคเคธे เค्เคฏों เคธीเคเคจा เคाเคนिเค? (5 Examples — consequences of NOT cleaning)
เคฏเคนाँ เคนเคฎ เคฆिเคाเคँเคे เคी เค เคเคฐ data clean เคจ เคिเคฏा เคाเค เคคो เค्เคฏा เคเคฒเคค เคนोเคा (simple, clear examples)।
Example 1 — Missing values change statistics (mean wrong)
df = pd.DataFrame({'val':[10, None, 30]}) print('mean (skips NaN):', df['val'].mean()) เค เคเคฐ เคนเคฎ NaN เคो 0 เคฎाเคจเคเคฐ add เคเคฐें เคคो result เคฌเคฆเคฒेเคा print('sum skipping NaN:', df['val'].sum())
Explanation: Statistics calculation default behavior NaN เคे เคธाเคฅ เค
เคฒเค เคนोเคคी เคนै — เค
เคเคฐ logically NaN เคो 0 เคฎाเคจเคจा เคนै เคคो fillna(0)
เคเคฐें, เคตเคฐเคจा leave เคเคฐें।
Example 2 — Duplicates cause overcount
dfdup = pd.DataFrame({'item':['A','A','B'],'qty':[1,1,2]}) print('rows before:', len(dfdup)) print(dfdup) dfdup2 = dfdup.drop_duplicates() print('rows after:', len(dfdup2))
Explanation: Duplicate rows เคนोเคจे เคธे aggregates (เคैเคธे total items) เคเคฒเคค เคนोंเคे।
Example 3 — Arithmetic with NaN propagates NaN
dfA = pd.DataFrame({'a':[1, None, 3]}) print((dfA['a'] + 2).tolist())
Explanation: NaN arithmetic เคฎें เคฐเคนे เคคो final results เคฎें NaN เค เคธเคเคคे เคนैं — preprocessing เคฎें fill เคฏा drop เคเคฐเคจा เคाเคนिเค।
Example 4 — Healthcare: duplicate patient distorts counts
df_pat = pd.DataFrame({'pid':[1,2,1,3]}) print('unique patients:', df_pat['pid'].nunique()) print('rows before:', len(df_pat)) print(df_pat.drop_duplicates())
Explanation: Duplicate patient rows เคธे patient count เคเคฐ per-patient stats เคเคฒเคค เคนोंเคे।
Example 5 — Survey completeness percent
df_s = pd.DataFrame({'q1':[1,None,0], 'q2':[None,1,1]}) print('overall completeness (%) =', df_s.notnull().mean().mean()*100)
Explanation: เค เคเคฐ completeness เคเคฎ เคนै เคคो survey results reliable เคจเคนीं เคนोंเคे — cleaning เคเคฐ imputation เคैเคธे เคเคฐेंเคे เคฏเคน design decision เคนै।
Q4: เคเคธे เคเคนाँ เคเคฐ เคैเคธे use เคเคฐेंเคे? (5 Practical examples)
Small, real preprocessing patterns เคो เคเคช data pipelines เคฎें เคฌाเคฐ-เคฌाเคฐ เคฆेเคेंเคे:
Example 1 — E-commerce: dedupe customer table for recommender
df = pd.DataFrame({'cust_id':[1,2,1,3],'visits':[5,2,5,1]}) dedupe keeping first df_u = df.drop_duplicates(subset=['cust_id']) print(df_u)
Use: Recommendation models per-user stats เคฌเคจाเคคे เคธเคฎเคฏ duplicate rows problem เคนोเคा — dedupe เคเคฐเคे fix เคเคฐें।
Example 2 — Banking: remove null transaction amounts before fraud model
df = pd.DataFrame({'tx':[1,2,3],'amt':[100,None,200]}) df_clean = df.dropna(subset=['amt']) print(df_clean)
Use: ML model เคो numeric amount เคाเคนिเค — null rows เคฎॉเคกเคฒ เคฎें confuse เคเคฐेंเคी।
Example 3 — Healthcare: impute missing age with median
df = pd.DataFrame({'pid':[1,2,3],'age':[25,None,45]}) df['age'] = df['age'].fillna(df['age'].median()) print(df)
Use: Median imputation outliers เคธे เคเคฎ เคช्เคฐเคญाเคตिเคค เคนोเคคा เคนै।
Example 4 — Education: forward-fill attendance for continuous days
df = pd.DataFrame({'day':[1,2,3,4],'present':[1,None,None,1]}) df['present'] = df['present'].fillna(method='ffill') print(df)
Use: Continuous time-series เคฎें forward/backward fill practical เคนोเคคा เคนै।
Example 5 — Govt survey: drop respondents with too many blanks
df = pd.DataFrame({'r':[1,2,3],'a':[1,None,None],'b':[None,2,None],'c':[3,4,None]}) keep rows with fewer than 2 blanks df_clean = df[df.isnull().sum(axis=1) < 2] print(df_clean)
Use: Low-quality respondents remove เคเคฐเคे overall dataset quality improve เคเคฐें।
Q5: เคเคธे เค्เคฏों use เคเคฐเคจा เคाเคนिเค? (5 Examples — benefits)
Benefits เคो เคोเคे เคเคฆाเคนเคฐเคฃों เคฎें เคฆिเคा เคฐเคนे เคนैं:
Example 1 — Stable statistics after cleaning
df = pd.DataFrame({'v':[10,None,30,40]}) df2 = df.copy() df2['v'] = df2['v'].fillna(df2['v'].mean()) print('mean before:', df['v'].mean()) print('mean after:', df2['v'].mean()) print(df2)
Benefit: Imputation เคธे statistics consistent เคนोंเคे — reporting reliable เคฌเคจेเคा।
Example 2 — Remove duplicates saves rows and storage
df = pd.DataFrame({'id':[1,1,2,3]}) print('before rows:', len(df)) df_u = df.drop_duplicates() print('after rows:', len(df_u))
Benefit: Deduplication เคธे storage เคिเคฐेเคा เคเคฐ analysis เคธเคนी เคนोเคा।
Example 3 — Arithmetic works after fill
df = pd.DataFrame({'a':[1,None,3]}) res = (df['a'].fillna(0) + 2).tolist() print(res)
Benefit: Calculations predictable เคนोंเคी; NaN เคธे unexpected errors เคจเคนीं เคเคँเคे।
Example 4 — Visualization ready (no gaps)
df = pd.DataFrame({'x':[1,2,3],'y':[10,None,30]}) df['y'] = df['y'].fillna(method='ffill') print(df)
Benefit: Visual plots เคฎें gaps เคจเคนीं เคฆिเคेंเคे — trends เคธाเคซ เคฆिเคेंเคे।
Example 5 — Business totals correct
df = pd.DataFrame({'sale':[100,None,200]}) print('sum default (NaN ignored):', df['sale'].sum()) df['sale'] = df['sale'].fillna(0) print('sum after fillna(0):', df['sale'].sum())
Benefit: Total sales calc เคเคฐเคจे เคे เคฒिเค NaN เคो 0 เคฎाเคจเคจा เคเคฐूเคฐी เคนो เคธเคเคคा เคนै — cleaning เคธे business metrics เคธเคนी เคฎिเคฒेंเคे।