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

标签 python pandas pandas-groupby

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

相关文章:

python - {m,n} 不匹配 m 以下但匹配 n 以上。为什么?

python - 计算多个 pandas 列中出现的次数

Pandas 按时间和 ID 分组并聚合

python - Tkinter/ttk - TreeView 不占据全帧

python - 使用 Spyder IDE,如何从 "goto definition"返回?

python - 使用 Pandas 创建分布不均的事件

python - 使用合并单元格 reshape Dataframe pandas

python - 返回 pandas df 中值的运行计数

python - pandas groupby 基于唯一值扩展 df

python - 我应该将 Unix 时间存储在单独的表中吗