Python Practice › Pandas Programs › Program 92
Fill with the most frequent value
Write a pandas program to replace NaN with each column’s most frequent value.
Output
city age 0 Pune 30.0 1 Pune 30.0 2 Pune 29.0 3 Delhi 30.0
Approach
mode().iloc[0]per column.
Solution
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.