使用applymap到数据帧,applymap施加一拉每个单元格上的mbda函数。在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是一个列表,而不是一个大熊猫数据框(data_LastYear_Period)