2016-07-30 142 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