Replacing empty strings with NaN in Pandas

I have a pandas dataframe (which was created by importing a csv file). I want to replace empty values ​​with NaN. Some of these empty values ​​are empty, and some contain (variable number) spaces '' , ' ' , ' ' , etc.

Using this thread sentence I have

 df.replace(r'\s+', np.nan, regex=True, inplace = True) 

which replaces all lines containing only spaces, but also replaces every line that has a space, and that is not what I want.

How to replace only lines with spaces and empty lines only?

+5
source share
1 answer

Indicate that it should start with a space and end with spaces with the ^ and $ characters:

 df.replace(r'^\s*$', np.nan, regex=True, inplace = True) 
+6
source

Source: https://habr.com/ru/post/1260057/


All Articles