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

如何将含字典列的Pandas DataFrame转为Polars Object类型DataFrame?

解决Pandas字典列转Polars Object类型列的问题

要保留原始Python字典对象而不被Polars转为Arrow结构体,可以通过以下两种方式实现:

方法1:直接构造Polars Series并指定Object类型

从Pandas DataFrame中提取列数据,用pl.Series显式指定dtype=pl.Object,再组合成Polars DataFrame:

import pandas as pd
import polars as pl

df_pd = pd.DataFrame({ "the_column": [{ "key" : 123 }, { "foo" : 456 }, { "bar" : 789 }]})

# 构造Object类型的Series
series_obj = pl.Series("the_column", df_pd["the_column"], dtype=pl.Object)
df_pl = pl.DataFrame(series_obj)

print(df_pl)

输出结果:

shape: (3, 1)
┌─────────────────┐
│ the_column      │
│ ---             │
│ object          │
╞═════════════════╡
│ {'key': 123}    │
│ {'foo': 456}    │
│ {'bar': 789}    │
└─────────────────┘

方法2:使用Polars DataFrame构造器直接指定类型

跳过from_pandas方法,直接用原始数据构造Polars DataFrame并指定列类型:

import pandas as pd
import polars as pl

data = { "the_column": [{ "key" : 123 }, { "foo" : 456 }, { "bar" : 789 }]}
df_pl = pl.DataFrame(data, schema={"the_column": pl.Object})

print(df_pl)

输出与方法1一致。

为什么schema_overrides会报错?

pl.from_pandas转换时会自动将Pandas中的字典列解析为Arrow结构体类型(Polars默认优先推断结构化类型),此时强制用schema_overrides转为Object类型会触发错误——结构体内部字段是强类型(如Int64),无法直接转为未知的Object类型。直接构造Series或DataFrame可绕过自动类型推断,保留原始Python对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:57:30