简体   繁体   English

从pandas数据框中删除空格

[英]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: 我想删除所有空格( rstriplstrip )数据框,以便输出应如下所示:

     '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. 但没有成功。

Use pd.DataFrame.applymap to take care of data. 使用pd.DataFrame.applymap来处理数据。 Use pd.DataFrame.rename to take care of column names. 使用pd.DataFrame.rename来处理列名。

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'

An alternative to strip for removing spaces at the beginning and end.. 用于在开始和结束时移除空间的条带的替代方案..

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM