Open In App

Replace NaN Values with Zeros in Pandas DataFrame

Last Updated : 09 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. 

Replace NaN Values with Zeros in Pandas DataFrame

 

Methods to Replace NaN Values with Zeros in Pandas DataFrame

In Python, there are two methods by which we can replace NaN values with zeros in Pandas dataframe. They are as follows:

Replace NaN Values with Zeros using Pandas fillna() 

The fillna() function is used to fill NA/NaN values using the specified method. Let us see a few examples for a better understanding.

Replace NaN values with zeros for a column using Pandas fillna() 

Syntax to replace NaN values with zeros of a single column in Pandas dataframe using fillna() function is as follows:

Syntax: df['DataFrame Column'] = df['DataFrame Column'].fillna(0)

Python3




# importing libraries
import pandas as pd
import numpy as np
 
nums = {'Set_of_Numbers': [2, 3, 5, 7, 11, 13,
                           np.nan, 19, 23, np.nan]}
 
# Create the dataframe
df = pd.DataFrame(nums, columns =['Set_of_Numbers'])
 
# Apply the function
df['Set_of_Numbers'] = df['Set_of_Numbers'].fillna(0)
 
# print the DataFrame
df


Output:

Replace NaN values with zero for a single column using Panda fillna()

fillna() to replace NaN for a single column

Replace NaN values with zeros for an entire column using Pandas fillna() 

Syntax to replace NaN values with zeros of the whole Pandas dataframe using fillna() function is as follows:

Syntax: df.fillna(0)

Python3




# importing libraries
import pandas as pd
import numpy as np
 
nums = {'Number_set_1': [0, 1, 1, 2, 3, 5, np.nan,
                         13, 21, np.nan],
       'Number_set_2': [3, 7, np.nan, 23, 31, 41,
                        np.nan, 59, 67, np.nan],
       'Number_set_3': [2, 3, 5, np.nan, 11, 13, 17,
                        19, 23, np.nan]}
 
# Create the dataframe
df = pd.DataFrame(nums)
 
# Apply the function
df = df.fillna(0)
 
# print the DataFrame
df


Output:

Replace NaN values with zero for whole dataframe using Panda fillna()

fillna() function  to replace NaN for the whole dataframe

Replace NaN Values with Zeros using NumPy replace() 

The dataframe.replace() function in Pandas can be defined as a simple method used to replace a string, regex, list, dictionary, etc. in a DataFrame.

Replace NaN values with zeros for a column using NumPy replace() 

Syntax to replace NaN values with zeros of a single column in Pandas dataframe using replace() function is as follows:

Syntax: df['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0)

Python3




# importing libraries
import pandas as pd
import numpy as np
 
nums = {'Car Model Number': [223, np.nan, 237, 195, np.nan,
                             575, 110, 313, np.nan, 190, 143,
                             np.nan],
       'Engine Number': [4511, np.nan, 7570, 1565, 1450, 3786,
                         2995, 5345, 7777, 2323, 2785, 1120]}
 
# Create the dataframe
df = pd.DataFrame(nums, columns =['Car Model Number'])
 
# Apply the function
df['Car Model Number'] = df['Car Model Number'].replace(np.nan, 0)
 
# print the DataFrame
df


Output:

Replace NaN values with zero for a single column using NumPy replace()

replace() to replace NaN for a single column

Replace NaN values with zeros for an entire Dataframe using NumPy replace() 

Syntax to replace NaN values with zeros of the whole Pandas dataframe using replace() function is as follows:

Syntax: df.replace(np.nan, 0)

Python3




# importing libraries
import pandas as pd
import numpy as np
 
nums = {'Student Name': [ 'Shrek', 'Shivansh', 'Ishdeep'
                         'Siddharth', 'Nakul', 'Prakhar',
                         'Yash', 'Srikar', 'Kaustubh',
                         'Aditya''Manav', 'Dubey'],
        'Roll No.': [ 18229, 18232, np.nan, 18247, 18136,
                     np.nan, 18283, 18310, 18102, 18012,
                     18121, 18168],
        'Subject ID': [204, np.nan, 201, 105, np.nan, 204,
                       101, 101, np.nan, 165, 715, np.nan],
       'Grade Point': [9, np.nan, 7, np.nan, 8, 7, 9, 10,
                       np.nan, 9, 6, 8]}
 
# Create the dataframe
df = pd.DataFrame(nums)
 
# Apply the function
df = df.replace(np.nan, 0)
 
# print the DataFrame
df


Output:

Replace NaN values with zero for whole dataframe using NumPy replace()

replace() function  to replace NaN for the whole dataframe



Similar Reads

Replace all the NaN values with Zero's in a column of a Pandas dataframe
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it. DataFrame.fillna(): This method is used to fill null or null values with a specific value. Syntax: DataFrame.fillna(self,
3 min read
Ways to Create NaN Values in Pandas DataFrame
Let's discuss ways of creating NaN values in the Pandas Dataframe. There are various ways to create NaN values in Pandas dataFrame. Those are: Using NumPy Importing csv file having blank values Applying to_numeric function Method 1: Using NumPy C/C++ Code import pandas as pd import numpy as np num = {'number': [1,2,np.nan,6,7,np.nan,np.nan]} df = p
1 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Count NaN or missing values in Pandas DataFrame
In this article, we will see how to Count NaN or missing values in Pandas DataFrame using isnull() and sum() method of the DataFrame. Dataframe.isnull() method Pandas isnull() function detect missing values in the given object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing
5 min read
Count the NaN values in one or more columns in Pandas DataFrame
Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value. Consider the following DataFrame. # importing the modules impo
2 min read
Highlight the nan values in Pandas Dataframe
In this article, we will discuss how to highlight the NaN (Not a number) values in Pandas Dataframe. NaN values used to represent NULL values and sometimes it is the result of the mathematical overflow.Lets first make a dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe d
2 min read
How to Drop Columns with NaN Values in Pandas DataFrame?
Nan(Not a number) is a floating-point value which can't be converted into other data type expect to float. In data analysis, Nan is the unnecessary value which must be removed in order to analyze the data set properly. In this article, we will discuss how to remove/drop columns having Nan values in the pandas Dataframe. We have a function known as
3 min read
How to Drop Rows with NaN Values in Pandas DataFrame?
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. In this article, we will
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
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 rem
3 min read
Practice Tags :