Handling Missing Values (Nulls)
Detect, fill, and drop NaN values — essential for accurate analysis
Missing values (NaN — Not a Number) are in every real-world dataset. Pandas represents missing data as NaN for numeric columns and None or NaN for object columns. Handling them correctly prevents silent errors — a SUM with NaN returns NaN, an average with NaN skews results, and a merge with NaN drops rows unexpectedly.
The three strategies for missing values: drop (remove rows/columns with nulls), fill (replace with a value), or flag (add a boolean column marking where nulls were).
Example
Key Points
- ✓df.isnull().sum() is the first thing to check after loading data
- ✓dropna() removes rows — be careful about how many rows you lose
- ✓fillna(value) fills with a constant; fillna(df["col"].median()) fills with statistics
- ✓Forward fill (ffill) is useful for time series — carry the last known value forward
- ✓inplace=True modifies the DataFrame directly — without it, you get a new DataFrame back
Practice Question
A "City" column has 200 null values. You want to fill them with the string "Unknown". Which is correct?
Related Topics
Data Cleaning with PandasRename columns, fix data types, remove duplicates, and standardise messy real-world dataPandas DataFramesThe core Pandas data structure — a 2D table with rows and columnsExploratory Data Analysis (EDA) WorkflowA systematic 6-step EDA process every data analyst should follow on any new dataset