python – How to Replace All the nan Strings with Empty String in My DataFrame?

python – How to Replace All the nan Strings with Empty String in My DataFrame?

Use a list of strings to replace with blanks strings that wont affect actual nans…

df.replace([nan, None], )

Whichll give you a new dataframe of:

ID   col1    col2    col3  col4
1  Apple                   NaN
2         orange           NaN
3                 banana   NaN

Use pandas NaN. Those cells will be empty in Excel (you will be able to use select empty cells command for example. You cannot do that with empty strings).

import numpy as np
df.replace([None, nan], np.nan, inplace=True)

enter

enter

python – How to Replace All the nan Strings with Empty String in My DataFrame?

You can compare each column to the numpy object dtype (which is basically text columns), and then only do replacements for those columns.

for col in df:
    if df[col] == np.dtype(O):  # Object
        df.col1.replace([None, NaN, np.nan], , inplace=True)

Leave a Reply

Your email address will not be published. Required fields are marked *