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

指定pl.Object仍报‘struct orders must remain the same’,如何让Polars存字典为Object?

解决Polars 0.14.18中"struct orders must remain the same"报错问题

问题场景

使用数据库fetchall()结果创建DataFrame,指定dict_col为pl.Object类型以保留原始字典结构,但触发如下报错:

thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: ComputeError(Borrowed("struct orders must remain the same"))', /Users/runner/work/polars/polars/polars/polars-core/src/frame/row.rs:457:86
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Traceback (most recent call last):
  File:
    df = pl.DataFrame(
  File "venv/lib/python3.9/site-packages/polars/internals/dataframe/frame.py", line 299, in __init__
    self._df = sequence_to_pydf(
  File "venv/lib/python3.9/site-packages/polars/internals/construction.py", line 612, in sequence_to_pydf
    pydf = PyDataFrame.read_rows(data, infer_schema_length)
pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value: ComputeError(Borrowed("struct orders must remain the same"))

报错原因

Polars 0.14.18版本中,通过行数据(如fetchall()返回结果)创建DataFrame时,会自动尝试将字典解析为struct类型——即使已指定pl.Object类型。若不同行的字典键顺序不一致,就会触发"struct orders must remain the same"错误。

解决方案

绕过行读取阶段的自动解析逻辑,通过单独创建pl.Series再组合为DataFrame:

# 获取原始数据库返回数据
rows = c.fetchall()

# 拆分各列数据
primary_keys = [row[0] for row in rows]
string_cols = [row[1] for row in rows]
dict_cols = [row[2] for row in rows]

# 分别创建指定类型的Series,再组合成DataFrame
df = pl.DataFrame({
    "primary_key": pl.Series(primary_keys, dtype=pl.Int32),
    "string_col": pl.Series(string_cols, dtype=pl.Object),
    "dict_col": pl.Series(dict_cols, dtype=pl.Object)
})

这种方式会直接将字典作为Python原生对象存储在pl.Object列中,避免Polars自动解析为struct,从而解决报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:15:35