python - 创建具有相似性索引值的列
问题描述
如何创建分别显示每行相似度索引的列?
这段代码
def func(name):
matches = try_test.apply(lambda row: (fuzz.partial_ratio(row['name'], name) >= 85), axis=1)
return [try_test.word[i] for i, x in enumerate(matches) if x]
try_test.apply(lambda row: func(row['name']), axis=1)
返回与条件匹配的索引>=85
。但是,我也有兴趣通过将每个字段与所有其他字段进行比较来获得这些值。
数据集是
try_test = pd.DataFrame({'word': ['apple', 'orange', 'diet', 'energy', 'fire', 'cake'],
'name': ['dog', 'cat', 'mad cat', 'good dog', 'bad dog', 'chicken']})
非常感谢您的帮助。
预期输出(数值只是一个例子)
word name sim_index1 sim_index2 sim_index3 ...index 6
apple dog 100 0
orange cat 100
... mad cat 0.6 100
在对角线上有一个值为 100,因为我正在比较狗和狗,......如果你认为它会更好,我可能还会考虑另一种方法。
解决方案
IIUC,你可以稍微改变你的功能来得到你想要的:
def func(name):
return try_test.apply(lambda row: (fuzz.partial_ratio(row['name'], name)), axis=1)
print(try_test.apply(lambda row: func(row['name']), axis=1))
0 1 2 3 4 5
0 100 0 33 100 100 0
1 0 100 100 0 33 33
2 33 100 100 29 43 14
3 100 0 29 100 71 0
4 100 33 43 71 100 0
5 0 33 14 0 0 100
也就是说,不需要超过一半的计算,因为结果是对称矩阵,对角线为 100。因此,如果您的数据更大,那么您可以partial_ratio
使用当前行之前的行。添加 soreindex
然后使用T
(transpose) 和创建完整矩阵np.diag
,您可以执行以下操作:
def func_pr (row):
return (try_test.loc[:row.name-1, 'name']
.apply(lambda name: fuzz.partial_ratio(name, row['name'])))
#start at index 1 (second row)
pr = (try_test.loc[1:].apply(func_pr, axis=1)
.reindex(index=try_test.index,
columns=try_test.index)
.fillna(0)
.add_prefix('sim_idx')
)
#complete the result with transpose and diag
pr += pr.to_numpy().T + np.diag(np.ones(pr.shape[0]))*100
# concat
res = pd.concat([try_test, pr.astype(int)], axis=1)
你得到
print(res)
word name sim_idx0 sim_idx1 sim_idx2 sim_idx3 sim_idx4 \
0 apple dog 100 0 33 100 100
1 orange cat 0 100 100 0 33
2 diet mad cat 33 100 100 29 43
3 energy good dog 100 0 29 100 71
4 fire bad dog 100 33 43 71 100
5 cake chicken 0 33 14 0 0
sim_idx5
0 0
1 33
2 14
3 0
4 0
5 100
推荐阅读
- spring - 为什么以及何时应该在 Spring 事务隔离级别中使用 READ UNCOMMITTED 隔离级别
- node.js - 从两个设备同时点击注册会创建两个用户
- html - 在 Bootstrap Material 设计中,我的下拉菜单会自行切换并闪烁错误
- css - 以 vuetify 形式减小高度和行距
- azure - .net core 3.1 证书身份验证在 Azure 上部署时返回 403
- python - 使用熊猫逗号与分号分隔的csv文件
- python - pyplot mudole的show()函数发生UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb7 in position 0: invalid start byte
- mysql - 喜欢和总喜欢的数据库设计
- javascript - 无法理解为什么以下 JavaScript 函数不起作用
- angular - Html 画布不适合使用 html2pdf 库的 pdf 页面