How to use numpy.nan_to_num() In Python
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
How to Fix: ValueError: cannot convert float NaN to integer
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