w3resource

Filling Missing Values with the Mean Using Pandas


4. Filling Missing Values with the Mean

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to fill missing values in a numeric column with the mean and validate the change.
  • Write a Pandas program to compute the column-wise mean and fill missing values in multiple columns simultaneously.
  • Write a Pandas program to fill missing values with the mean only for rows that meet a specific condition.
  • Write a Pandas program to fill missing values with the mean and then plot the distribution before and after imputation.

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.



Follow us on Facebook and Twitter for latest update.