Open In App

Replace NaN with Blank or Empty String in Pandas?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to replace NaN with Blank or Empty string in Pandas.

Example:

Input:  "name": ['suraj', 'NaN', 'harsha', 'NaN']
Output: "name": ['sravan',       ,  'harsha', '     ']
Explanation: Here, we replaced NaN with empty string.

Replace NaN with Empty String using replace()

We can replace the NaN with an empty string using df.replace() function. This function will replace an empty string inplace of the NaN value.

Python3




# import pandas module
import pandas as pd
 
# import numpy module
import numpy as np
 
# create dataframe with 3 columns
data = pd.DataFrame({
 
    "name": ['sravan', np.nan, 'harsha', 'ramya'],
    "subjects": [np.nan, 'java', np.nan, 'html/php'],
    "marks": [98, np.nan, np.nan, np.nan]
})
 
# replace nan with empty string
# using replace() function
data.replace(np.nan, '')


Output:

 

Replace NaN with Blank String using fillna()

The fillna() is used to replace multiple columns of NaN values with an empty string. we can also use fillna() directly without specifying columns.

Example 1:

Multiple Columns Replace Empty String without specifying columns name.

Python3




# import pandas module
import pandas as pd
 
# import numpy module
import numpy as np
 
# create dataframe with 3 columns
data = pd.DataFrame({
 
    "name": ['sravan', np.nan, 'harsha', 'ramya'],
    "subjects": [np.nan, 'java', np.nan, 'html/php'],
    "marks": [98, np.nan, np.nan, np.nan]
})
 
# replace nan with empty string
# using fillna() function
data.fillna('')


Output:

 

Example 2:

Multiple Columns Replace Empty String by specifying column name.

Python3




# import pandas module
import pandas as pd
 
# import numpy module
import numpy as np
 
# create dataframe with 3 columns
data = pd.DataFrame({
 
    "name": ['sravan', np.nan, 'harsha', 'ramya'],
    "subjects": [np.nan, 'java', np.nan, 'html/php'],
    "marks": [98, np.nan, np.nan, np.nan]
})
 
# replace nan with empty string
# using fillna() function
data[['name', 'subjects', 'marks']].fillna('')


Output:

 

RECOMMENDED ARTICLES – Check for NaN in Pandas DataFrame



Last Updated : 23 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads