gpt4 book ai didi

python - 如何在python中对具有相似文本的数据框进行分组

转载 作者:行者123 更新时间:2023-12-05 01:30:17 25 4
gpt4 key购买 nike

我有一个这样的数据框 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]})

enter image description here

我需要按代码和描述对其进行分组。按代码分组很简单:

GR = DF.groupby('Code')

enter image description here

现在我想继续按描述分组,因此所有相同或相似(具有公共(public)部分)的值都被分组在一起。你能帮我用一个公式来得到这样的东西吗:

enter image description here

可能有两个问题:“相等值”和“相似值”。如果至少有关于“相等值”的任何提示,那就太好了。

最佳答案

要检查相似的字符串,您可以使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com