Handle Missing Values in pandas
Missing values commonly appear when data is incomplete, unavailable, or could not be parsed.
What is Handle Missing Values in pandas?
Missing values commonly appear when data is incomplete, unavailable, or could not be parsed.
Find and fill missing DataFrame values with pandas.
When should you use it?
- Read, clean, and transform tabular data.
- Analyze data from CSV, Excel, APIs, or databases.
- Prepare reports, statistics, and chart data.
Example code
main.py
import pandas as pd
import numpy as np
students = pd.DataFrame({"name": ["Ada", "Lin", "Sam"], "score": [95, np.nan, 85]})
students["score"] = students["score"].fillna(students["score"].median())
print(students)
Expected output
name score
0 Ada 95.0
1 Lin 90.0
2 Sam 85.0
How it works
The median is calculated from available scores and used to replace NaN. Assigning back to the column makes the change explicit.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Add rows, columns, and missing values.
- Combine filtering, sorting, and groupby into a small report.
- Load a real file, inspect dtypes, and handle invalid data.