strip object series without deleting the int/float cells in the series

Viewed 65

I have a series of type object, When using Series.str.strip() the cells that contain only int are getting turned into Nan.

How do I avoid this?


example

sr = pd.Series([1,2,3,'foo   '])
sr.str.strip()

0    NaN
1    NaN
2    NaN
3    foo
dtype: object

desired outcome

0    1
1    2
2    3
3    foo
dtype: object
2 Answers

The simpliest is replace missing values by original values by Series.fillna:

sr = pd.Series([1,2,3,'foo   '])

sr.str.strip().fillna(sr)

Or striping only strings tested by isinstance:

print (sr.apply(lambda x: x.strip() if isinstance(x, str) else x))

0      1
1      2
2      3
3    foo
dtype: object

You can cast the series to str altogether and then strip:

>>> sr.astype(str).str.strip()

0      1
1      2
2      3
3    foo
dtype: object

this way 1 becomes "1" and remains unchanged against stripping. But they will remain strings at the end, not integers; not sure if that's the desired output.

Related