我对python很新。我想问一下,如果有任何方法可以将文本数据框列表与文本数据框列表进行匹配呢? (如果我错误地提出这个问题,请编辑这个问题)
例如我有这些数据:
df1 =
id Names
0 123 Simpson J.
1 456 Snoop Dogg
df2 =
Names
0 John Simpson
1 Snoop Dogg
2 S. Dogg
3 Mr Dogg
有没有一种方法可以找到,可能使用findall
或match
或任何python库,这样我就可以生成出具有id的名称多少次,这几乎就像这样结果:< / p>
result =
id Names_appeared
0 123 1
1 456 3
简短的解释和一些网址可能会帮助我更多地了解它。提前谢谢。
答案 0 :(得分:1)
以下是IanS建议使用fuzzywuzzy的示例:
import pandas as pd
from fuzzywuzzy import fuzz
def fuzz_count(shortList, longList, minScore):
""" Count fuzz ratios greater than or equal to a minimum score. """
results = []
for s in shortList:
scores = [fuzz.ratio(s, l) for l in longList]
count = sum(x >= minScore for x in scores)
results.append(count)
return results
data1 = {'id': pd.Series([123, 456]),
'Names': pd.Series(['Simpson J.', 'Snoop Dogg'])}
data2 = {'Names': pd.Series(['John Simpson', 'Snoop Dogg', 'S. Dogg', 'Mr Dogg'])}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
result = pd.DataFrame()
result['id'] = df1['id']
counts = fuzz_count(df1['Names'], df2['Names'], minScore=60) # [1, 2]
result['Names_appeared'] = counts
print(result) # id Names_appeared
# 0 123 1
# 1 456 2