使用 Polars,如何将字符串列表表达式/列连接到字符串

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

这是我想要使用

map_elements
执行的简单解决方案。我如何仅使用 Polars 功能来做到这一点?

import polars as pl

# Create a DataFrame with a column containing lists of strings
df = pl.DataFrame({
    "list_of_strings": [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
})

# Define a function to concatenate lists of strings into a single string
def concatenate_list_of_strings(lst):
    return "".join(lst)

# Apply the function to the DataFrame
df = df.with_column(
    pl.col("list_of_strings").map_elements(concatenate_list_of_strings, return_dtype=pl.String).alias("concatenated_string")
)

print(df)
python python-polars
1个回答
0
投票

正如评论中已经提到的,Polars 的原生表达式 API 中有

pl.Expr.list.join
,可以将子列表中的所有字符串项连接起来,并在它们之间使用分隔符。

df.with_columns(
    pl.col("list_of_strings").list.join("")
)
shape: (3, 1)
┌─────────────────┐
│ list_of_strings │
│ ---             │
│ str             │
╞═════════════════╡
│ abc             │
│ def             │
│ ghi             │
└─────────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.