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

使用Pandas按2个月分组DatetimeIndex报错:TypeError: Categorical input must be list-like

解决按2个月分组DatetimeIndex时的TypeError问题

错误原因

pd.Grouper是为DataFrame或Series这类带标签的序列设计的分组工具,直接作用于DatetimeIndex对象时,会因类型不匹配触发TypeError: Categorical input must be list-like错误。

解决方案

方案一:转为Series后使用pd.Grouper分组

把生成的时间序列包装成Series,再通过pd.Grouper指定2个月的频率进行分组:

import pandas as pd

date_time = pd.date_range(start='2022-01-01',
                          end='2022-12-31',
                          freq='H')
# 将DatetimeIndex转为Series
time_series = pd.Series(date_time, index=date_time)
# 按2个月频率分组
res = time_series.groupby(pd.Grouper(freq="2M"))

for r in res:
    print(r)

方案二:直接用周期转换分组

利用DatetimeIndex的to_period方法,把时间序列转为2个月的周期索引,再直接分组:

import pandas as pd

date_time = pd.date_range(start='2022-01-01',
                          end='2022-12-31',
                          freq='H')
# 转换为2个月周期后分组
res = date_time.groupby(date_time.to_period('2M'))

for r in res:
    print(r)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:13:19