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

绘制美国银行股票滚动平均图时遇非单调DatetimeIndex切片报错求助

解决非单调DatetimeIndex的时间切片错误

错误原因

触发的Value based partial slicing on non-monotonic DatetimeIndexes with non-existing keys is not allowed错误,本质是两点:

  1. 你的DataFrame的DatetimeIndex不是单调递增/递减的
  2. 切片范围里可能存在不存在的日期键,导致loc无法正常解析时间范围

修复步骤

  • 第一步:检查并修复索引单调性
    先确认索引是否单调:

    print(BAC.index.is_monotonic_increasing)
    

    如果返回False,对索引重新排序:

    BAC = BAC.sort_index()
    
  • 第二步:安全筛选日期范围
    避免直接用loc['起始日期':'结束日期']的方式,改用布尔索引筛选更稳妥:

    date_mask = (BAC.index >= '2009-01-01') & (BAC.index <= '2010-01-01')
    bac_close_filtered = BAC['Close'][date_mask]
    

修改后的完整代码

import matplotlib.pyplot as plt

# 确保索引是单调递增的DatetimeIndex
BAC = BAC.sort_index()

# 筛选2009年1月1日到2010年1月1日的收盘价数据
date_mask = (BAC.index >= '2009-01-01') & (BAC.index <= '2010-01-01')
bac_close_filtered = BAC['Close'][date_mask]

plt.figure(figsize=(12,6))
# 绘制30日滚动平均线
bac_close_filtered.rolling(window=30).mean().plot(label='30 Day Avg')
# 绘制原始收盘价曲线
bac_close_filtered.plot(label='BAC CLOSE')
plt.legend()
plt.show()

额外说明

如果你的日期索引格式不规范,建议先用pd.to_datetime统一转换:

BAC.index = pd.to_datetime(BAC.index)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:02:43