您可以使用fuzzywuzzy 来查找值的相似性。例如,使用fuzz.ratio(str1, str2) 将返回一个指示字符串有多相似的指示符。还有其他方法。您必须自己找出最适合您的用例的方法。
下面的例子使用fuzz.ratio(str1, str2),并认为80的比率是相等的:
# pip install fuzzywuzzy python-levenshtein
# or: conda install -c conda-forge fuzzywuzzy python-levenshtein
import io
import pandas as pd
from fuzzywuzzy import fuzz
df1 = pd.read_csv(io.StringIO("""
Product Name, Cost
Car with batteries, 2
Headphones Sony, 3
"""))
df2 = pd.read_csv(io.StringIO("""
Product Name, Cost
Car batteries, 2
Headphones Sony, 3
"""))
COLUMN_NAME = "Product Name"
ACCEPTED_RATIO = 80
def match(right, left):
return fuzz.ratio(right, left) > ACCEPTED_RATIO
rsuffix = "_r"
compared = df1.join(df2, rsuffix=rsuffix)
compared["Matches"] = compared.apply(
lambda x: match(x[COLUMN_NAME], x[f"{COLUMN_NAME}{rsuffix}"]),
axis=1,
)
compared = compared.drop(
[c for c in compared.columns if c.endswith(rsuffix)],
axis=1
)
print(compared) 的输出将是:
Product Name Cost Matches
0 Car with batteries 2 True
1 Headphones Sony 3 True