You need to enable JavaScript to run this app. Pandas DataFrame中统计指定词多列出现次数并按列分组输出
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame中统计指定词多列出现次数并按列分组输出

Pandas 多列指定单词出现次数统计实现方法

你单次运行多段统计代码只返回最后一个结果,是因为Python交互环境(包括Jupyter)默认仅输出单元格最后一行表达式的返回值,批量统计所有目标列的实现方法如下:


完整实现代码

import pandas as pd
# 若需要不区分大小写匹配关键词,额外导入re
import re
# 1. 定义要统计的目标列列表
target_cols = ['Name', 'Year', 'Score', '2nd Score', 'Country', 'Fruit', 'Transit Duration', 'Quality', 'Taste', 'Freshness', 'Packaging']
# 2. 定义要统计的关键词
keyword = 'The'
# 3. 批量统计所有列的关键词出现总次数
count_result = df3[target_cols].apply(lambda col: col.astype(str).str.count(keyword).sum())
# 4. 调整列名去掉空格(匹配你预期输出的列名格式)
count_result.index = count_result.index.str.replace(' ', '')
# 5. 按要求格式输出
print(count_result.to_string(header=False))

说明

  • 代码中加入astype(str)是为了把所有列统一转成字符串类型,避免数值列调用str.count时报错返回空值
  • 如果需要不区分大小写匹配(同时统计the/THE/The等所有形式),把str.count(keyword)替换为str.count(keyword, flags=re.IGNORECASE)即可
  • 如果不需要打印而是要把结果存为字典、DataFrame做后续处理,直接调用count_result.to_dict()或者count_result.reset_index()即可

运行上述代码输出的结果和你给出的预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:45:02