我正在尝试通过 PySpark 对某些数据执行一些模糊匹配。为此,我使用了
fuzzywuzzy
包并在Databricks上运行它。
我的数据集非常简单。它存储在 CSV 文件中,包含两列:Name1 和 Name2。但是,我不只是想比较同一行中的两个值,而是想将每个 Name1 与所有可用的 Name2 值进行比较。
这就是我的代码的样子,
from pyspark.sql import functions as f
from fuzzywuzzy import fuzz
from pyspark.sql.types import StringType
# create a simple function that performs fuzzy matching on two strings
def match_string(s1, s2):
return fuzz.token_sort_ratio(s1, s2)
# convert the function into a UDF
MatchUDF = f.udf(match_string, StringType())
# separate the two Name columns into individual DataFrames
df1 = raw_df.select('Name1')
df2 = raw_df.select('Name2')
# perform a CROSS JOIN on the two DataFrames
# CAN THIS BE AVOIDED?
df = df1.crossJoin(df2)
# use the UDF from before to calculate a similarity score for each combination
df = df.withColumn("similarity_score", MatchUDF(f.col("Name1"), f.col("Name2")))
一旦我有了相似度分数,我就可以计算每个名字的排名,从而获得最佳匹配。
我担心的是CROSS JOIN。这成倍地增加了我拥有的数据点的数量。无论如何,这可以避免吗?
我也对完全不同的方法持开放态度,这些方法将以更优化的方式完成我需要做的事情。