簡體   English   中英

Python:如何在數據框中拆分字符串列?

[英]Python: How to split a string column in a dataframe?

我有一個包含兩列的數據框,其中一列是Date ,另一列是Location(Object)數據類型,以下是具有值的Location列的格式:

 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,並且仍在學習,該問題是否超出標准。

一種直接的方法是apply split方法應用於列的每個元素,並選擇最后一個元素:

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

我們可以嘗試使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM