Home »
Python »
Python Programs
Fill nan in multiple columns in place in pandas
Given a pandas dataframe, we have to fill nan in multiple columns in place in it.
By Pranit Sharma Last updated : September 29, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose, we have a DataFrame with multiple columns with different data types, some are strings and some are numeric columns. We will replace nan values in string columns with '.' and nan values in numeric columns with 0.
While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell.
Filling nan in multiple columns in place
For this purpose, we will use DataFrame.fillna() method inside which we will pass a dictionary of items where the key will reflect the column name and the value will reflect that value with which we will replace the nan values.
Let us understand with the help of an example,
Python program to fill nan in multiple columns in place
# Importing pandas package
import pandas as pd
# Importing methods from sklearn
from sklearn.preprocessing import MinMaxScaler
# Creating a dictionary
d = {
'Name':['Pranit','Simran','Varun','Kusum',None],
'Age':[None,23,37,None,63],
'City':['Gwalior',None,'Noida',None,'Bhopal']
}
# Creating DataFrame
df = pd.DataFrame(d)
# Display the DataFrame
print("Original DataFrame:\n",df,"\n")
# Filling nan values
df.fillna({'Name':'.', 'City':'.','Age':0}, inplace=True)
# Display result
print("Result:\n",df,"\n")
Output
The output of the above program is:
Python Pandas Programs »