Polars DataFrame生成年月列遇SchemaError:类型不匹配问题求助
解决Polars生成year-month列的SchemaError问题
错误原因分析
你之前的代码存在两个关键问题:
alias('year-month')的位置错误,应该嵌套在with_column的表达式内部,而非放在方法调用外部- 仅将日期转成
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结构与期望一致:
| date | year-month |
|---|---|
| 2022-01-01 | 2022-01 |
| 2022-02-01 | 2022-02 |
| 2022-03-01 | 2022-03 |
内容的提问来源于stack exchange,提问作者Vanessa
相关产品推荐
相关产品推荐

