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

如何在pandas时序图中为缺失观测值添加间隙显示

时间序列补全日期范围绘图方案

你已经完成日期字段的时间戳转换,接下来只需要通过重索引补全完整日期序列,再根据你要的间隙/水平线段效果做对应处理即可,以下是可直接复用的实现:

  • 第一步:补全连续日期索引
    先将日期列设为DataFrame索引,用pd.date_range生成从首条数据到末条数据的连续时间序列,通过reindex补全所有缺失日期,缺失日期对应的观测值会自动赋值为NaN:
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # 替换为你自己的列名即可
    df = df.set_index("date_col")
    # freq参数根据你的时间粒度调整:日级是D、小时级是H、周级是W
    full_dates = pd.date_range(start=df.index.min(), end=df.index.max(), freq="D")
    df_full = df.reindex(full_dates)
    

效果1:无观测值位置显示断带间隙

Matplotlib对连续时间轴上的NaN值默认会断开绘图线条,直接用补全后的DataFrame绘图就能自动生成间隙,不需要额外处理:

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(df_full.index, df_full["value_col"])
ax.tick_params(axis="x", rotation=45)
plt.tight_layout()
plt.show()

如果绘图没有出现预期间隙,先检查是否在绘图前误调用了填充空值的方法,或升级pandas、matplotlib到较新版本。

效果2:无观测值位置显示水平线段

需要水平延伸上一个观测值到下一个新观测点的话,对补全后的空值做前向填充即可:

# 用上一个非空观测值填充缺失日期的数值
df_fill = df_full.ffill()

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(df_fill.index, df_fill["value_col"], label="连续序列")
# 可选:叠加原始观测点的散点标记,区分真实值和填充段
ax.scatter(df.index, df["value_col"], c="crimson", s=20, label="原始观测值")
ax.legend()
ax.tick_params(axis="x", rotation=45)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:12:22