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:
How to convert Float to Int in Python?
Next article icon

How to Fix: ValueError: cannot convert float NaN to integer

Last Updated : 24 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article we will discuss how to fix the value error - cannot convert float NaN to integer in Python.

In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer.

Let's see the error and explore the methods to deal with it.

Dataset in use:

Let's check the error when converting from float type (marks column) to integer type. We can convert by using astype() function

Example: Depicting the error

Python3
# import pandas import pandas  # import numpy import numpy  # create a dataframe dataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh',                                         'sridevi', 'vijay', 'sreemukhi'],                               'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]})  # convert to integer type dataframe['marks'].astype(int) 

Output:

ValueError: Cannot convert non-finite values (NA or inf) to integer

Because the NaN values are not possible to convert the dataframe. So in order to fix this issue, we have to remove NaN values

Method 1: Drop rows with NaN values

Here we are going to remove NaN values from the dataframe column by using dropna() function. This function will remove the rows that contain NaN values.

Syntax:

dataframe.dropna()

Example: Dealing with error 

Python3
# import pandas import pandas  # import numpy import numpy  # create a dataframe dataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh',                                        'sridevi', 'vijay',                                         'sreemukhi'],                               'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]}) # display data type print(dataframe['marks'] .dtype)   # drop the NaN values dataframe = dataframe.dropna()  # display print(dataframe)  # convert to integer type for marks column dataframe['marks'] = dataframe['marks'].astype(int)  # display data type dataframe['marks'] .dtype 

Output:

Method 2: Replace NaN values with 0

We can replace NaN values with 0 to get rid of NaN values. This is done by using fillna() function. This function will check the NaN values in the dataframe columns and fill the given value.

Syntax:

dataframe.fillna(0)

Example: Dealing with the error

Python3
# import pandas import pandas  # import numpy import numpy  # create a dataframe dataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh',                                         'sridevi', 'vijay',                                         'sreemukhi'],                               'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]}) # display data type print(dataframe['marks'] .dtype)  # replace NaN values with 0 dataframe = dataframe.fillna(0)  # display print(dataframe)  # convert to integer type for marks column dataframe['marks'] = dataframe['marks'].astype(int)  # display data type dataframe['marks'] .dtype 

Output:

Method 3: Using numpy.nan_to_num()

Here we are using NumPy to convert NaN values to 0 numbers.

Syntax:

numpy.nan_to_num(numpy.nal)

Example: Dealing with the error

Python3
# import modules import numpy  # create an nan value data = numpy.nan  # display print(data)  # convert man to value final = numpy.nan_to_num(data)  # display final 

Output:

nan 0.0

Method 4: Use Nullable 

We can create nan value as NaN, this does not create any error while converting float to integer.

Syntax:

numpy.NaN

Example: Dealing with the error

Python3
# import pandas import pandas  # import numpy import numpy  # create a dataframe dataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh',                                         'sridevi', 'vijay',                                        'sreemukhi'],                               'marks': [90.3, numpy.NaN, 67.8, 89, numpy.NaN]}) # display data type print(dataframe['marks'] .dtype)  # replace NaN values with 0 dataframe = dataframe.fillna(0)  # display print(dataframe)  # convert to integer type for marks column dataframe['marks'] = dataframe['marks'].astype(int)  # display data type dataframe['marks'] .dtype 

Output:

float64         name  marks 0   sireesha   90.3 1    gnanesh    0.0 2    sridevi   67.8 3      vijay   89.0 4  sreemukhi    0.0 dtype('int64')

Next Article
How to convert Float to Int in Python?
author
sireeshakanneganti112
Improve
Article Tags :
  • Python
  • Python How-to-fix
Practice Tags :
  • python

Similar Reads

  • How To Fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python
    In this article, we'll delve into understanding of typeerror and how to fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python. Types of Errors in Python Script ExecutionThere are many different types of errors that can occur while executing a python script. These errors indicate
    3 min read
  • How To Fix Valueerror Exceptions In Python
    Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Pyth
    4 min read
  • How to Convert Integers to Floats in Pandas DataFrame?
    Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, etc. There are 2 methods to convert Integers to Floats: Method 1: Using DataFrame.astype() method Syntax :  DataFrame.astype(dtype, co
    4 min read
  • How to Convert NumPy Array of Floats into Integers
    In this article, we will see how to convert NumPy Array of Floats into Integers. We are given a NumPy array of float-type values. Our task is to convert all float-type values of Numpy array to their nearest array of integer values. Input: [1.2, 4.5, 9.1, 6.5, 8.9, 2.3, 1.2] Output: [1, 4, 9, 6, 8, 2
    4 min read
  • How to convert Float to Int in Python?
    In Python, you can convert a float to an integer using type conversion. This process changes the data type of a value However, such conversions may be lossy, as the decimal part is often discarded. For example: Converting 2.0 (float) to 2 (int) is safe because here, no data is lost.But converting 3.
    5 min read
  • Cannot Convert String To Float in Python
    Python, a versatile and powerful programming language, is widely used for data manipulation and analysis. However, developers often encounter challenges, one of which is the "Cannot Convert String To Float" error. This error occurs when attempting to convert a string to a float, but the string's con
    3 min read
  • How to Fix: TypeError: ‘numpy.float’ object is not callable?
    In this article, we are going to see how to fix TypeError: ‘numpy.float’ object is not callable in Python. There is only one case in which we can see this error:  If we try to call a NumPy array as a function, we are most likely to get such an error.  Example: [GFGTABS] Python3 import numpy as np a
    1 min read
  • How to Convert float64 Columns to int64 in Pandas?
    float64 represents a floating-point number with double precision and int64 represents a 64-bit integer number. In this article, we will learn to Convert float64 Columns to int64 in Pandas using different methods Convert float64 Columns to int64 in Pandas DataFrameTo transform a Pandas column to an i
    4 min read
  • Convert Floats to Integers in a Pandas DataFrame
    Let us see how to convert float to integer in a Pandas DataFrame. We will be using the astype() method to do this. It can also be done using the apply() method. Convert Floats to Integers in a Pandas DataFrameBelow are the ways by which we can convert floats to integers in a Pandas DataFrame: Using
    3 min read
  • How to Fix "TypeError: 'float' object is not callable" in Python
    In Python, encountering the error message "TypeError: 'float' object is not callable" is a common issue that can arise due to the misuse of the variable names or syntax errors. This article will explain why this error occurs and provide detailed steps to fix it along with the example code and common
    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