Filling Missing Values with the Mean Using Pandas
Pandas: Machine Learning Integration Exercise-4 with Solution
Write a Pandas program that fills missing values with the Mean.
This exercise demonstrates how to fill missing values in numerical columns with the mean of the column.
Sample Solution :
Code :
import pandas as pd
# Load the dataset
df = pd.read_csv('data.csv')
# Fill missing values in the 'Age' column with the mean of the column
df['Age'].fillna(df['Age'].mean(), inplace=True)
# Output the updated dataset
print(df)
Output:
ID Name Age Gender Salary Target 0 1 Sara 25.0 Female 50000.0 0 1 2 Ophrah 30.0 Male 60000.0 1 2 3 Torben 22.0 Male 70000.0 0 3 4 Masaharu 35.0 Male 80000.0 1 4 5 Kaya 28.2 Female 55000.0 0 5 6 Abaddon 29.0 Male NaN 1
Explanation:
- Loaded the dataset using Pandas.
- Used fillna() to replace missing values in the 'Age' column with the mean of the column.
- Displayed the updated dataset.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/pandas/pandas-fill-missing-values-with-the-mean.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics