Way*_*pth 6 python fuzzy matrix pandas
我有一个带有x个字符串名称及其相关ID的文件。本质上是两列数据。
我想要的是一个关联样式表,其格式为x乘x(将有问题的数据同时作为x轴和y轴),但是我希望使用Fuzzywuzzy库的函数fuzz.ratio(x ,y)作为输出,使用字符串名称作为输入。本质上是针对每个条目运行每个条目。
这就是我的想法。只是为了表明我的意图:
import pandas as pd
from fuzzywuzzy import fuzz
df = pd.read_csv('random_data_file.csv')
df = df[['ID','String']]
df['String_Dup'] = df['String'] #creating duplicate of data in question
df = df.set_index('ID')
df = df.groupby('ID')[['String','String_Dup']].apply(fuzz.ratio())
Run Code Online (Sandbox Code Playgroud)
但是显然,这种方法目前不适用于我。任何帮助表示赞赏。不必是熊猫,这只是我相对熟悉的环境。
我希望我的问题字眼清楚,而且真的很感谢任何意见,
使用 pandas 的crosstab函数,然后按列apply计算模糊。这比我的第一个答案要优雅得多。
import pandas as pd
from fuzzywuzzy import fuzz
# Create sample data frame.
df = pd.DataFrame([(1, 'abracadabra'), (2,'abc'), (3,'cadra'), (4, 'brabra')],
columns=['id', 'strings'])
# Create the cartesian product between the strings column with itself.
ct = pd.crosstab(df['strings'], df['strings'])
# Note: for pandas versions <0.22, the two series must have different names.
# In case you observe a "Level XX not found" error, the following may help:
# ct = pd.crosstab(df['strings'].rename(), df['strings'].rename())
# Apply the fuzz (column-wise). Argument col has type pd.Series.
ct = ct.apply(lambda col: [fuzz.ratio(col.name, x) for x in col.index])
# This results in the following:
# strings abc abracadabra brabra cadra
# strings
# abc 100 43 44 25
# abracadabra 43 100 71 62
# brabra 44 71 100 55
# cadra 25 62 55 100
Run Code Online (Sandbox Code Playgroud)
为简单起见,我省略了groupby您问题中建议的操作。如果需要在组上应用模糊字符串匹配,只需创建一个单独的函数:
def cross_fuzz(df):
ct = pd.crosstab(df['strings'], df['strings'])
ct = ct.apply(lambda col: [fuzz.ratio(col.name, x) for x in col.index])
return ct
df.groupby('id').apply(cross_fuzz)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
425 次 |
| 最近记录: |