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

如何绘制动态滚动均值图?基于时间序列的C列滚动均值可视化方法

实现方案

以下是基于Python的可运行实现,直接适配你给出的数据源和需求:

1. 依赖库

需要提前安装pandas和matplotlib两个库:

pip install pandas matplotlib

2. 完整代码

import pandas as pd
import matplotlib.pyplot as plt

# 构造数据源,也可以替换为从csv/数据库读入你的全量数据
data = {
    "A": ["2021-10-19 10:47:18", "2021-10-19 10:47:21", "2021-10-19 10:47:25", "2021-10-19 10:47:27", "2021-10-19 10:47:28"],
    "B": ["2021-10-19 10:47:20", "2021-10-19 10:47:22", "2021-10-19 10:47:25", "2021-10-19 10:47:27", "2021-10-19 10:47:30"],
    "C": ["00:00:02", "00:00:01", "00:00:00", "00:00:00", "00:00:03"]
}
df = pd.DataFrame(data)

# 数据类型转换
df["B"] = pd.to_datetime(df["B"])
# 把C列时间差转为秒级数值
df["C_seconds"] = pd.to_timedelta(df["C"]).dt.total_seconds()
# 按B列时间排序(全量数据如果乱序要先执行这一步)
df = df.sort_values("B").set_index("B")

# 计算滚动均值
# 示例用扩展窗口(累加所有历史值计算均值),符合你给出的预期输出
df["rolling_mean"] = df["C_seconds"].expanding().mean()
# 如果要固定窗口(比如最近3条记录的均值),替换为以下代码:
# df["rolling_mean"] = df["C_seconds"].rolling(window=3, min_periods=1).mean()
# 如果要固定时间窗口(比如最近5分钟的均值),替换为以下代码:
# df["rolling_mean"] = df["C_seconds"].rolling(window="5T", min_periods=1).mean()

# 绘制秒级粒度滚动均值图
plt.figure(figsize=(10, 4))
plt.plot(df.index, df["rolling_mean"], marker='o', linewidth=2)
plt.xlabel("时间")
plt.ylabel("A-B时间差滚动均值(秒)")
plt.title("时间差滚动均值变化趋势")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 1小时粒度聚合统计
hourly_stats = df["C_seconds"].resample("1H").agg(["mean", "max", "min"])
# 绘制小时级均值图
plt.figure(figsize=(10, 4))
plt.plot(hourly_stats.index, hourly_stats["mean"], marker='s', color='#ff7f0e', linewidth=2)
plt.xlabel("时间(小时级)")
plt.ylabel("A-B时间差小时均值(秒)")
plt.title("1小时粒度时间差均值变化趋势")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

3. 输出说明

运行后你的示例数据对应滚动均值结果完全匹配预期:

  • 2021-10-19 10:47:20 对应均值为 2.0
  • 2021-10-19 10:47:22 对应均值为 1.5
  • 后续点依次为 1.0、0.75、1.2

如果需要调整统计粒度,修改resample的参数即可:比如10分钟粒度填'10T'、1天粒度填'1D'。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:15:03