polars 将列表类型的列连接成字符串类型的列

问题描述 投票:0回答:1

我想使用仅限极坐标的本机函数将数据帧列表[String] 列连接到字符串列。可以吗?

df = pl.DataFrame({
    'col1': [["1.0", "1.0"], ["2.0", "3.0"]],
    'col2': ["a", "a"],
})

这是我想要达到的预期输出。

shape: (2, 2)
┌─────────┬──────┐
│ col1    ┆ col2 │
│ ---     ┆ ---  │
│ str     ┆ str  │
╞═════════╪══════╡
│ 1.0,1.0 ┆ a    │
│ 2.0,3.0 ┆ a    │
└─────────┴──────┘

我根本不想使用自定义Python函数。

python python-polars
1个回答
2
投票

您可以通过

list.join
变换获得:

df.with_columns(
    pl.col('col1').list.join(',')
)

# result
shape: (2, 2)
┌─────────┬──────┐
│ col1    ┆ col2 │
│ ---     ┆ ---  │
│ str     ┆ str  │
╞═════════╪══════╡
│ 1.0,1.0 ┆ a    │
│ 2.0,3.0 ┆ a    │
└─────────┴──────┘

© www.soinside.com 2019 - 2024. All rights reserved.