基于含字符串时间戳的DataFrame绘制分年度各月事件发生次数统计图
实现步骤
1. 日期格式转换
首先把Date列从字符串转为pandas内置的datetime格式,同时提取后续统计需要的年份、月份字段:
import pandas as pd import matplotlib.pyplot as plt # 假设你的DataFrame名为df # 原日期为日/月/年格式,需指定dayfirst=True避免日月解析颠倒 df['Date'] = pd.to_datetime(df['Date'], dayfirst=True) # 提取统计需要的维度字段 df['year'] = df['Date'].dt.year df['month'] = df['Date'].dt.month df['month_name'] = df['Date'].dt.month_name() # 可选,X轴显示月份名称更直观
2. 按年月聚合统计事件量
按年份+月份分组统计记录数,即为对应月份的事件发生量:
# 统计所有事件(Cold为Yes/No都计入) monthly_count = df.groupby(['year', 'month', 'month_name'], as_index=False).size() # 如果你只需要统计Cold为Yes的事件,换成下面的写法即可 # monthly_count = df[df['Cold'] == 'Yes'].groupby(['year', 'month', 'month_name'], as_index=False).size()
3. 绘制分年多子图
根据数据中的年份数量动态生成子图,每个子图对应一年的各月统计数据:
# 获取所有去重排序后的年份 years = sorted(monthly_count['year'].unique()) n_years = len(years) # 子图布局:默认1行排列,年份较多时可以换成2行布局 nrows=(n_years+1)//2, ncols=2 fig, axes = plt.subplots(nrows=1, ncols=n_years, figsize=(6*n_years, 4), sharey=True) # 单年份时axes不是数组,统一格式方便后续遍历 if n_years == 1: axes = [axes] for idx, year in enumerate(years): ax = axes[idx] # 筛选当前年份数据,按月份排序 year_data = monthly_count[monthly_count['year'] == year].sort_values('month') # 绘制柱状图 ax.bar(year_data['month_name'], year_data['size']) # 设置子图样式 ax.set_title(f'{year}年各月事件数量') ax.set_xlabel('月份') # 旋转X轴标签避免重叠 plt.setp(ax.get_xticklabels(), rotation=45, ha='right') axes[0].set_ylabel('事件数量') # 自动调整布局避免标签被截断 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者teller.py3
相关产品推荐
相关产品推荐

