使用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)