This tutorial will discuss about different ways to replace NaN with None in pandas dataframe.
Table Of Contents
Preparing DataSet
First we will create a DataFrame, which has 3 columns, and six rows. This DataFrame has certain NaN values.
import pandas as pd import numpy as np # List of Tuples players = [ ('Suse', 123, 789), ('Aadi', np.NaN, np.NaN), ('Susen', 132, np.NaN), ('Shaunak',789, np.NaN), ('Path', np.NaN, 666), ('Ria', 890, np.NaN)] # Create a DataFrame object from list of tuples df = pd.DataFrame(players, columns=['Name', 'Level_1 Score', 'Level_2 Score']) print(df)
Output
Name Level_1 Score Level_2 Score 0 Suse 123.0 789.0 1 Aadi NaN NaN 2 Susen 132.0 NaN 3 Shaunak 789.0 NaN 4 Path NaN 666.0 5 Ria 890.0 NaN
Now we want to replace NaN
values in all columns of this DataFrame with the value None
. Let’s see how to do that.
Replace NaN with None using replace()
Pandas DataFrame provides a function replace()
, to replace all the occurrences of a given value with a replacemenet value. To replace all occurrences of NaN
with None
, create a dictionary containing only one key-value pair. Where key is ‘NaN’, and value is None
. Then Pass that dictionary as an argument to the replace()
function. It will replace all occurrences of NaN
with None
in the complete DataFrame. Also, pass inplace
as True
, due to which all modifications in DataFrame will be in place.
# Replace NaN with None in whole DataFrame df.replace({np.nan: None}, inplace=True) print(df)
Output
Frequently Asked:
Name Level_1 Score Level_2 Score 0 Suse 123.0 789.0 1 Aadi None None 2 Susen 132.0 None 3 Shaunak 789.0 None 4 Path None 666.0 5 Ria 890.0 None
It replaced all the NaN
values with None
in all the columns of DataFrame.
Summary
We learned thow to replace all occurrences of NaN values with None in complete DataFrame in Pandas.