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

Polars中datetime类型列分箱报错:TypeError问题求助

解决Polars中Datetime列分箱的TypeError问题

问题根源

Polars的cut函数仅支持数值类型输入,无法直接处理datetime类型的分箱边界(breaks),因此传入datetime对象会触发TypeError: argument 'breaks': must be real number, not datetime.datetime。


解决方案

针对datetime列的分箱需求,推荐以下两种实现方式:

方案1:快速生成分箱起始标识(极简版)

如果仅需要标记每个日期所属的分箱起始点(如按3个月对齐),直接使用dt.truncate或dt.floor即可:

df = df.with_columns(
    # 将日期截断到最近的3个月起始点
    pl.col("ts").dt.truncate("3mo").alias("period_bins")
)

执行后结果示例:

┌────────────┬────────────┐
│ ts         │ period_bins│
│ ---        │ ---        │
│ date       │ date       │
╞════════════╪════════════╡
│ 2021-10-01 │ 2021-10-01 │
│ 2021-11-01 │ 2021-10-01 │
│ 2022-03-01 │ 2022-01-01 │
└────────────┴────────────┘

方案2:生成完整区间标签(模拟Pandas Cut效果)

如果需要像Pandas那样显示区间范围(如[2021-10-01, 2022-01-01)),可以通过floor和duration拼接区间字符串:

df = df.with_columns(
    period_bins = pl.format(
        "[{}, {})",
        # 取当前日期所在3个月区间的起始
        pl.col("ts").dt.floor("3mo"),
        # 计算区间的结束时间
        pl.col("ts").dt.floor("3mo") + pl.duration(months=3)
    )
)

执行后结果示例:

┌────────────┬──────────────────────────┐
│ ts         │ period_bins              │
│ ---        │ ---                      │
│ date       │ str                      │
╞════════════╪══════════════════════════╡
│ 2021-10-01 │ [2021-10-01, 2022-01-01) │
│ 2021-11-01 │ [2021-10-01, 2022-01-01) │
│ 2022-03-01 │ [2022-01-01, 2022-04-01) │
└────────────┴──────────────────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:25:30