【问题标题】:Join two dataframes on two columns with similar strings Python用相似的字符串Python在两列上加入两个数据框
【发布时间】:2021-03-17 02:12:56
【问题描述】:

我有两个数据框(df1 和 df2),我想使用两列“州”(即阿肯色州)和“县”(即联合)进行合并。 (Union 是阿肯色州的一个县)。

df1 和 df2 需要匹配“州”和“县”,但 df2 的县名带有附加字符串(即 Woodmont County Borough),而 df1 县名(即 Woodmont)中没有。

我该怎么做才能将这两个数据框与县的不同表示形式合并?我有很多县名。

【问题讨论】:

    标签: python merge


    【解决方案1】:

    首先,获取 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',具体取决于连接的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2017-05-18
      • 1970-01-01
      相关资源
      最近更新 更多