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

如何按特定方式处理Polars DataFrame的列?

Polars实现列表列转指定格式DataFrame

实现步骤

  1. 宽表转长表:用melt方法将原DataFrame的列名转为Name列,原列表数据转为Values列,得到长格式数据。
  2. 列表转结构体并展开:将Values列的列表转为结构体(指定字段名为Value0、Value1、Value2),再通过unnest展开结构体为独立列。

完整代码

import polars as pl

# 原DataFrame
df = pl.DataFrame({
    "foo": [[1, 2, 3], [7, 8, 9]],
    "bar": [[4, 5, 6], [1, 0, 1]]
})

# 转换逻辑
result = (
    df.melt(var_name="Name", value_name="Values")
    .with_columns(
        pl.col("Values").list.to_struct(fields=[f"Value{i}" for i in range(3)])
    )
    .unnest("Values")
)

print(result)

输出结果

shape: (4, 4)
┌──────┬────────┬────────┬────────┐
│ Name ┆ Value0 ┆ Value1 ┆ Value2 │
│ ---  ┆ ---    ┆ ---    ┆ ---    │
│ str  ┆ i64    ┆ i64    ┆ i64    │
╞══════╪════════╪════════╪════════╡
│ foo  ┆ 1      ┆ 2      ┆ 3      │
│ foo  ┆ 7      ┆ 8      ┆ 9      │
│ bar  ┆ 4      ┆ 5      ┆ 6      │
│ bar  ┆ 1      ┆ 0      ┆ 1      │
└──────┴────────┴────────┴────────┘

内容的提问来源于stack exchange,提问作者Ryan Xu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:16:29