Python Practice › Pandas Programs › Program 90
Fill from the next row
Write a pandas program to replace NaN with the value from the next row.
Output
name age 0 Alex 30.0 1 Peter 29.0 2 Peter 29.0 3 Klaus 22.0
Approach
bfill().
Solution
import numpy as npimport pandas as pddf = pd.DataFrame({"name": ["Alex", np.nan, "Peter", "Klaus"], "age": [30, np.nan, 29, 22]})print(df.bfill())Output
name age 0 Alex 30.0 1 Peter 29.0 2 Peter 29.0 3 Klaus 22.0
Learn the concept
New to this topic? Read the lesson, then come back.