Python Practice › Pandas Programs › Program 53
Replace NaN with a value
Write a pandas program to replace NaN in a column with a fixed value.
Output
name age 0 Alex 30.0 1 John 0.0 2 Peter 29.0 3 Klaus 0.0
Approach
fillna(value).
Solution
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
Learn the concept
New to this topic? Read the lesson, then come back.