In this python pandas program, we will replace NaNs with the value from the previous row in a DataFrame using the pandas library.
Steps to solve the program
- Import pandas library as pd.
- Create a dataframe using pd.DataFrame().
- Now replace the NaN values with the value in the previous row of the same column using df.fillna(method=’pad’).
- Print the output.
import pandas as pd
import numpy as np
df = pd.DataFrame({'Sr.no.':[1,2,3,4],
'Name':['Alex',np.nan,'Peter','Klaus'],
'Age':[30,np.nan,29,np.nan]})
print("Original Dataframe: \n",df)
print("Fill the rows where all elements are missing with previous values:")
result = df.fillna(method='pad')
print(result)
Output :
Original Dataframe:
Sr.no. Name Age
0 1 Alex 30.0
1 2 NaN NaN
2 3 Peter 29.0
3 4 Klaus NaN
Fill the rows where all elements are missing with previous values:
Sr.no. Name Age
0 1 Alex 30.0
1 2 Alex 30.0
2 3 Peter 29.0
3 4 Klaus 29.0