2016-09-26 93 views
0

我有两个数据帧匹配国家名称的字符串在数据帧COUNTRYCODE列中的空值:灾难,CountryInfo灾害具有例如具有一些空值的列国家代码:更新通过使用python

灾害:

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

CountryInfo:

0.**CountryName** - **ISO** 
1.India    - IND 
2.Afganistan  - AFD 
3.United States  - US 

预期结果

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

我需要填写国家代码参考国家名称的子字符串。任何人都可以为此提出解决方案吗?

回答

0

这应该这样做。您需要使用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与名称中df1提供最接近的匹配改变Country列在Country列一个简单的事情。这是在子串上执行一种“模糊连接”的一种方式。

df1['Country'] = df1.Country.map(lambda x: difflib.get_close_matches(x, df2.Country)[0]) 
df1 
     Country Country_code 
0   India   Null 
1 Afghanistan   AFD 
2   India   IND 
3 United States   Null 

现在,你可以简单地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 
+0

感谢您的回复,但国家名称在数据框中都不相同。我需要使用值的子字符串来匹配国家/地区名称。例如,美利坚合众国应通过采取子串美国来匹配美国,并且必须相应地提供国家代码。 – Bharath

+0

明白了。你需要导入difflib模块然后运行这个代码df2.Country.map(lambda x:difflib.get_close_matches(x,df1.Country)[0])(我编辑了我原来的答案)。这将找到df2和df1中的国家/地区列表和最终匹配的返回。 。然后您可以加入数据框架。 – conor

+0

对不起,它工作不正常。它返回'突尼斯'为'俄罗斯',它不想在灾难数据框架中更改我的国家名称。但是,当我尝试使用下面的代码来匹配国家名称'countryinfo [countryinfo ['ISOen_proper']。str。包含(“俄罗斯”)],但它返回整个数据帧,并且它不能在这里传递数据帧。可以有人告诉我如何为整个数据帧实现此功能并将ISO代码映射到灾难数据帧。 – Bharath