Fixed Top Ad (Local Preview)800x90 • Slot 6608427872
Data Cleaning with Pandas
✕1. Common Data Problems
- Real-world datasets are rarely perfect. They may contain: 👉 Missing values 👉 Duplicate rows 👉 Wrong data types 👉 Spelling mistakes 👉 Extra spaces 👉 Inconsistent categories 👉 Outliers 👉 Incorrect formats 📌 Data cleaning means fixing messy data so it becomes useful for analysis.
1.1 🧹 Why Do We Clean Data?
1.2 Common Data Quality Issues
| Issue | Example | Possible Solution |
|---|---|---|
| Inconsistent column names | Name, name, Customer Name | Standardize using rename() or names while loading |
| Missing values | NULL, blanks, NaN | Use dropna() or fillna() |
| Duplicates | Same row appears multiple times | Use drop_duplicates() |
| Inconsistent categories | F, Fe, Female | Standardize using replace() or map() |
| Incorrect data types | Age stored as text | Use astype() or pd.to_datetime() |
| Outliers | Age = 300 | Remove using filters or limit using clip() |
| Incorrect data format | Years stored as separate columns | Use melt() or pivot_table() |
| Spelling mistakes | New Yrok instead of New York | Use fuzzy matching |
| Inconsistent units | kg and pounds mixed | Convert to one standard unit |
| Case sensitivity | male, Male, MALE | Convert to lower or upper case |
| Business rule violation | TxnDate < CreatedDate | Fix or remove invalid rows |
| Leading/trailing spaces | " Ram " | Use .str.strip() |
| Non-numeric characters in numeric column | Age = "25 years" | Clean using regex |
2. Tidy Data
- Tidy data is a standard way of organizing data for analysis. In tidy data: ✅ Each variable forms a column ✅ Each observation forms a row ✅ Each type of observational unit forms a table 📌 Simple idea: Tidy data is organized data that is easier to analyze.
- Here, sales for different years are stored in different columns.
2.1 📊 What is Tidy Data?
2.2 Example of Untidy Data
| product | year_2020_sales | year_2021_sales |
|---|---|---|
| Product A | 100 | 150 |
| Product B | 200 | 250 |
- Here:
-
productis a column -yearis a column -salesis a column - Each row is one observation 📌 Tidy data is usually better for analysis. Wide data is often better for reporting.
2.3 Example of Tidy Data
| product | year | sales |
|---|---|---|
| Product A | 2020 | 100 |
| Product A | 2021 | 150 |
| Product B | 2020 | 200 |
| Product B | 2021 | 250 |

3. melt()
melt()converts data from wide format to long format. This is useful when we want to convert untidy data into tidy data. 📌 Simple idea:melt()turns many value columns into two columns: variable and value.- When we use
melt(): - Number of rows usually increases - Number of columns usually decreases pd.melt(df,id_vars=["id_1", "id_2"],value_vars=["val_1", "val_2"])Here:id_varsare columns we want to keep fixedvalue_varsare columns we want to unpivotimport pandas as pddf = pd.DataFrame({"product": ["A", "B"],"year_2020_sales": [100, 200],"year_2021_sales": [150, 250]})melted_df = pd.melt(df,id_vars=["product"])print(melted_df)Output: product variable value 0 A year_2020_sales 100 1 B year_2020_sales 200 2 A year_2021_sales 150 3 B year_2021_sales 250melted_df = pd.melt(df,id_vars=["product"],var_name="year",value_name="sales")print(melted_df)📌var_namegives a name to the old column-name column. 📌value_namegives a name to the value column.
3.1 🔄 What is melt()?
3.2 What Happens During Melt?
3.3 Syntax
3.4 Example: Melt Sales Data
3.5 Better Column Names After Melt
4. pivot_table()
pivot_table()converts data from long format to wide format. It is like the reverse ofmelt(). 📌 Simple idea:pivot_table()spreads values into separate columns.- When we use
pivot_table(): - Number of rows usually decreases - Number of columns usually increases df.pivot_table(index=["id_1", "id_2"],columns="variable",values="value")- If there are duplicate values for the same index and column combination,
pivot_table()aggregates them. By default, it uses average. We can change this usingaggfunc. Example:df.pivot_table(index="product",columns="year",values="sales",aggfunc="sum") import pandas as pddf = pd.DataFrame({"product": ["A", "A", "B", "B"],"year": [2020, 2021, 2020, 2021],"sales": [100, 150, 200, 250]})p_df = df.pivot_table(index="product",columns="year",values="sales")print(p_df)Output: year 2020 2021 product A 100 150 B 200 250
4.1 📌 What is pivot_table()?
4.2 What Happens During Pivot?
4.3 Syntax
4.4 Handling Duplicate Values
4.5 Example: Pivot Sales Data

5. cut() and qcut()
cut()is used to divide numeric values into bins based on fixed ranges. Example: 0 to 18 = Child 18 to 35 = Adult 35 to 60 = Seniorbins = [0, 18, 35, 60]labels = ["Child", "Adult", "Senior"]df["age_group"] = pd.cut(df["age"],bins=bins,labels=labels)print(df)📌cut()uses the bin limits we provide.qcut()divides data into equal-sized groups based on quantiles. Example: If we use:q=3Pandas tries to divide the data into 3 groups with similar number of rows.labels = ["Young", "Middle-aged", "Old"]df["age_quantile"] = pd.qcut(df["age"],q=3,labels=labels)print(df)📌 Simple idea:cut()uses fixed ranges.qcut()uses quantiles.
5.1 ✂️ What is cut()?
5.2 Example: cut()
5.3 What is qcut()?
5.4 Example: qcut()

6. Handling Missing Values
- Missing values are empty or unknown values in data. In Pandas, missing values are often shown as:
NaNCommon strategies: ✅ Drop missing rows or columns ✅ Fill missing values with a fixed value ✅ Fill missing values using mean, median, or mode ✅ Use forward fill or backward fill ✅ Estimate missing values using interpolation or prediction df["course_clean"] = df["course"].fillna("Unknown")This replaces missing course values with "Unknown".df["age_clean"] = df["age"].fillna(df["age"].mean())This replaces missing age values with the average age.df["experience_clean"] = df["experience"].ffill()This fills missing values using the previous available value. Backward fill:df["experience_clean"] = df["experience"].bfill()filter_mask = (df["education"].isnull()) & (df["age"] < 25)df.loc[filter_mask, "education"] = "SLC"This fills missing education values with "SLC" only when age is below 25.df.dropna(subset=["name"], inplace=True)This removes rows where name is missing. 📌 Usefillna()when you want to fill missing values. 📌 Usedropna()when you want to remove missing rows.
6.1 ❓ What are Missing Values?
6.2 Fill Missing Text Values
6.3 Fill Missing Numeric Values
6.4 Forward Fill
6.5 Fill Missing Values with Conditions
6.6 Drop Rows with Missing Values

7. Handling Duplicates
- Duplicate rows are repeated records in a dataset. They can happen due to: - Repeated data entry - Multiple file imports - System errors - Merged data from different sources
duplicate_mask = df.duplicated(subset=["name", "age"],keep=False)duplicates = df[duplicate_mask]print(duplicates)Here:subset=["name", "age"]checks duplicates using these columnskeep=Falsemarks all duplicate rows as duplicatesunique_df = df.drop_duplicates(subset=["name", "age"],keep="first")print(unique_df.duplicated(subset=["name", "age"]).sum())📌duplicated()finds duplicates.drop_duplicates()removes duplicates.
7.1 👥 What are Duplicates?
7.2 Find Duplicate Rows
7.3 Remove Duplicate Rows
8. Data Value Issues
- Sometimes the same category is written in different ways.
Example:
m, male, Male, MWe can standardize values usingreplace().df["gender"] = df["gender"].replace({"m": "Male","f": "Female"}) mapping_dict = {"m": "Male","f": "Female"}df["gender"] = df["gender"].str.lower().map(mapping_dict)📌 Note:replace()keeps values that are not in the dictionary.map()may convert unmatched values to missing values.- Outliers are values that are unusually high or unusually low.
Example:
Age = 300 df["age"] = df["age"].clip(lower=0, upper=120)This limits age values to the range 0 to 120.outlier_mask = (df["age"] < 0) | (df["age"] > 120)df = df[~outlier_mask]This removes rows where age is below 0 or above 120.
8.1 🧩 Inconsistent Categories
8.2 Using map()
8.3 Outliers
8.4 Limit Outliers with clip()
8.5 Remove Outliers with Filter

df["name"] = df["name"].str.strip()This removes extra spaces from the beginning and end of names.df["name"] = df["name"].str.upper()or:df["name"] = df["name"].str.lower()This makes text values consistent.- Sometimes numeric columns contain characters.
Example:
"25 years"We can remove non-numeric characters using regex.df["age"] = df["age"].str.replace(r"\D","",regex=True).astype(int)📌 Simple idea: Text cleaning often uses.str,replace(), and regex.
8.6 Leading and Trailing Spaces
8.7 Inconsistent Case
8.8 Non-Numeric Characters in Numeric Columns
9. Fuzzy Matching to Clean Spelling Issues
- Fuzzy matching is used to find strings that are approximately similar, not exactly the same. Example: New yolk ≈ New York It is useful for fixing spelling mistakes or inconsistent location names.
- The
fuzzywuzzylibrary can be used for fuzzy matching in Python. Install it using:pip install fuzzywuzzy python-Levenshtein from fuzzywuzzy import processchoices = ["New York", "Kathmandu", "Delhi"]query = "New yolk"best_match = process.extractOne(query, choices)print(best_match)Possible output: ('New York', 88) 📌 The result contains: - Best matching text - Similarity score 📌 Simple idea: Fuzzy matching helps clean values that are close but not exactly the same.
9.1 🔤 What is Fuzzy Matching?
9.2 Library for Fuzzy Matching
9.3 Example: Fuzzy Matching

