Python Practice › Pandas Programs › Program 53

Replace NaN with a value

EasyPandas Programs · 53 of 95

Write a pandas program to replace NaN in a column with a fixed value.

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

Approach

  1. fillna(value).

Solution

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

Learn the concept

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

More pandas programs

← All 95 Pandas Programs