Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Replace NaN Values with Zeros in Pandas DataFrame
Next article icon

Replace all the NaN values with Zero's in a column of a Pandas dataframe

Last Updated : 25 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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, value=None, method=None, axis=None, inplace=False, limit=None,                                  downcast=None)

Parameters: This method will take following parameters:

  • value (scalar, dict, Series, or DataFrame):  Specify the value to use to fill null values.
  • method([‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None], default None): Specify the method used to fill null values.
  • axis (0 or ‘index’, 1 or ‘columns’): Specify the axis along which to fill missing values.
  • inplace(bool, default False): If bool value is True, fill in-place which will modify any other views on this object.
  • limit(int, default None): Specify the maximum number of consecutive NaN values to forward/backward fill.
  • downcast(dict, default is None): A dict of item dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible).

Returns: DataFrame or None. Object with null values filled or None if inplace=True.

Code: Create a Dataframe.

Python3
# Import Pandas Library import pandas as pd  # Import Numpy Library import numpy as np  # Create a DataFrame df = pd.DataFrame([[np.nan, 2, 3, np.nan],                    [3, 4, np.nan, 1],                    [1, np.nan, np.nan, 5],                    [np.nan, 3, np.nan, 4]])  # Show the DataFrame print(df) 

Output:

dataframe with NaN values

Code: Replace all the NaN values with Zero's

Python3
# Filling null values # with 0 df.fillna(value = 0,            inplace = True)  # Show the DataFrame print(df) 

Output:

dataframe with zero's values

                                                        DataFrame.replace():

This method is used to replace null or null values with a specific value.

Syntax: DataFrame.replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False,                         method='pad')

Parameters: This method will take following parameters:

  • to_replace(str, regex, list, dict, Series, int, float, None): Specify the values that will be replaced.
  • value(scalar, dict, list, str, regex, default value is None): Specify the value to replace any values matching to_replace with.
  • inplace(bool, default False): If a value is True, in place. Note: this will modify any other views on this object.
  • limit(int, default None): Specify the maximum size gap to forward or backward fill.
  • regex(bool or same types as to_replace, default False): If a value is True then to_replace must be a string. Alternatively, this could be a regular expression or a list,  dict, or array of regular expressions in which case to_replace must be None.
  • method {‘pad’, ‘ffill’, ‘bfill’, None}: Specify the method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.

Returns: DataFrame. Object after replacement.

Code: Create a Dataframe.

Python3
# Import Pandas Library import pandas as pd  # Import Numpy Library import numpy as np  # Create a DataFrame df = pd.DataFrame([[np.nan, 2, 3, np.nan],                    [3, 4, np.nan, 1],                    [1, np.nan, np.nan, 5],                    [np.nan, 3, np.nan, 4]])  # Show the DataFrame print(df) 

Output:

dataframe with NaN values

Code: Replace all the NaN values with Zero's

Python3
# Filling null values with 0 df = df.replace(np.nan, 0)  # Show the DataFrame print(df) 

Output:

dataframe with zero's values

Next Article
Replace NaN Values with Zeros in Pandas DataFrame

A

adityamankar
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Replace NaN Values with Zeros 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
    5 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 met
    5 min read
  • Replace the column contains the values 'yes' and 'no' with True and False In Python-Pandas
    Let’s discuss a program To change the values from a column that contains the values 'YES' and 'NO' with TRUE and FALSE.   First, Let's see a dataset. Code: [GFGTABS] Python3 # import pandas library import pandas as pd # load csv file df = pd.read_csv("supermarkets.csv") # show the datafram
    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
    3 min read
  • How to drop all columns with null values in a PySpark DataFrame ?
    The pyspark.sql.DataFrameNaFunctions class in PySpark has many methods to deal with NULL/None values, one of which is the drop() function, which is used to remove/delete rows containing NULL values in DataFrame columns. You can also use df.dropna(), as shown in this article. You may drop all rows in
    3 min read
  • Drop rows from Pandas dataframe with missing values or NaN in columns
    We are given a Pandas DataFrame that may contain missing values, also known as NaN (Not a Number), in one or more columns. Our task is to remove the rows that have these missing values to ensure cleaner and more accurate data for analysis. For example, if a row contains NaN in any specified column,
    4 min read
  • How to Drop Rows with NaN Values in Pandas DataFrame?
    In Pandas missing values are represented as NaN (Not a Number) which can lead to inaccurate analyses. One common approach to handling missing data is to drop rows containing NaN values using pandas. Below are some methods that can be used: Method 1: Using dropna()The dropna() method is the most stra
    2 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. Ju
    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
    2 min read
  • How to Replace Values in Column Based on Condition in Pandas?
    Let's explore different methods to replace values in a Pandas DataFrame column based on conditions. Replace Values Using dataframe.loc[] FunctionThe dataframe.loc[] function allows us to access a subset of rows or columns based on specific conditions, and we can replace values in those subsets. df.l
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences