Using fuzzywuzzy to create a column of matched results in the data frame

感情迁移 提交于 2019-12-04 15:41:15

It's not a good idea to store lists in DataFrame, I suggest store every match as a row in DataFrame. Here is the code:

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

import pandas as pd
import io

master = pd.read_csv(io.StringIO("""ID,ITEM
1,Pepperoni Pizza
2,Cheese Pizza
3,Chicken Salad
4,Plain Salad"""))

lookups = ["Cheese", "Salad"]

choices = master.set_index("ID").ITEM.to_dict()

res = [(lookup,) + item for lookup in lookups for item in process.extract(lookup, choices,limit=2)]
df = pd.DataFrame(res, columns=["lookup", "matched", "score", "id"])
df

output:

   lookup        matched  score  id
0  Cheese   Cheese Pizza     90   2
1  Cheese  Chicken Salad     45   3
2   Salad  Chicken Salad     90   3
3   Salad    Plain Salad     90   4

Basically, I create a choices dict from master for match and then for loop the lookups and store the result as a list. And convert the list to DataFrame finally.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!