How to replace NaN with blank/empty string?

Learn how to replace NaN with blank/empty string? By Pranit Sharma Last updated : September 19, 2023

While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell. To deal with this type of data, you can either remove the particular row (if the number of missing values is low) or you can handle these values.

Problem statement

Given a Pandas DataFrame, we have to replace NaN with blank/empty string.

Replacing NaN with blank/empty string

To replace the Nan values with blank strings, we will use dataframe.replace() method. The dataframe.replace() method in Pandas is a simple method that takes two parameters, first is the value of the string, list, dictionary, etc which has to be replaced. Secondly, it takes the value with which our data has to be replaced.

Let us understand with the help of an example.

Python program to create and print pandas dataframe

# Importing pandas package
import pandas as pd

# To create NaN values, you must import numpy package, 
# then you will use numpy.NaN to create NaN values
import numpy as np

# Creating a dictionary with some NaN values
d = {
    "Name":['Hari','Mohan','Neeti','Shaily'],
    "Age":[25,np.NaN,np.NaN,21],
    "Gender":['Male','Male',np.NaN,'Female'],
    "Profession":['Doctor','Teacher','Singer',np.NaN]
}

# Now we will create DataFrame
df = pd.DataFrame(d)

# Viewing the original DataFrame
print("Original DataFrame:\n")
print(df,"\n\n")

Output

The output of the above program is:

Example 1: Replace NaN with blank/empty string

We can clearly see the NaN values in the above output, we need to replace these NaN values with blank string.

Python program to replace NaN with blank/empty string

# Replacing NaN values with 0
df = df.replace(np.nan, "")

# Viewing The replaced vales
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example 2: Replace NaN with blank/empty string

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.