Reputation: 4933
I have following dataframe
' A ' 'B ' ' C'
0 ' 1 ' ' 2' '3'
1 '4' '5 6' '7'
2 '8' ' 9 ' '1 0'
I want to remove all spaces (rstrip
,lstrip
) data frame so that output should be as follows:
'A' 'B' 'C'
0 '1' '2' '3'
1 '4' '5 6' '7'
2 '8' '9' '1 0'
I have tried using following things:
for col in data.columns:
print (data[col].str.strip(to_strip=None))
for col in data.columns:
print (data[col].str.ltrip(to_strip=None))
data.columns = data.columns.str.replace(' ', '')
But no success.
Upvotes: 3
Views: 2373
Reputation: 294278
Use pd.DataFrame.applymap
to take care of data. Use pd.DataFrame.rename
to take care of column names.
df.applymap(str.strip).rename(columns=str.strip)
A B C
0 1 2 3
1 4 5 6 7
2 8 9 1 0
To account for that little quote guy
f = lambda x: "'" + x.strip("'").strip() + "'"
df.applymap(f).rename(columns=f)
'A' 'B' 'C'
0 '1' '2' '3'
1 '4' '5 6' '7'
2 '8' '9' '1 0'
Upvotes: 9
Reputation: 356
An alternative to strip for removing spaces at the beginning and end..
import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
Upvotes: 1