如何在DataFrame中按日期计算词频并实现时间维度词频可视化
按日期维度汇总每日词频并生成可视化的实现方法
基础数据对齐
默认使用的DataFrame列名映射(可根据实际列名替换):
publish_date:对应格式为7_23_2020的tweet发布日期列tokenized_words:对应单条tweet分词后得到的token集合/列表列
所有实现基于pandas、标准库Counter、matplotlib、seaborn完成,无外部跳转链接。
分步操作流程
1. 日期格式标准化与目标区间筛选
字符串格式的日期直接排序会出现逻辑错误(例如7_2_2020会被排在7_23_2020之前),必须先转成标准datetime格式再做筛选和分组:
import pandas as pd from collections import Counter import matplotlib.pyplot as plt import seaborn as sns # 字符串日期转datetime对象,对齐格式 df['publish_date'] = pd.to_datetime(df['publish_date'], format='%m_%d_%Y') # 筛选7_23_2020至7_30_2020的目标数据子集 target_subset = df[ (df['publish_date'] >= '2020-07-23') & (df['publish_date'] <= '2020-07-30') ].copy()
如果你的日期是其他分段顺序(例如日_月_年),直接调整
pd.to_datetime中的format参数即可。
2. 计算全目标区间的Top10高频词
汇总区间内所有tweet的token,统计全局词频,选出后续需要追踪的高频目标词:
# 逐行汇总区间内所有token full_range_tokens = [] for token_list in target_subset['tokenized_words']: full_range_tokens.extend(token_list) # 取全局词频排名前10的词 word_total_counter = Counter(full_range_tokens) top10_target_words = [word for word, freq in word_total_counter.most_common(10)]
3. 按日期拆分统计Top10词的每日出现频次
逐天聚合数据,生成长表结构的统计结果,方便后续绘图:
daily_freq_records = [] # 按发布日期分组遍历 for day, day_group in target_subset.groupby('publish_date'): # 汇总当日所有tweet的token day_tokens = [] for token_list in day_group['tokenized_words']: day_tokens.extend(token_list) day_counter = Counter(day_tokens) # 仅统计Top10目标词的当日出现次数,其余词直接跳过 for word in top10_target_words: daily_freq_records.append({ 'date': day, 'word': word, 'daily_freq': day_counter.get(word, 0) }) # 转成结构化DataFrame daily_freq_table = pd.DataFrame(daily_freq_records)
4. 生成每日词频变化可视化
用多折线图展示每个Top10词在区间内的使用频次变化,直观呈现趋势:
# 设置绘图基础样式 sns.set_theme(style="whitegrid") plt.figure(figsize=(12, 6)) # 绘制折线图,每个数据点加标记方便定位数值 sns.lineplot( data=daily_freq_table, x='date', y='daily_freq', hue='word', marker='o' ) # 调整图表标注避免重叠/截断 plt.xticks(rotation=45) plt.title('2020年7月23日-7月30日 Top10高频词每日使用频次变化') plt.xlabel('发布日期') plt.ylabel('当日总出现次数') plt.tight_layout() plt.show()
拓展说明
这套流程输出的中间统计结果(每日总词数、单个词的每日出现次数、区间全局总词数),可以直接作为后续PMI计算的输入参数,不需要重复执行分词、汇总等重复操作。
内容的提问来源于stack exchange,提问作者Alex Gonzalez
相关产品推荐
相关产品推荐

