【问题标题】:merge 2 dataframes based on partial string-match between columns基于列之间的部分字符串匹配合并 2 个数据帧
【发布时间】:2021-08-22 11:16:06
【问题描述】:

我有两个数据框df1和df2如下图:

Df1:

                  movie    correct_id
0              birdman        N/A
1     avengers: endgame        N/A
2              deadpool        N/A
3  once upon deadpool        N/A

Df2:参考数据框

          movie              correct_id
0               birdmans          4
1  The avengers: endgame          2
2               The King          3
3   once upon a deadpool          1

预期结果:

            movie    correct_id
0              birdman        4
1     avengers: endgame       2
2             deadpool       N/A
3   once upon deadpool        1

请问如何根据部分字符串匹配合并两个数据框?

注意:电影名称不完全相同

【问题讨论】:

  • 首先您需要精确定义您认为的部分字符串匹配。国王怎么了?
  • 我认为是参考的df2,参考中不存在国王。我的意思是电影的名字不完全一样。 exp 'The avengers:endgame' 在 ref (df2) 但在 df1 中是 'avengers:endgame'
  • 查看fuzzywuzzyrapidfuzz 以计算字符串距离,并为df1 中的每个键输入df2 以最小化列文斯坦距离

标签: python pandas dataframe


【解决方案1】:

来自previous post

输入数据:

>>> df1
                movie  correct_id
0             birdman         NaN
1   avengers: endgame         NaN
2            deadpool         NaN
3  once upon deadpool         NaN

>>> df2
                   movie  correct_id
0               birdmans           4
1  The avengers: endgame           2
2               The King           3
3   once upon a deadpool           1

有点模糊逻辑:

from fuzzywuzzy import process

dfm = pd.DataFrame(df1["movie"].apply(lambda x: process.extractOne(x, df2["movie"]))
                               .tolist(), columns=["movie", "ratio", "best_id"])
>>> dfm
                            movie  ratio  best_id
0                        birdmans     93        0
1  The avengers: endgame: endgame     90        1
2            once upon a deadpool     90        3
3            once upon a deadpool     95        3

dfm 的索引是df1 的索引,而不是best_id 列是df2 的索引。现在你可以更新你的第一个数据框了:

THRESHOLD = 90  # adjust this number

ids = dfm.loc[dfm["ratio"] > THRESHOLD, "best_id"]
df1["correct_id"] = df2.loc[ids, "correct_id"].astype("Int64")
>>> df1
                movie  correct_id
0             birdman           4
1   avengers: endgame           2
2            deadpool        <NA>
3  once upon deadpool           1

【讨论】:

  • 不,不可能,这不是好的结果。请检查我的更新答案。
  • 其实第一个对我来说效果很好,但是当我尝试更新的答案时,我得到了一个错误 TypeError: object cannot be convert to an IntegerDtype
  • 删除 astype("Int64") 并查看结果。你的 Pandas 版本是什么?
  • 你为什么删除了你的投票而不接受我的回答???
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 2021-01-29
  • 2020-10-15
  • 2021-01-16
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
相关资源
最近更新 更多