作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个这样的数据框 DF:
DF = pd.DataFrame({'Code':['abc', 'abc', 'abc', 'abc', 'def'],
'Description':['ABC String', 'ABC String', 'ABC String and sth', 'Only sth else', 'ABC String'],
'Value':[10, 20, 30, 40, 100]})
我需要按代码和描述对其进行分组。按代码分组很简单:
GR = DF.groupby('Code')
现在我想继续按描述分组,因此所有相同或相似(具有公共(public)部分)的值都被分组在一起。你能帮我用一个公式来得到这样的东西吗:
可能有两个问题:“相等值”和“相似值”。如果至少有关于“相等值”的任何提示,那就太好了。
最佳答案
要检查相似的字符串,您可以使用 jellyfish.levenshtein_distance。想法是迭代每个组并从组中获取最频繁的元素,然后评估相对于最频繁元素的 levenshtein_distance。如果距离接近于 0,则表示给定的字符串相似,反之亦然。
# from difflib import SequenceMatcher
from statistics import mode
import jellyfish
import pandas as pd
df = pd.DataFrame({'Code': ['abc', 'abc', 'abc', 'abc', 'def'],
'Description': ['ABC String', 'abc string', 'ABC String and sth', 'Only sth else', 'ABC String'],
'Value': [10, 20, 30, 40, 100]})
df_list = []
for grp,df in df.groupby('Code'):
df['distance'] = df['Description'].apply(lambda x : jellyfish.levenshtein_distance(x, mode(df['Description'])))
df['Description'] = mode(df['Description'])
df_list.append(df[df['distance'] < 10])
df = pd.concat(df_list).drop('distance', axis=1)
print(df)
输出-
Code Description Value
0 abc ABC String 10
1 abc ABC String 20
2 abc ABC String 30
4 def ABC String 100
为了更好、更准确的分析 - 将字符串转换为小写,删除空格和标点符号,然后遵循算法。
关于python - 如何在python中对具有相似文本的数据框进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67240893/
我是一名优秀的程序员,十分优秀!