Replace NaN by Empty String in pandas DataFrame in Python (Example)


In this tutorial you’ll learn how to set NaN values to blank character strings in a pandas DataFrame in the Python programming language.

The post contains these topics:

If you want to know more about these topics, keep reading…


Example Data & Libraries

First, we need to import the pandas library:

import pandas as pd                                        # Load pandas

The following data is used as basement for this Python programming tutorial:

data = pd.DataFrame({'x1':[6, 7, 3, 7, float('NaN'), 9],  # Create example DataFrame
                     'x2':[3, float('NaN'), float('NaN'), 4, 1, 3],
                     'x3':range(7, 1, - 1)})
print(data)                                               # Print example DataFrame


table 1 DataFrame replace nan empty string pandas dataframe python


Table 1 shows that our example data is made up of six rows and three columns that are named “x1”, “x2”, and “x3”.


Example: Substitute NaN Values in pandas DataFrame with Empty Cells

This example demonstrates how to exchange NaN values by blank data cells (i.e. empty character strings).

For this task, we can use the fillna function as shown in the following Python syntax:

data_new = data.copy()                                    # Duplicate data
data_new = data_new.fillna('')                            # Fill NaN with blanks
print(data_new)                                           # Print new data


table 2 DataFrame replace nan empty string pandas dataframe python


In Table 2 it is shown that we have created a new pandas DataFrame called data_new, which contains empty cells instead of NaN values.


Video, Further Resources & Summary

I have recently released a video on my YouTube channel, which shows and explains the Python syntax of this article. You can find the video below:



In case you need further information on NaN values in pandas DataFrames as shown in the Python code of this article, I recommend watching the following video of the Data School YouTube channel. In the video, the speaker explains how to handle missing values in a pandas DataFrame:



In addition, you may want to have a look at the other tutorials on I have published several articles already:


Summary: In this Python post you have learned how to replace NaN values by blank character strings in a pandas DataFrame. In case you have any additional comments or questions, please let me know in the comments.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.