使用Python通过匹配国家名称的子字符串来更新数据框中国家代码列中的空值

2024-06-07 09:30:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧:Disaster,CountryInfo Disaster有一个列country code,其中有一些空值,例如:

灾难:

 1.**Country**              - **Country_code** 
 2.India                    - Null         
 3.Afghanistan (the)        - AFD
 4.India                    - IND
 5.United States of America - Null

国家信息:

^{pr2}$

预期结果

          Country Country_code
 0          India          IND
 1    Afghanistan          AFD
 2          India          IND
 3  United States           US

我需要根据国家的子字符串填写国家代码名字。可以有人建议解决这个问题吗?在


Tags: 数据code国家countrynullunited空值ind
1条回答
网友
1楼 · 发布于 2024-06-07 09:30:59

这应该行。您需要用rename更改列名,以便dataframes具有相同的列名。然后,difflib模块及其get_close_matches方法可以对Country名称进行模糊匹配和替换。然后就是简单地合并dataframes

import pandas as pd
import numpy as np
import difflib

df1 = pd.DataFrame({'Country' : ['India', 'Afghanistan', 'India', 'United States of America'],
                        'Country_code' : ['Null', 'AFD', 'IND', 'Null']})
df1
                    Country Country_code
0                     India         Null
1               Afghanistan          AFD
2                     India          IND
3  United States of America         Null

df2 = pd.DataFrame({'Country' : ['India', 'Afghanistan', 'India', 'United States'],
                    'ISO' : ['IND', 'AFD', 'IND', 'USA']})
df2
          Country ISO
0          India  IND
1    Afghanistan  AFD
2          India  IND
3  United States  USA

df2.rename(columns={'ISO' : 'Country_code'}, inplace=True)
df2
         Country Country_code
0          India          IND
1    Afghanistan          AFD
2          India          IND
3  United States          USA

下面的代码将使用df2中的Country列中提供最接近匹配的Country列中的名称进行更改。这是对子串执行某种“模糊连接”的方法。在

^{pr2}$

现在您可以简单地mergedataframes,它将更新df1中丢失的Country_code行。在

df1.merge(df2, how='right', on=['Country', 'Country_code'])

         Country Country_code
0    Afghanistan          AFD
1          India          IND
2          India          IND
3  United States          USA

相关问题 更多 >

    热门问题