Python Practice › Pandas Programs › Program 92

Fill with the most frequent value

EasyPandas Programs · 92 of 95

Write a pandas program to replace NaN with each column’s most frequent value.

Advertisement
Output
    city   age
0   Pune  30.0
1   Pune  30.0
2   Pune  29.0
3  Delhi  30.0

Approach

  1. mode().iloc[0] per column.

Solution

Python
import numpy as npimport pandas as pddf = pd.DataFrame({"city": ["Pune", np.nan, "Pune", "Delhi"], "age": [30, np.nan, 29, 30]})print(df.fillna(df.mode().iloc[0]))
Output
    city   age
0   Pune  30.0
1   Pune  30.0
2   Pune  29.0
3  Delhi  30.0

Line by line

Line 4

df.mode().iloc[0] is the most frequent value of every column.

Learn the concept

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

More pandas programs

← All 95 Pandas Programs

Leave a Comment