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

Bokeh回调中Pandas rolling函数报window必须为整数错误求助

解决Bokeh回调中Pandas Rolling操作的ValueError问题

你遇到的ValueError('window must be an integer',)错误,核心原因有两个:

1. DataFrame未设置Datetime索引

当你使用时间偏移格式的窗口(比如'1D'表示1天)调用rolling()时,Pandas要求DataFrame的索引必须是DatetimeIndex类型。但从你打印的DataFrame输出来看,time只是普通列而非索引,Pandas无法识别'0D'/'1D'这类时间窗口参数,会将其视为无效的非整数输入,从而抛出错误。

2. 滚动平均后的索引处理问题

即使修复了索引,滚动平均后的结果会保留Datetime索引,但Bokeh的ColumnDataSource需要将索引转回普通列才能正常渲染,否则会丢失时间字段。


修正后的回调代码

以下是修复后的完整回调函数,同时处理了索引转换、空值填充等细节:

def callback(attr, old, new):
    # 从source加载数据并转为DataFrame
    df = pd.DataFrame.from_dict(source.data.copy())
    
    # 关键步骤:将time列转为datetime并设置为索引
    df['time'] = pd.to_datetime(df['time'])
    df.set_index('time', inplace=True)
    print(df[:10])
    
    if new == 0:
        # 当滑动条为0时,直接返回原始数据,需将索引转回列
        data = df.reset_index()
    else:
        # 使用时间窗口计算滚动平均,同时处理空值(避免开头无数据的情况)
        data = df.rolling(window=f'{new}D').mean().reset_index()
        # 用前向填充补全空值,可根据需求替换为bfill或固定值
        data.fillna(method='ffill', inplace=True)
    
    # 更新ColumnDataSource的数据
    source.data = ColumnDataSource(data=data).data

额外注意事项

  • 确保定期获取新数据时,新数据的time字段也是标准的datetime格式,否则后续回调处理仍会出错。
  • 如果你的时间间隔是固定的(比如30分钟),也可以用整数窗口(比如new*48,因为1天有48个30分钟间隔),这样不需要依赖Datetime索引,但时间窗口的灵活性会降低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:40:29