Replace NaN with Blank or Empty String in Pandas?
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 as pd
import numpy as np
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]
})
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 as pd
import numpy as np
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]
})
data.fillna('')
|
Output:
Example 2:
Multiple Columns Replace Empty String by specifying column name.
Python3
import pandas as pd
import numpy as np
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]
})
data[[ 'name' , 'subjects' , 'marks' ]].fillna('')
|
Output:
RECOMMENDED ARTICLES – Check for NaN in Pandas DataFrame
Last Updated :
23 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...