这应该这样做。您需要使用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
现在,你可以简单地merge
的dataframes
,这将更新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
感谢您的回复,但国家名称在数据框中都不相同。我需要使用值的子字符串来匹配国家/地区名称。例如,美利坚合众国应通过采取子串美国来匹配美国,并且必须相应地提供国家代码。 – Bharath
明白了。你需要导入difflib模块然后运行这个代码df2.Country.map(lambda x:difflib.get_close_matches(x,df1.Country)[0])(我编辑了我原来的答案)。这将找到df2和df1中的国家/地区列表和最终匹配的返回。 。然后您可以加入数据框架。 – conor
对不起,它工作不正常。它返回'突尼斯'为'俄罗斯',它不想在灾难数据框架中更改我的国家名称。但是,当我尝试使用下面的代码来匹配国家名称'countryinfo [countryinfo ['ISOen_proper']。str。包含(“俄罗斯”)],但它返回整个数据帧,并且它不能在这里传递数据帧。可以有人告诉我如何为整个数据帧实现此功能并将ISO代码映射到灾难数据帧。 – Bharath