这是我想要使用
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)
正如评论中已经提到的,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 │
└─────────────────┘