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

Polars:如何将行内列合并为list[object]并转换列类型为object

问题场景与需求

用户创建了如下Polars DataFrame:

import polars as pl
df = pl.DataFrame(dict(
  j=['hello', 'world'],
  k=[1, 2],
))

输出结构:

j (str)  k (i64)
 hello    1
 world    2
shape: (2, 2)

执行df.select(polars.concat_list(polars.all()))后,得到统一为字符串类型的列表列:

j (list[str])
 ["hello", "1"]
 ["world", "2"]
shape: (2, 1)

用户期望得到保留原数据类型的list[object]列:

df = pl.DataFrame(dict(
  j=[['hello', 1], ['world', 2]],
))

目标输出结构:

j (object)
 ['hello', 1]
 ['world', 2]
shape: (2, 1)

尝试df.select(polars.all().cast(object))时触发异常:

pyo3_runtime.PanicException: cannot convert object to arrow

用户需实现两个需求:

  • 将每行所有列合并为list[object];
  • 常规方式将列转换为object类型。
解决方案

1. 合并每行列为list[object]

利用struct将列打包,再通过apply转为Python原生列表并指定返回类型为pl.Object,避免类型统一:

result = df.select(
    pl.struct(pl.all()).apply(
        lambda x: list(x.values()), 
        return_dtype=pl.Object
    ).alias("combined")
)
print(result)

输出结果:

shape: (2, 1)
┌─────────────────┐
│ combined        │
│ ---             │
│ object          │
╞═════════════════╡
│ ["hello", 1]    │
│ ["world", 2]    │
└─────────────────┘

2. 将列转换为object类型

直接cast(object)会触发Arrow底层错误,需通过apply包装值来实现类型转换:

# 转换指定列
df = df.with_columns(
    pl.col("k").apply(lambda x: x, return_dtype=pl.Object)
)

# 转换所有列
df = df.with_columns(
    pl.all().apply(lambda x: x, return_dtype=pl.Object)
)

转换后列类型会变为object,同时保留原有数据的类型信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:22:27