2016-07-30 52 views
2

我有兩列的數據幀一個是Date,另一種是Location(Object)數據類型,下面是位置的列與值的格式:Python:如何拆分數據框中的字符串列?

Date           Location 
1  07/12/1912       AtlantiCity, New Jersey 
2  08/06/1913     Victoria, British Columbia, Canada 
3  09/09/1913         Over the North Sea 
4  10/17/1913       Near Johannisthal, Germany 
5  03/05/1915         Tienen, Belgium 
6  09/03/1915        Off Cuxhaven, Germany 
7  07/28/1916        Near Jambol, Bulgeria 
8  09/24/1916        Billericay, England 
9  10/01/1916        Potters Bar, England 
10 11/21/1916          Mainz, Germany 

我的要求是","分離分割位置只保留位置列中的第二部分(ex. New Jersey, Canada, Germany, England etc..)。我也必須檢查它是否只有一個元素(值爲單個元素沒有「,」)

有沒有一種方法,我可以用預定義的方法做到這一點,而無需循環每一行?

對不起,如果問題不符合標準,因爲我是新來的Python,仍然在學習。

回答

2

一種直接的方式是applysplit法柱的每個元素,拿起最後一個:

df.Location.apply(lambda x: x.split(",")[-1]) 

1    New Jersey 
2     Canada 
3  Over the North Sea 
4    Germany 
5    Belgium 
6    Germany 
7    Bulgeria 
8    England 
9    England 
10    Germany 
Name: Location, dtype: object 

要檢查每個單元都有,我們可以在使用str.contains方法只有一個元素列:

df.Location.str.contains(",") 

1  True 
2  True 
3  False 
4  True 
5  True 
6  True 
7  True 
8  True 
9  True 
10  True 
Name: Location, dtype: bool 
1

我們可以與嘗試str.extract

print(df['Location'].str.extract(r'([^,]+$)'))  
#0   New Jersey 
#1    Canada 
#2 Over the North Sea 
#3    Germany 
#4    Belgium 
#5    Germany 
#6    Bulgeria 
#7    England 
#8    England 
#9    Germany