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

Polars DataFrame生成年月列遇SchemaError:类型不匹配问题求助

解决Polars生成year-month列的SchemaError问题

错误原因分析

你之前的代码存在两个关键问题:

  1. alias('year-month')的位置错误,应该嵌套在with_column的表达式内部,而非放在方法调用外部
  2. 仅将日期转成Datetime类型但未格式化为字符串,与期望的Utf8类型不匹配;同时解析日期时fmt='%Y-%m'与原数据YYYY-MM-DD的格式不匹配

解决方案

提供两种高效实现方式:

方法一:直接字符串切片(最优,适用于固定格式日期)

原date列是标准YYYY-MM-DD格式,直接截取前7位即可得到year-month:

df = pl.DataFrame({
   'date': ['2022-01-01', '2022-02-01', '2022-03-01']
})

# 生成year-month列
df = df.with_column(pl.col('date').str.slice(0, 7).alias('year-month'))

方法二:日期类型转换后格式化(适用于非固定格式日期)

先将字符串解析为日期类型,再通过strftime格式化输出:

df = pl.DataFrame({
   'date': ['2022-01-01', '2022-02-01', '2022-03-01']
})

# 生成year-month列
df = df.with_column(
    pl.col('date')
    .str.strptime(pl.Date, fmt='%Y-%m-%d')  # 匹配原数据的完整日期格式
    .dt.strftime('%Y-%m')  # 格式化为年月字符串
    .alias('year-month')
)

最终结果

执行后得到的DataFrame结构与期望一致:

dateyear-month
2022-01-012022-01
2022-02-012022-02
2022-03-012022-03

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:58:26