Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white space from pandas data frame

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.

like image 942
Piyush S. Wanare Avatar asked Dec 17 '25 23:12

Piyush S. Wanare


1 Answers

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'
like image 159
piRSquared Avatar answered Dec 20 '25 13:12

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!