簡體   English   中英

用相似的字符串連接兩列上的兩個數據框 Python

[英]Join two dataframes on two columns with similar strings Python

我有兩個數據框(df1 和 df2),我想使用兩列合並,“州”(即阿肯色州)和“縣”(即聯合)。 (聯盟是阿肯色州的一個縣)。

df1 和 df2 需要匹配 'State' 和 'County',但 df2 的縣名帶有額外的字符串(即 Woodmont County Borough),但在 df1 縣名(即 Woodmont)中找不到。

我該怎么做才能將這兩個數據框與縣的不同表示合並? 我有很多縣名。

首先,獲取 df1 中的“縣”列表

然后,在 df2 中創建一個新列,如果在 df2.County 中找到 County_list 中的縣,則將其存儲在我們稱為 County_cleaned 的新列中

然后對於county_list中的每個縣,如果它出現在df2['County']中,則將其放入新創建的County_cleaned

現在,您可以使用 df2 中新創建的列將 df1 和 df2 合並在一起(我們稱之為 df3):

# get a list of the counties in df1
county_list = df1.County.unique()

#initialise a new column to empty string
df2['County_cleaned'] = ''

#for each of the counties in df1, if a county from df1 appears 
#somewhere in the df2.County, then add it to the newly created 
#column called County_cleaned 
for c in county_list:
    df2.loc[df2['County'].str.contains(c), 'County_cleaned']=c

#merge the 2 dataframes to create df3
df3 = df1.merge(df, how='inner', left_on=['State','County'], right_on=['State', 'County_cleaned')

注意:我設置了 how='inner' 但這也可以是 'outer','left','right' 取決於連接的類型。

暫無
暫無

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

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