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

Pandas rolling的on参数无法使用MultiIndex层级的优化方法问询

问题:MultiIndex Series使用rolling指定索引层级报错

尝试在MultiIndex索引的Series上调用pandas的rolling函数,根据文档说明on参数可指定索引层级,但设置on="time"时触发错误:

ValueError: invalid on specified as time, must be a column (of DataFrame), an Index or None

测试数据初始化代码

import pandas as pd
idx = pd.MultiIndex.from_arrays([[1,2,3,4], pd.date_range(start="1-1-2023", end="1-4-2023")], names=["number", "time"])
ser = pd.Series(data=[1,2,3,4], index=idx)
print(ser)

输出:

number  time
1       2023-01-01    1
2       2023-01-02    2
3       2023-01-03    3
4       2023-01-04    4
dtype: int64

报错代码

out = ser.rolling("2D", on="time").mean()

现有解决方法

将time层级转为DataFrame列,计算后还原索引:

out = ser.reset_index("time").rolling("2D", on="time").mean()
out = out.set_index("time", append=True)
print(out)

输出:

number  time      
1       2023-01-01    1.0
2       2023-01-02    1.5
3       2023-01-03    2.5
4       2023-01-04    3.5
Name: 0, dtype: float64

请问是否有更简洁的实现方式?


回答

可以直接将on参数指定为MultiIndex中time层级的Index对象,无需来回转换索引与列:

out = ser.rolling("2D", on=ser.index.get_level_values("time")).mean()
print(out)

输出结果与现有方法一致:

number  time      
1       2023-01-01    1.0
2       2023-01-02    1.5
3       2023-01-03    2.5
4       2023-01-04    3.5
Name: 0, dtype: float64

如果熟悉层级位置,还能更精简(time是第2个层级,索引从0开始):

out = ser.rolling("2D", on=ser.index.get_level_values(1)).mean()

核心原因:Series的rolling方法on参数不支持直接传入MultiIndex的层级名称字符串,但可接受具体的Index对象。通过get_level_values获取目标层级的索引序列后,就能直接用于滚动计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:05:16