You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Pandas技术实现:生成DataFrame中关键短语的频率分布及跨类别占比统计

解决Pandas关键短语频率分析与新增列需求

嘿,这问题我熟!先直接给你结论:从频率字典入手确实是高效的方案,因为它能快速统计全局短语出现次数,后续的类别分布和占比计算都能基于这个基础数据展开,避免重复遍历DataFrame,节省时间。下面我一步步给你拆解实现方法:

1. 构建全局关键短语频率字典

首先我们需要把Key Phrases列的列表拆分成单独行,再统计每个短语的总出现次数,这一步用Pandas的explode()方法就能轻松搞定:

import pandas as pd

# 先定义你给的示例数据
data = {
    'Sentence': ['the red ball', 'a big blue box', 'he throws the red ball'],
    'Key Phrases': [['red ball'], ['blue'], ['he throws','red ball']],
    'Category': ['object', 'object', 'action']
}
df = pd.DataFrame(data)

# 构建全局频率字典
phrase_counts = df['Key Phrases'].explode().value_counts().to_dict()
# 输出结果: {'red ball': 2, 'blue': 1, 'he throws': 1}

2. 计算关键短语的跨类别频率分布

接下来我们要统计每个短语在不同类别里的出现占比,这里可以先通过groupby统计每个短语在各个类别的出现次数,再用除法计算占比:

# 统计每个短语在各分类的出现次数
phrase_category_counts = df.explode('Key Phrases').groupby(['Key Phrases', 'Category']).size().unstack(fill_value=0)

# 计算每个短语在各类别的占比(转成百分比)
phrase_category_distribution = phrase_category_counts.div(phrase_category_counts.sum(axis=1), axis=0) * 100

# 输出的分布表示例:
#             action  object
# Key Phrases               
# blue           0.0   100.0
# he throws    100.0     0.0
# red ball      50.0    50.0

3. 新增Key Phrase Occurrences

我们写一个自定义函数,遍历每行的关键短语和所属类别,查询对应的占比并格式化成要求的字符串,再用apply()方法批量生成新列:

# 定义生成新列内容的函数
def get_phrase_occurrences(row):
    phrases = row['Key Phrases']
    category = row['Category']
    result_parts = []
    for phrase in phrases:
        # 获取当前短语在该类别的占比,转成整数百分比
        percentage = phrase_category_distribution.loc[phrase, category]
        result_parts.append(f"{phrase}: {int(percentage)}%")
    return ', '.join(result_parts)

# 新增列
df['Key Phrase Occurrences'] = df.apply(get_phrase_occurrences, axis=1)

# 最终生成的DataFrame就和你给出的示例完全一致啦!

4. 构建以Category为键的短语占比字典

最后我们把之前的分布表转换成你需要的字典结构,以类别为键,值是该类别下所有短语及其占比的字典:

category_phrase_dict = {}
for category in phrase_category_distribution.columns:
    # 筛选该类别下有出现的短语,转成指定格式的字典
    category_phrases = phrase_category_distribution[category][phrase_category_distribution[category] > 0].apply(lambda x: f"{int(x)}%").to_dict()
    category_phrase_dict[category] = category_phrases

# 输出结果:
# {
#     'action': {'he throws': '100%', 'red ball': '50%'},
#     'object': {'blue': '100%', 'red ball': '50%'}
# }

内容的提问来源于stack exchange,提问作者MightyTreeFrog

火山引擎 最新活动