You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定列分组,统计DataFrame对应列中列表元素的出现次数

解决代码与实现说明

直接用pandas的拆分、行展开、分组计数、宽表转换四个步骤即可实现需求,完整可运行代码如下:

import pandas as pd

# 构造示例数据,替换成你自己的实际数据即可
df = pd.DataFrame({
    'words': ['cat, dog, dog', 'cat, cat, mouse', 'mouse, cat, dog, elephant', 'elephant, elephant'],
    'category': [1, 1, 2, 3]
})

# 拆分单词并展开为单行单个单词
df_explode = df.assign(word=df['words'].str.split(',\s*')).explode('word')
# 按单词和分类统计次数,转换为宽表格式
res = df_explode.groupby(['word', 'category']).size().unstack(fill_value=0).reset_index().rename_axis(columns=None)

运行后输出的res完全符合你给出的期望结果格式。


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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:27:05