Skip to content
Related Articles
Open in App
Not now

Related Articles

Replace NaN with Blank or Empty String in Pandas?

Improve Article
Save Article
  • Last Updated : 30 Sep, 2022
Improve Article
Save Article

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', '     ']
Explaination: 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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!