ADVERTISEMENT
ADVERTISEMENT

How to Replace NaN Values with Zeros in Pandas DataFrame?

Given a DataFrame, we have to replace the NaN values with zeros.
Submitted by Pranit Sharma, on April 25, 2022

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. To deal with this type of data, you can either remove the particular row (if the number of missing values is low) or you can handle these values.

To replace the Nan values with zeroes we will use a DataFrame.replace() method.

pandas.DataFrame.replace() Method

The DataFrame.replace() method in Pandas is a simple method that takes two parameters, first is the value of the string, list, dictionary, etc which has to be replaced. Secondly, it takes the value with which our data has to be replaced.

Syntax:

DataFrame.replace(
    to_replace=None, 
    value=NoDefault.no_default, 
    inplace=False, 
    limit=None, 
    regex=False, 
    method=NoDefault.no_default
    )

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with the help of an example.

# Importing pandas package
import pandas as pd

# To create NaN values, you must import numpy package, 
# then you will use numpy.NaN to create NaN values
import numpy as np

# Creating a dictionary with some NaN values
d = {
    "Name":['Hari','Mohan','Neeti','Shaily'],
    "Age":[25,np.NaN,np.NaN,21],
    "Gender":['Male','Male',np.NaN,'Female'],
    "Profession":['Doctor','Teacher','Singer',np.NaN]
}

# Now, Create DataFrame
df = pd.DataFrame(d)

# Printing the original DataFrame
print("Original DataFrame:\n")
print(df,"\n\n")

# Replacing NaN values with 0
df = df.replace(np.nan, 0)

# Printing The replaced vales
print("Modified DataFrame:\n",df)

Output:

Replace NaN Values with Zeros | Example

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.