Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Last Updated :
21 Aug, 2024
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and remove Null values from a data frame, fillna() manages and let the user replace NaN values with some value of their own.Â
Pandas DataFrame.fillna() Syntax
Syntax:Â DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)
Parameters:Â
- value : Static, dictionary, array, series or dataframe to fill instead of NaN.
- method : Method is used if user doesn’t pass any value. Pandas have different methods like bfill, backfill, or ffill which fills the place with value in the Forward index or Previous/Back respectively.
- axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and ‘index’ or ‘columns’ for String
- inplace: It is a boolean which makes the changes in data frame itself if True.
- limit : This is an integer value which specifies maximum number of consecutive forward/backward NaN value fills.
- downcast : It takes a dict which specifies what dtype to downcast to which one. Like Float64 to int64.
- **kwargs : Any other Keyword arguments
Python Pandas DataFrame.fillna() to Replace Null values in Dataframe
Below are the ways by which we can replace null values in Dataframe in Python:
- Replace NaN Values with String | Pandas
- Before Replacing
- Using method parameter
- Using Limit
Pandas: How to Replace NaN Values with String
Example 1: Replacing NaN values with a Static value Before Replacing
In this example, we are using pandas library to import the “nba.csv” file and create a DataFrame named “nba” containing the data from the CSV file, which is then displayed using the nba variable.
Python
# importing pandas module
import pandas as pd
# making data frame from csv file
nba = pd.read_csv("nba.csv")
nba
Output
Example 2: Replacing NaN values with a Static value After replacing
In the following example, all the null values in College column has been replaced with “No college” string. Firstly, the data frame is imported from CSV and then College column is selected and fillna() method is used on it.Â
Python
# importing pandas module
import pandas as pd
# making data frame from csv file
nba = pd.read_csv("nba.csv")
# replacing na values in college with No college
nba["College"].fillna("No College", inplace = True)
nba
Output: 
Replacing Null Values Using method Parameter
In the following example, method is set as ffill and hence the value in the same column replaces the null value. In this case Georgia State replaced null value in college column of row 4 and 5. Similarly, bfill, backfill and pad methods can also be used.Â
Python
# importing pandas module
import pandas as pd
# making data frame from csv file
nba = pd.read_csv("nba.csv")
# replacing na values in college with No college
nba["College"].fillna( method ='ffill', inplace = True)
nba
Output
Replacing Null Values Using Limit
In this example, a limit of 1 is set in the fillna() method to check if the function stops replacing after one successful replacement of NaN value or not.Â
Python
# importing pandas module
import pandas as pd
# making data frame from csv file
nba = pd.read_csv("nba.csv")
# replacing na values in college with No college
nba["College"].fillna( method ='ffill', limit = 1, inplace = True)
nba
Output:
As shown in the output, The college column of 4th row was replaced but 5th one wasn’t since the limit was set 1. 
Python | Pandas DataFrame.fillna() to replace Null values in dataframe – FAQs
How to Replace Null Value in DataFrame
In pandas, null values can be represented as NaN (Not a Number) or None. You can use the fillna() method to replace these null values with a specified value.
Example:
import pandas as pd
# Creating a DataFrame with null values
df = pd.DataFrame({
'A': [1, 2, None, 4],
'B': ['a', None, 'c', 'd']
})
# Replace null values with a specified value
df.fillna('No Value', inplace=True)
print(df)
How Do You Replace Blank Values in a DataFrame in Python?
Blank values can be replaced using the replace() method in pandas. If by “blank” you mean empty strings, you can specify that in the method.
Example:
import pandas as pd
df = pd.DataFrame({
'A': [1, '', 3, 4],
'B': ['x', 'y', '', 'z']
})
# Replace empty strings with a specified value
df.replace('', 'Empty', inplace=True)
print(df)
What are the Ways to Replace NULL Values?
Several ways to handle and replace NULL values in a pandas DataFrame include:
- Replacing with a specific value: Using
fillna(value). - Replacing with a statistical value: Such as the mean, median, or mode of the column.
- Forward filling or backward filling: Using
fillna(method='ffill') or fillna(method='bfill'). - Dropping rows or columns with NULL values: Using
dropna().
Example of replacing with the median:
df['A'].fillna(df['A'].median(), inplace=True)
How to Replace NaN with None in df?
In pandas, NaN and None can sometimes be used interchangeably in the context of denoting missing or null values. If you specifically want to convert NaN values to None, you can use a lambda function with applymap().
Example:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A': [1, 2, np.nan, 4],
'B': ['a', 'b', 'c', np.nan]
})
# Replace NaN with None
df = df.applymap(lambda x: None if pd.isna(x) else x)
print(df)
How Do You Remove Null Values from DataFrame?
To remove null values from a DataFrame, you can use the dropna() method, which allows you to drop rows or columns that contain null values.
Example – Dropping rows with any null values:
df.dropna(inplace=True)
Example – Dropping columns with any null values:
df.dropna(axis=1, inplace=True)
Each of these methods provides a flexible way to handle missing or null values in pandas, allowing you to clean data effectively for further analysis or visualization