Data Cleaning with pandas
Fix messy real-world data — duplicates, wrong types, inconsistent values, and bad formats
Data cleaning takes 60–80% of a data analyst's time. Real datasets have duplicate rows, wrong data types, inconsistent category names ("Delhi" vs "delhi" vs "Delhi "), and columns that should be split or combined.
Pandas has a comprehensive set of tools for all of these. This tutorial covers the cleaning operations you will use in every project.
Example
Key Points
- ✓df.duplicated().sum() counts duplicate rows; drop_duplicates() removes them
- ✓df.columns.str.lower().str.replace(" ","_") standardises all column names at once
- ✓pd.to_datetime() is essential for date columns — enables date filtering and time analysis
- ✓inplace=True modifies the DataFrame directly — without it, you must reassign: df = df.drop_duplicates()
- ✓str.strip().str.title() is the standard fix for city/name columns with mixed case and spaces
Practice Question
A column "City" has values "delhi", "Delhi", "DELHI", "delhi " (with trailing space). Which operation standardises all of these to "Delhi"?