在此示例中,如何从 Python DataFrame 中去除空格

How to strip whitespaces from Python DataFrame in this example

我正在将 excel 文件读入 DataFrame。我需要从所有单元格中去除空白,在 Python 3.5 中保持其他单元格不变。 例如:

from pandas import Series, DataFrame
import pandas as pd
import numpy as np

#read data from DataFrame
data_ThisYear_Period=[[' 序 号','北  京','上  海','  广州'],\
                      ['  总计','11232',' 2334','3 4'],\
                      [' 温度','1223','23 23','2323'],\
                      ['人 口','1232','21 321','1222'],\
                      ['自行车', '1232', '21321', '12  22']]
data_LastYear_Period=DataFrame(data_ThisYear_Period)
print(type(data_LastYear_Period))

data_ThisYear_Period.apply(data_ThisYear_Period.str.strip(),axis=1)

追溯(最近一次通话): 文件 "C:/test/temp.py",第 17 行,位于 data_ThisYear_Period.apply(data_ThisYear_Period.str.strip(),轴=1) AttributeError: 'list' 对象没有属性 'apply'

在此示例中如何从 Python DataFrame 中去除空格

对数据框使用 applymap,applymap 在每个单元格上应用 lambda 函数。在 lambda 函数中拆分字符串(忽略其中的空格)然后加入它。如果有一个int,那么你可以在lambda函数中使用if else。

from pandas import Series, DataFrame
import pandas as pd
import numpy as np

#read data from DataFrame
data_ThisYear_Period=[[' 序 号','北  京','上  海','  广州'],\
                      ['  总计','11232',' 2334','3 4'],\
                      [' 温度','1223','23 23','2323'],\
                      ['人 口',1232,'21 321','1222'],\
                      ['自行车', '1232', '21321', '12  22']]

data_LastYear_Period=DataFrame(data_ThisYear_Period)
print data_LastYear_Period
data_LastYear_Period = data_LastYear_Period.applymap((lambda x: "".join(x.split()) if type(x) is str else x ))

print data_LastYear_Period

结果

      0      1       2       3
0   序 号   北  京    上  海      广州
1    总计  11232    2334     3 4
2    温度   1223   23 23    2323
3   人 口   1232  21 321    1222
4   自行车   1232   21321  12  22

     0      1      2     3
0   序号     北京     上海    广州
1   总计  11232   2334    34
2   温度   1223   2323  2323
3   人口   1232  21321  1222
4  自行车   1232  21321  1222

附带说明一下,您收到此特定错误是因为

data_ThisYear_Period.apply(data_ThisYear_Period.str.strip(),axis=1)

data_ThisYear_Period 是一个列表而不是 pandas 数据框 (data_LastYear_Period)