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

如何在Polars中实现list[]类型列到str类型的转换?

Polars中高效将List类型列转为字符串的方案

直接使用cast(str)转换Polars的List类型列会触发错误:

ComputeError: Cannot cast list type

如果不想用rows()、转Pandas DataFrame或apply()这类性能较低的方法,可以用以下矢量化的高效方案实现需求:

推荐方法:用list.join + pl.format拼接

利用Polars内置的列表拼接和字符串格式化函数,全程矢量化处理,性能远高于逐元素映射:

import polars as pl

# 初始化测试数据
df = pl.from_dict({'foo': [[1,2,3], [4,5]], 'bar': ['Hello World', 'Hi Polars']})
# 转换List列为目标格式的字符串
result_df = df.with_columns(
    pl.format('"[{}]"', pl.col("foo").list.join(", ")).alias("foo")
)

print(result_df)

执行后输出符合预期:

shape: (2, 2)
┌─────────────┬─────────────┐
│ foo         ┆ bar         │
│ ---         ┆ ---         │
│ str         ┆ str         │
╞═════════════╪═════════════╡
│ "[1, 2, 3]" ┆ Hello World │
│ "[4, 5]"    ┆ Hi Polars   │
└─────────────┴─────────────┘

原理说明

  1. pl.col("foo").list.join(", "):将每个List元素用, 拼接成无方括号的字符串(比如[1,2,3]变成"1, 2, 3")
  2. pl.format('"[{}]"', ...):给拼接后的字符串包裹方括号和双引号,生成最终格式的字符串

这种方法完全基于Polars的矢量化API,避免了Python层面的循环,处理大数据量时性能优势明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:42:56