如何在Polars中合并或展平DataFrame的嵌套列表列?
在Polars中展开嵌套列表列(list of lists)
你可以直接使用Polars的list.flatten()方法来实现需求,它会将每个单元格里的list[list[T]]结构展开为一维的list[T],同时自动忽略空的子列表。
实现代码
import polars as pl df = pl.DataFrame({ "nodes": [[[1], [1,2], []], [[2]], [[1], [2]]] }) # 展开嵌套列表 result_df = df.with_columns(pl.col("nodes").list.flatten()) print(result_df)
输出结果
shape: (3, 1) ┌───────────┐ │ nodes │ │ --- │ │ list[i64] │ ╞═══════════╡ │ [1, 1, 2] │ │ [2] │ │ [1, 2] │ └───────────┘
额外说明
- 若要保留原列,仅新增处理后的列,可指定新列名:
result_df = df.with_columns(flattened_nodes=pl.col("nodes").list.flatten()) - 针对更深层次的嵌套列表,可以多次调用
list.flatten(),或者结合list.eval()做自定义处理,但你的场景用list.flatten()就足够简洁高效。
内容的提问来源于stack exchange,提问作者mavex857
相关产品推荐
相关产品推荐

