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 |
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 |
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 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 |
data_new = data.copy() # Duplicate data data_new = data_new.fillna('') # Fill NaN with blanks print(data_new) # Print new data
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
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:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may want to have a look at the other tutorials on https://statisticsglobe.com/. I have published several articles already:
- How to Manipulate a pandas DataFrame in Python
- Replace Blank Values by NaN in pandas DataFrame in Python
- Check If Any Value is NaN in pandas DataFrame in Python
- Replace NaN with 0 in pandas DataFrame in Python
- Remove Rows with NaN from pandas DataFrame in Python
- Replace NaN Values by Column Mean in Python
- Basic Course for the pandas Library in Python
- Python Programming Examples
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.