Python Pandas program to replace the NaN values with mode value in a DataFrame

In this python pandas program, we will replace the NaN values with mode value in a DataFrame using the pandas library.

Steps to solve the program
  1. Import pandas library as pd.
  2. Create a dataframe using pd.DataFrame().
  3. Now replace the NaN values with the mode value in of the same column using df.fillna(method=’pad’).
  4. Print the output.
				
					import pandas as pd
import numpy as np
df = pd.DataFrame({'Sr.no.':[1,2,3,4,5],
                   'Name':['Alex',np.nan,'Peter','Klaus','Stefan'],
                   'Age':[30,np.nan,29,22,22]})
print("Original Dataframe: \n",df)
result = df.fillna(df.mode().iloc[0])
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  22.0
4       5  Stefan  22.0
   Sr.no.    Name   Age
0       1    Alex  30.0
1       2    Alex  22.0
2       3   Peter  29.0
3       4   Klaus  22.0
4       5  Stefan  22.0
				
			

replace NaNs with mean in a DataFrame

replace NaNs with the median value in a DataFrame

Leave a Comment