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

如何使用Pandas DataFrame统计特定作者的目标词汇出现次数

Pandas统计特定作者文本中目标词汇的出现次数

原始数据

先构造示例DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Author': ['Jake', 'Mac', 'Sarah'],
    'Text': ['hey hey my names Jake', 'hey my names Mac', 'heymy names Sarah'],
    'Date': ['1.04.1997', '1.02.2019', '5.07.2001']
})

实现步骤

  1. 统计目标词汇出现次数
    使用str.count()结合正则表达式匹配完整单词,避免误匹配包含目标词汇的拼接词(比如示例中的"heymy"):
target_word = 'hey'
# 正则\b用于匹配单词边界,case=False忽略大小写(可选)
df['Count'] = df['Text'].str.count(r'\b' + target_word + r'\b', case=False)
  1. 筛选有效结果
    过滤掉次数为0的记录,只保留Author和Count列:
result = df[df['Count'] > 0][['Author', 'Count']].reset_index(drop=True)
  1. 查看结果
print(result)

输出结果:

Author  Count
0   Jake      2
1    Mac      1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:45:36