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

Python Polars如何将列表列展开并保留索引列?

解决Polars列表列展开成行的最优方法

你完全不需要遍历DataFrame,Polars内置了专门的explode方法——这是矢量化操作,效率比遍历高得多,直接就能实现需求:

实现代码

import polars as pl

# 原DataFrame
df2 = pl.DataFrame({'x': [1, 2, 3], 'y': [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j']]})

# 展开列表列并重命名
result_df = df2.explode('y').rename({'y': 'yp'})

print(result_df)

输出结果

shape: (10, 2)
┌─────┬─────┐
│ x   ┆ yp  │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 1   ┆ a   │
│ 1   ┆ b   │
│ 1   ┆ c   │
│ 2   ┆ d   │
│ 2   ┆ e   │
│ 2   ┆ f   │
│ 2   ┆ g   │
│ 3   ┆ h   │
│ 3   ┆ i   │
│ 3   ┆ j   │
└─────┴─────┘

补充说明

  • explode('y')会把y列的每个列表元素拆成单独的行,同时保留对应的x列值
  • 如果不需要重命名列,直接调用df2.explode('y')即可,展开后的列名还是y

内容的提问来源于stack exchange,提问作者Greg Vaysman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:52:15