2017-03-23 1415 views
0

我正在讀取一個excel文件到DataFrame中。我需要從所有單元格中刪除空格,而其他單元格在Python 3.5中保持不變。 例如:如何從Python DataFrame中去除空格在這個例子中

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的:「列表」對象沒有屬性「應用」

如何從數據幀的Python剝離空格在這個例子中

回答

1

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

+0

非常感謝你!在這個例子中,它可以工作,但是當我從excel中讀取DataFrame時,它會失效:AttributeError:(「'int'object has no attribute'split'」,'index on sequence sequence number'),我該如何解決它?謝謝 ! – chenhong

+0

如果有一個int,那麼你可以在lambda函數中使用if else。請參閱編輯。 – plasmon360

+0

謝謝!有用! – chenhong

相關問題