Introduction
Replacing NAN values in pandas with an empty string, we have various methods to ensure the data consistency. We will learn totally four different ways to replace the NAN values with an empty string.
Replacing NAN values methods
- Replace NAN using replace()
- Replace NAN using apply()
- Replace NAN using applymap()
- Replace NAN using fillna()
1.Replace NAN using replace()
In pandas, we can replace NAN values with an empty string using ‘replace()’ method. The replace() method should be preferred way whenever you want to replace NAN with an empty string in the DataFrame. Here’s an example program demonstrating how to do this.
import pandas as pd #sample DataFrame with NAN values df=pd.DataFrame({ 'A':[1, 2, None, 4], 'B':[None, 6, 7, 8], 'C':[9, 10, 11, None]}) #Repalce NAN values with an empty string df.replace(to_replace=pd.NA, value='',inplaceTrue) print(df)
2. Replace NAN using apply()
In pandas, you can use the ‘apply()’ method to replace NAN values with an empty string. The apply() method uses the lambda function to replace NAN values with an empty string in pandas. Here’s an example program demonstrating how to do this.
import pandas as pd #sample DataFrame with NAN values df=pd.DataFrame({ 'A':[1, 2, None, 4], 'B':[None, 6, 7, 8], 'C':[9, 10, 11, None]}) # Apply a lambda function to replace NAN values with an empty string df=df.apply(lambda x: x.fillna('') if x.d type=='0' else x) print(df)
3. Replace NAN using applymap()
In pandas, we can replace NAN values with an empty string using ‘applymap()’ method. Here in the applymap() method, you can apply lambda function to each element of the DataFrame. Here’s an example program demonstrating how to do this.
import pandas as pd #sample DataFrame with NAN values df=pd.DataFrame({ 'A':[1, 2, None, 4], 'B':[None, 6, 7, 8], 'C':[9, 10, 11, None]}) # Apply a lambda function to replace NAN values with an empty string df=df.applymap(lambda x: '' if pd.isna(x) else x) print(df)
4. Replace NAN using fillna()
In pandas, we can replace NAN values with an empty string using ‘fillna()’ method. Here’s an example program demonstrating how to do this.
import pandas as pd import numpy as np # Creating a sample DataFrame with NaN values data = {'Name': ['AMMU', 'AMAN', 'YADAV', 'VBKR'], 'Age': [20, np.nan, 21, np.nan], 'Score': [99, 91, np.nan, 95]} df = pd.DataFrame(data) # Replace NaN with empty string using fillna() df.fillna('', inplace=True) print(df)
Conclusion
In this overall article, we looked at four different ways to replacing the NAN values with an empty string in pandas DataFrame. It is recommended to use the ‘replace()’ method widely to replacing NAN values with an empty string.