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

如何用Python Polars从整数格式日期生成新日期列

解决Polars中整数格式日期转日期列及生成滞后日期的问题

你遇到的SchemaError是因为str.strptime方法仅支持字符串类型的列,而你的IntegerDate是整数类型(Int64),直接调用字符串处理方法会出现类型不匹配。下面是修正后的完整实现,和你Pandas代码的逻辑完全对齐:

方法1:一次性生成两个列

import polars as pl

df = df.with_columns(
    # 先将整数转为字符串,再解析为日期时间
    PeriodDate=pl.col("IntegerDate").cast(pl.Utf8).str.strptime(pl.Datetime, "%Y%m"),
    # 基于解析后的日期生成滞后一个月的日期
    LaggedDate=pl.col("IntegerDate").cast(pl.Utf8).str.strptime(pl.Datetime, "%Y%m").dt.offset_by("-1mo")
)

方法2:先生成PeriodDate,再复用它生成LaggedDate(更高效)

如果数据量很大,避免重复解析日期可以提升性能:

df = df.with_columns(
    PeriodDate=pl.col("IntegerDate").cast(pl.Utf8).str.strptime(pl.Datetime, "%Y%m")
).with_columns(
    LaggedDate=pl.col("PeriodDate").dt.offset_by("-1mo")
)

关键步骤说明

  • cast(pl.Utf8):将整数类型的日期值转换为字符串,满足str.strptime的输入要求。
  • str.strptime(pl.Datetime, "%Y%m"):按照%Y%m(年+月)的格式将字符串解析为Polars的Datetime类型。
  • dt.offset_by("-1mo"):对日期时间列执行偏移操作,减去1个月,效果等价于Pandas中的pd.DateOffset(months=1)。

如果只需要保留年月精度(不需要日时分秒),可以将解析类型改为pl.Date,或者在解析后调用dt.truncate("month")截断到月份:

PeriodDate=pl.col("IntegerDate").cast(pl.Utf8).str.strptime(pl.Date, "%Y%m")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:35:18