Python Practice › Pandas Programs › Program 91

Fill with the mean

EasyPandas Programs · 91 of 95

Write a pandas program to replace NaN with the column mean.

Advertisement
Output
    name   age
0   Alex  30.0
1   John  27.0
2  Peter  29.0
3  Klaus  22.0

Approach

  1. fillna(df[col].mean()).

Solution

Python
import numpy as npimport pandas as pddf = pd.DataFrame({"name": ["Alex", "John", "Peter", "Klaus"], "age": [30, np.nan, 29, 22]})df["age"] = df["age"].fillna(df["age"].mean())print(df)
Output
    name   age
0   Alex  30.0
1   John  27.0
2  Peter  29.0
3  Klaus  22.0

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs

Leave a Comment