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
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Python | Pandas dataframe.clip()
Next article icon

Python | Pandas DataFrame.fillna() to replace Null values in dataframe

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
    • After 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.



Next Article
Python | Pandas dataframe.clip()

K

Kartikaybhutani
Improve
Article Tags :
  • Python
  • Pandas-DataFrame-Methods
  • Python pandas-dataFrame
  • python-modules
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • Pandas Functions in Python: A Toolkit for Data Analysis
    Pandas is one of the most used libraries in Python for data science or data analysis. It can read data from CSV or Excel files, manipulate the data, and generate insights from it. Pandas can also be used to clean data, filter data, and visualize data. Whether you are a beginner or an experienced pro
    6 min read
  • Pandas Read CSV in Python
    CSV files are the Comma Separated Files. It allows users to load tabular data into a DataFrame, which is a powerful structure for data manipulation and analysis. To access data from the CSV file, we require a function read_csv() from Pandas that retrieves data in the form of the data frame. Here’s a
    7 min read
  • Python | Pandas Dataframe/Series.head() method
    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. Pandas head() method is used to return top n (5 by default) rows of a data frame or se
    2 min read
  • Pandas Dataframe/Series.tail() method - Python
    Python is a popular language for data analysis because it has many useful libraries. One of these libraries is Pandas, which makes working with data easier. The .tail() method in Pandas helps us see the last n rows of a DataFrame or Series. This is useful when dealing with large datasets and we need
    2 min read
  • Pandas Dataframe.sample() | Python
    Pandas DataFrame.sample() function is used to select randomly rows or columns from a DataFrame. It proves particularly helpful while dealing with huge datasets where we want to test or analyze a small representative subset. We can define the number or proportion of items to sample and manage randomn
    2 min read
  • Python | Pandas dataframe.info()
    The `dataframe.info()` function in Pandas proves to be an invaluable tool for obtaining a succinct summary of a dataframe. This function is particularly useful during exploratory analysis, offering a quick and informative overview of the dataset. Leveraging `dataframe.info()` is an efficient way to
    4 min read
  • Pandas DataFrame dtypes Property | Find DataType of Columns
    Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns).  Pandas DataFrame.dtypes attribute returns a series with the data type of each column. Example: [GFGTABS] Python import pandas as pd df = pd.DataFrame({'Weig
    3 min read
  • Pandas df.size, df.shape and df.ndim Methods
    Understanding structure of our data is an important step in data analysis and Pandas helps in making this easy with its df.size, df.shape and df.ndim functions. They allow us to identify the size, shape and dimensions of our DataFrame. In this article, we will see how to implement these functions in
    2 min read
  • Pandas DataFrame describe() Method
    describe() method in Pandas is used to generate descriptive statistics of DataFrame columns. It gives a quick summary of key statistical metrics like mean, standard deviation, percentiles, and more. By default, describe() works with numeric data but can also handle categorical data, offering tailore
    3 min read
  • Python | Pandas Series.unique()
    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. While analyzing the data, many times the user wants to see the unique values in a par
    1 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