










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!











Learning Objectives Understand why data cleaning is necessary Inspect a dataset using Pandas Handle missing values and duplicates Fix data types and inconsistent text Handle invalid values and outliers Validate and save clean data
Step 1 โ Load the Dataset Syntax: import pandas as pd df = pd.read_csv("data.csv") Explanation: pandas is imported using the short name pd. read_csv() reads the CSV file. df stores the dataset as a DataFrame.
Step 2 โ Understand the Dataset df.head() โ first 5 rows df.tail() โ last 5 rows df.shape โ number of rows and columns df.columns โ column names df.info() โ structure, data types and non-null values df.describe() โ numerical summary statistics
Step 4 โ Remove Duplicates df.duplicated().sum() Counts duplicate rows. df.drop_duplicates(inplace=True) Removes duplicate records from the DataFrame. Why? Duplicate records can produce incorrect analysis and statistics.
Step 5 โ Fix Data Types df.dtypes Checks the data type of every column. df["Age"] = df["Age"].astype(int) Converts Age to integer. df["Date"] = pd.to_datetime(df["Date"]) Converts a Date column into Pandas datetime format.
Step 7 โ Find Invalid Values df[df["Age"] < 0] Finds records where Age is negative. df.loc[df["Age"] < 0, "Age"] = None Replaces invalid negative ages with a missing value. Example: Age = -5 is not a valid age.
Step 8 โ Handle Outliers Q1 = df["Salary"].quantile(0.25) Q3 = df["Salary"].quantile(0.75) IQR = Q3 - Q An outlier can be identified using the IQR rule. Keep values between Q1 โ 1.5รIQR and Q3 + 1.5รIQR. df = df[(df["Salary"] >= Q1 - 1.5 * IQR) & (df["Salary"] <= Q3 + 1.5 * IQR)]
Step 10 โ Rename Columns df.rename(columns={ "Student Name": "student_name", "Student Age": "age" }, inplace=True) Clear, consistent column names make code easier to read and use.
Step 11 โ Validate the Cleaned Data df.info() df.isnull().sum() df.duplicated().sum() df.describe() Run these checks again after cleaning. Validation confirms that the cleaning operations produced the expected result.
Worked Example โ Dirty Dataset Sample problems: Ravi | 20 | Chennai | 85 Ravi | 20 | Chennai | 85 โ duplicate Priya | NaN | chennai | 90 โ missing age + inconsistent city Arun | -5 | Chennai | 78 โ invalid age Cleaning actions: remove duplicate, handle missing Age, standardize City, correct invalid Age.
Complete Data-Cleaning Program import pandas as pd df = pd.read_csv("data.csv") df = df.drop_duplicates() df["Age"] = df["Age"].fillna(df["Age"].mean()) df["City"] = df["City"].str.strip().str.lower() df.loc[df["Age"] < 0, "Age"] = None df.info() df.to_csv("cleaned_data.csv", index=False)