【发布时间】:2022-01-04 06:14:45
【问题描述】:
输入: df1:
Flow Order
Bananas
White Peach
White Nectarine
df2
Subcategory_Description Segment_Description Flow
POTATO POTATOES P/P PP Potato White 4kg
POTATO POTATOES P/P PP Potato White 1.5kg
POTATO POTATOES P/P PP Potato White 2kg
BANANA BANANAS OTHER (INC P/P) 5pk Kids Banana
STONE FRUIT PEACHES P/P PP Peach White
STONE FRUIT NECTARINES P/P PP Nectarine White
MANGOES KENSINGTON PRIDE Mango Kp
BANANA BANANAS CAVENDISH Banana
STONE FRUIT PEACHES LOOSE Peach White
STONE FRUIT NECTARINES LOOSE Nectarine
STONE FRUIT NECTARINES LOOSE Nectarine White
场景: 必须从 df2 中获取所有匹配流,以 df1 作为基本流。我已经使用 python 中的 Fuzzywuzzy 库来执行此操作,但这里的问题是它也在考虑部分匹配。例如,在 Flow 的预期输出 - 'White Peach' 中,此处考虑了 White Potato(这不应该发生)。
直到上述场景的 Python 代码如下:
import pandas as pd
from fuzzywuzzy import process
# converting to pandas dataframes
dframe1 = pd.DataFrame(df1['Flow Order'])
dframe2 = pd.DataFrame(df2['Flow'])
# empty lists for storing the matches later
mat1 = []
mat2 = []
p = []
# printing the pandas dataframes
print("First dataframe:\n", dframe1,
"\nSecond dataframe:\n", dframe2)
# converting dataframe column to list
# of elements
# to do fuzzy matching
list1 = dframe1['Flow Order'].tolist()
list2 = dframe2['Flow'].tolist()
# taking the threshold as 82
threshold = 82
# iterating through list1 to extract
# it's closest match from list2
for i in list1:
mat1.append(process.extract(i, list2, limit=5))
dframe1['matches'] = mat1
# iterating through the closest matches
# to filter out the maximum closest match
for j in dframe1['matches']:
for k in j:
if k[1] >= threshold:
p.append(k[0])
mat2.append(",".join(p))
p = []
# storing the resultant matches back to dframe1
dframe1['matches'] = mat2
print("\nDataFrame after Fuzzy matching:")
print("dframe1:", dframe1)
以上代码输出: dframe1
Flow Order matches
Bananas Banana,5pk Kids Banana
White Peach PP Peach White,Peach White,PP Potato White 4kg,PP Potato White 1.5kg,PP Potato White 2kg
White Nectarine PP Nectarine White,Nectarine White,Nectarine,PP Potato White 2kg,PP Potato White 1kg
因此,要包含在上述代码中的想法是考虑 df2 中的“Subcategory_Description”和“Segment_Description”,以单独获得完美匹配流。这两列可用于取出主要名称以使用 fuzzywuzzy 匹配字符串。但我不确定如何包含这些内容。
预期输出:
Flow Order matches
Bananas Banana,5pk Kids Banana
White Peach PP Peach White,Peach White
White Nectarine PP Nectarine White,Nectarine White,Nectarine
请帮帮我。提前致谢!
【问题讨论】:
标签: python python-3.x pandas string-matching fuzzywuzzy