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

Polars Python中如何将多列数据合并为列表类型的列

Polars Python中如何将多列数据合并为列表类型的列

嘿,刚上手Polars的话碰到这种问题太正常啦,我来给你捋个简单的解决方法~

首先先还原一下你的示例数据:

import polars as pl

data = pl.DataFrame(
    {
        "a": [1, 2, 3],
        "b": [4, 5, 6],
        "c": [7, 8, 9],
    }
)

你想要把每一行的a、b、c列值打包成列表作为新列d,Polars里刚好有专门的函数能搞定这个——pl.concat_list(),直接用它就能实现需求:

result = data.with_columns(
    d=pl.concat_list(["a", "b", "c"])
)

print(result)

运行之后输出的结果就是你想要的样子:

shape: (3, 4)
┌─────┬─────┬─────┬───────────┐
│ a   ┆ b   ┆ c   ┆ d         │
│ --- ┆ --- ┆ --- ┆ ---       │
│ i64 ┆ i64 ┆ i64 ┆ list[i64] │
╞═════╪═════╪═════╪═══════════╡
│ 1   ┆ 4   ┆ 7   ┆ [1, 4, 7] │
│ 2   ┆ 5   ┆ 8   ┆ [2, 5, 8] │
│ 3   ┆ 6   ┆ 9   ┆ [3, 6, 9] │
└─────┴─────┴─────┴───────────┘

顺便补充个小技巧:如果你的列特别多,不想一个个列名写出来,可以用pl.all()来选中所有列,比如:

result = data.with_columns(
    d=pl.concat_list(pl.all())
)

这样就会自动把所有列按顺序合并成列表列啦~

备注:内容来源于stack exchange,提问作者Всеволод Морозов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 10:29:28