我有 2 个数据框 - 称它们为 df1
和df2
.
第一个看起来像:
df1
Name G ID Type Source Year
Washington WTG1 Normal Lin 2002
Washington 1 Normal Lin 2001
Washington 4 Normal BOX
Eddie GT2 Normal Lin
Mann 1 New BOX 2018
Mann 2 Normal BOX
Mann SI-01 Old Lin 2017
Mann GGh Old Lin
.
.
第二个看起来像:
df2
Name Unit ID Year
Washington WTG-1 2002
Washington 1 2001
Washington 4 2003
Eddie GT02 2010
Mann 1 2018
Mann 2 2001
Mann SI1 2017
Mann JO 2000
.
.
如您所见 df1
有一些 Year
值 df2
有,但何时有或没有是随机的。另外,一些值如 GGh
在Mann
的df2
显然没有匹配项。
G ID
和Unit ID
是我最有兴趣与之合并的。我需要一种方法在合并年份后制定一些条件(这些条件非常准确),其中 ID
值可用于合并。
条件类似于 Levenshtein Distance:
if i in df1['G ID']
不匹配j in df2['Unit ID']
-> Calculate LD
-> 如果distance is close enough
然后加入
我知道这是非常伪的代码,但我不知道如何继续。 有办法做到这一点吗?
最佳答案
您可以尝试使用 difflib
中的 .get_close_matches()
方法,如下所示:
import difflib
# make a key column to merge based on close matches
df2['Fuzzy_Key'] = df2.Unit_ID.map(lambda x: difflib.get_close_matches(x, df1.G_ID))
# since the values in our Fuzzy_Key column are lists, we have to convert them to strings
df2['Fuzzy_Key'] = df2.Fuzzy_Key.apply(lambda x: ''.join(map(str, x)))
输出
Name Unit_ID Year Fuzzy_Key
0 Washington WTG-1 2002 WTG1
1 Washington 1 2001 11
2 Washington 4 2003 4
3 Eddie GT02 2010 GT2
4 Mann 1 2018 11
5 Mann 2 2001 2
6 Mann SI1 2017 SI-01
7 Mann JO 2000
之后,我们可以合并新创建的Fuzzy_Key
pd.merge(df2, df1[['Type', 'Source', 'Year', 'G_ID']],
how='left',
left_on=['Year', 'Fuzzy_Key'],
right_on=['Year', 'G_ID'])
输出
Name Unit_ID Year Fuzzy_Key Type Source G_ID
0 Washington WTG-1 2002 WTG1 Normal Lin WTG1
1 Washington 1 2001 11 NaN NaN NaN
2 Washington 4 2003 4 NaN NaN NaN
3 Eddie GT02 2010 GT2 NaN NaN NaN
4 Mann 1 2018 11 NaN NaN NaN
5 Mann 2 2001 2 NaN NaN NaN
6 Mann SI1 2017 SI-01 Old Lin SI-01
7 Mann JO 2000 NaN NaN NaN
重要说明
它与键 (1 & 2001) 和 (1 & 2018) 不匹配,因为在创建 Fuzzy_Key
列时,它接近匹配到 11
而不是 1
正如您在第一个输出中看到的那样。我不明白为什么会发生这种情况,否则第 1 行和第 4 行也会有匹配项。
希望这是解决您问题的开始。 祝你好运!
关于python - 基于Python中列的部分匹配匹配和合并2个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54172863/