【问题标题】:Joining two dataframes based on partially matching country names基于部分匹配的国家名称连接两个数据框
【发布时间】:2021-08-22 22:07:12
【问题描述】:

目前,我有两个如下所示的数据框:

DF1:

Date Country A B C
01/01/2020 The United States 0 1 5
01/02/2020 The United States 2 5 0
01/03/2020 The United States 1 4 1
... ... ... ... ...
01/01/2020 Republic of Korea 2 3 7
01/02/2020 Republic of Korea 4 5 6

和 DF2:

Date Country D
01/01/2020 United States of America 9.0
01/02/2020 United States of America 9.1
01/03/2020 United States of America 9.4
... ... ...
01/01/2020 South Korea 2.1
01/02/2020 South Korea 2.5

我想将它们合并到 'Country' 和 'Date_reported' 但它们用于每个国家/地区的名称可能完全不同。我已经研究了fuzzywuzzy 和其他一些软件包,但我找不到一个可以让我完全按照我想要的方式进行合并的命令。我希望最终得到以下数据框(使用 DF1 的国家/地区名称):

Date Country A B C D
01/01/2020 The United States 0 1 5 9.0
01/02/2020 The United States 2 5 0 9.1
01/03/2020 The United States 1 4 1 9.4
... ... ... ... ... ...
01/01/2020 Republic of Korea 2 3 7 2.1
01/02/2020 Republic of Korea 4 5 6 2.5

有没有一种不需要我手动切换所有 DF2 国家/地区名称的有效方法?感谢您在这个主题上给我的任何帮助。

【问题讨论】:

    标签: python pandas dataframe merge fuzzywuzzy


    【解决方案1】:

    您可以尝试fuzzymatcher,但请记住,它可能不适用于所有情况。

    # pip install fuzzymatcher
    from fuzzymatcher import link_table, fuzzy_left_join
    
    merge_df = fuzzy_left_join(df, df1, ["Country", "Date"], ["Country", "Date"])
    merge_df = merge_df[["Date_left", "Country_left", "A", "B", "C", "D"]]
    
        Date_left   Country_left        A   B   C   D
    0   01/01/2020  The United States   0   1   5   9.0
    3   01/02/2020  The United States   2   5   0   9.1
    4   01/03/2020  The United States   1   4   1   9.4
    5   01/01/2020  Republic of Korea   2   3   7   2.1
    10  01/02/2020  Republic of Korea   4   5   6   2.5
    

    【讨论】:

      【解决方案2】:

      您可以创建一个在 df1 中但不在 df2 中的国家/地区列表,如下所示:

      new_list=[]
      for country in df1.country.tolist():
          if country not in df2.country.tolist():
              new_list.append(country)
              
      new_list
      

      因此,您需要在df2中更改国家/地区名称。您可以通过使用 new_list 中存在的国家/地区创建字典来做到这一点。

      dict={"United States of America":"The United States","Republic of Korea","South Korea"}
      df2["Country"].replace(dict, inplace=True)
      

      【讨论】:

        猜你喜欢
        • 2016-12-08
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-15
        • 2021-01-16
        相关资源
        最近更新 更多