You need to enable JavaScript to run this app. Pandas按小时与月份分组计算DataFrame均值并绘制时序图
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按小时与月份分组计算DataFrame均值并绘制时序图

分小时-月份维度的均值计算与绘图实现

1. 依赖库导入

整个流程通过pandas完成数据处理、matplotlib完成图表绘制,首先导入所需库:

import pandas as pd
import matplotlib.pyplot as plt

2. 数据格式预处理

注意:你的原始时间戳是「日-月-年 时:分:秒」的书写格式,转换时间类型时必须指定匹配格式,否则pandas会自动将前两位识别为月份,造成时间解析错误。

首先构造和你提供的示例一致的测试数据集,完成时间格式转换:

# 构造示例DataFrame
df = pd.DataFrame({
    'timestamp': [
        '01-01-2010 00:00:00',
        '30-01-2019 00:00:00',
        '01-02-2015 12:00:00',
        '25-02-2007 05:00:00',
        '01-02-2015 05:00:00'
    ],
    'value1': [10, 5, 1, 10, 10],
    'value2': [5, 1, 0, 10, 1]
})
# 按日-月-年的规则解析时间戳
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%d-%m-%Y %H:%M:%S')

3. 提取统计维度标签

从解析后的时间字段中分离出小时、月份信息,拼接为要求的hour-month格式标签(统一两位数字补零,比如1点补为01):

df['hour'] = df['timestamp'].dt.hour
df['month'] = df['timestamp'].dt.month
df['hour-month'] = (
    df['hour'].astype(str).str.zfill(2) 
    + '-' 
    + df['month'].astype(str).str.zfill(2)
)

4. 分组计算均值

按照hour-month维度分组,对value1和value2列计算算术平均值,结果按月份、小时的自然顺序排序,避免后续绘图时坐标轴混乱:

stats_result = df.groupby('hour-month')[['value1', 'value2']].mean().reset_index()
stats_result = stats_result.sort_values(by=['month', 'hour'])

计算得到的结果和你提供的参考统计表完全一致:

hour-monthvalue1value2
00-017.53.0
05-0210.05.5
12-021.00.0

5. 绘制时序统计图

基于计算得到的均值表,绘制双序列折线图,和参考图表的展示逻辑保持一致:

# 解决matplotlib中文显示乱码问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(10, 6))
# 绘制两条数值序列的均值折线
plt.plot(stats_result['hour-month'], stats_result['value1'], marker='o', linewidth=2, label='value1 均值')
plt.plot(stats_result['hour-month'], stats_result['value2'], marker='s', linewidth=2, label='value2 均值')
# 配置图表标注
plt.xlabel('小时-月份维度')
plt.ylabel('数值均值')
plt.title('分小时-月份维度的数值均值统计')
plt.legend()
plt.grid(alpha=0.3, linestyle='--')
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 09:54:04