If you want to replace the empty string and entries with spaces only, the correct answer is:!
df = df.replace(r'^\s*$', np.nan, regex=True)
Accepted answer
df.replace(r'\s+', np.nan, regex=True)
Does not replace an empty string!, You can try yourself with a slightly updated example:
df = pd.DataFrame([ [-0.532681, 'foo', 0], [1.490752, 'bar', 1], [-1.387326, 'fo o', 2], [0.814772, 'baz', ' '], [-0.222552, ' ', 4], [-1.176781, 'qux', ''], ], columns='AB C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))
Also note that "fo o" is not replaced with Nan, although it contains a space. Further note that this is simple:
df.replace(r'', np.NaN)
Doesnβt work either - try it.
Philipp Schwarz Dec 14 '17 at 10:20 2017-12-14 10:20
source share