I think need check if values are strings, because mixed values in column - numeric with strings and for each string call strip:
df = df.map(lambda x: x.strip() if isinstance(x, str) else x)
print (df)
A B C
0 A b 2 3.0
1 NaN 2 3.0
2 random 43 4.0
3 any txt is possible 2 1 22.0
4 23 99.0
5 help 23 NaN
If columns have same dtypes, not get NaNs like in your sample for numeric values in column B:
cols = df.select_dtypes(['object']).columns
df[cols] = df[cols].apply(lambda x: x.str.strip())
print (df)
A B C
0 A b NaN 3.0
1 NaN NaN 3.0
2 random NaN 4.0
3 any txt is possible 2 1 22.0
4 NaN 99.0
5 help NaN NaN
(original answer used applymap which is depreciated)
Answer from jezrael on Stack OverflowI think need check if values are strings, because mixed values in column - numeric with strings and for each string call strip:
df = df.map(lambda x: x.strip() if isinstance(x, str) else x)
print (df)
A B C
0 A b 2 3.0
1 NaN 2 3.0
2 random 43 4.0
3 any txt is possible 2 1 22.0
4 23 99.0
5 help 23 NaN
If columns have same dtypes, not get NaNs like in your sample for numeric values in column B:
cols = df.select_dtypes(['object']).columns
df[cols] = df[cols].apply(lambda x: x.str.strip())
print (df)
A B C
0 A b NaN 3.0
1 NaN NaN 3.0
2 random NaN 4.0
3 any txt is possible 2 1 22.0
4 NaN 99.0
5 help NaN NaN
(original answer used applymap which is depreciated)
I think there is a one-liner for that using regex and replace:
df = df.replace(r"^ +| +$", r"", regex=True)
Explanation for the regex:
- ^ is line start
- (space and plus, +) is one or more spaces
- | is or
- $ is line end.
So it searches for leading (line start and spaces) and trailing (spaces and line end) spaces and replaces them with an empty string.