Fill NaN with Blank String in pandas DataFrame in Python (Example Code)
In this article you’ll learn how to replace NaN values by blank character strings in a pandas DataFrame in the Python programming language.
Setting up the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A':[float('NaN'), 2, 9, 5, 1, 2, float('NaN')], # Construct example DataFrame in Python 'B':[5, 6, 6, float('NaN'), 1, 9, 2], 'C':['a', 'b', 'c', 'd', 'e', 'f', 'g']}) print(my_df) # Display example DataFrame in console # A B C # 0 NaN 5.0 a # 1 2.0 6.0 b # 2 9.0 6.0 c # 3 5.0 NaN d # 4 1.0 1.0 e # 5 2.0 9.0 f # 6 NaN 2.0 g |
my_df = pd.DataFrame({'A':[float('NaN'), 2, 9, 5, 1, 2, float('NaN')], # Construct example DataFrame in Python 'B':[5, 6, 6, float('NaN'), 1, 9, 2], 'C':['a', 'b', 'c', 'd', 'e', 'f', 'g']}) print(my_df) # Display example DataFrame in console # A B C # 0 NaN 5.0 a # 1 2.0 6.0 b # 2 9.0 6.0 c # 3 5.0 NaN d # 4 1.0 1.0 e # 5 2.0 9.0 f # 6 NaN 2.0 g
Example: Replace NaN by Blanks
my_df = my_df.fillna('') # Change NaN to empty string print(my_df) # Display updated DataFrame # A B C # 0 5.0 a # 1 2.0 6.0 b # 2 9.0 6.0 c # 3 5.0 d # 4 1.0 1.0 e # 5 2.0 9.0 f # 6 2.0 g |
my_df = my_df.fillna('') # Change NaN to empty string print(my_df) # Display updated DataFrame # A B C # 0 5.0 a # 1 2.0 6.0 b # 2 9.0 6.0 c # 3 5.0 d # 4 1.0 1.0 e # 5 2.0 9.0 f # 6 2.0 g