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:

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

Similar Reads

Method 1: Drop rows with NaN values

...

Method 2: Replace NaN values with 0

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

Method 3: Using numpy.nan_to_num()

...

Method 4: Use Nullable

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