Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have "None" and "nan" strings scattered in my dataframe. Is there a way to replace all of those with empty string "" or nan so they do not show up when I export the dataframe as excel sheet?

Simplified Example:

Note: nan in col4 are not strings

ID  col1   col2   col3   col4
1   Apple  nan    nan    nan
2   None   orange None   nan
3   None   nan    banana nan

The output should be like this after removing all the "None" and "nan" strings when we replaced them by empty strings "":

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

Any idea how to solve this problem?

Thanks,

like image 921
MEhsan Avatar asked Dec 01 '22 16:12

MEhsan


1 Answers

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 image description here

enter image description here

like image 174
ayhan Avatar answered Dec 04 '22 01:12

ayhan