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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:16:02