Polars创建DataFrame时指定日期列失败,后续转换却成功
Polars指定Date类型创建DataFrame失败,先转Utf8再转换则正常执行
问题场景
拥有字典列表results,预期的Schema定义如下:
import polars as pl results = ... schema = { "id": pl.Int64, "title": pl.Utf8, "proprietors": pl.List(pl.Utf8), "registrationDate": pl.Date, }
直接使用该Schema创建DataFrame时触发报错:
df = pl.DataFrame(results, schema=schema)
报错信息
ComputeError: could not append value: "2024-08-16T00:00:00" of type:
str to the builder; make sure that all rows have the same schema or
consider increasinginfer_schema_lengthit might also be that a value overflows the data-type's capacity
可行解决方案
先将日期列的类型临时改为pl.Utf8创建DataFrame,之后再转换为日期时间类型即可成功执行:
for col, dtype in schema.items(): if col.endswith("Date"): schema[col] = pl.Utf8 df = pl.DataFrame(results, schema=schema) for col, dtype in schema.items(): if col.endswith("Date"): df = df.with_columns(pl.col(col).str.strptime(pl.Datetime)) # 执行成功,无报错
使用环境:polars 1.6.0,Python 3.12.4
内容的提问来源于stack exchange,提问作者tsorn
相关产品推荐
相关产品推荐

