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

如何转置Polars DataFrame?附示例代码与期望输出

在Polars中实现DataFrame转置

你可以使用Polars的transpose方法完成这个转换,关键是配置参数让原Year列的值成为新的列名,原产品列名作为第一列。

实现代码

import polars as pl

df = pl.from_repr("""
┌──────┬──────────┬──────────┬──────────┐
│ Year ┆ Product1 ┆ Product2 ┆ Product3 │
│ ---  ┆ ---      ┆ ---      ┆ ---      │
│ i64  ┆ i64      ┆ i64      ┆ i64      │
╞══════╪══════════╪══════════╪══════════╡
│ 2018 ┆ 100      ┆ 150      ┆ 200      │
│ 2019 ┆ 120      ┆ 180      ┆ 240      │
│ 2020 ┆ 140      ┆ 210      ┆ 280      │
└──────┴──────────┴──────────┴──────────┘
""")

# 执行转置操作
transposed_df = df.transpose(
    include_header=True,
    header_name="",
    column_names=df["Year"].to_list()
)

print(transposed_df)

参数说明

  • include_header=True:保留原DataFrame的列名(Product1/2/3)作为转置后第一列的内容
  • header_name="":将转置后的第一列名称设置为空,匹配期望输出格式
  • column_names=df["Year"].to_list():把原Year列的所有值(2018/2019/2020)作为转置后的列名

输出结果

shape: (3, 4)
┌──────────┬──────┬──────┬──────┐
│          ┆ 2018 ┆ 2019 ┆ 2020 │
│ ---      ┆ ---  ┆ ---  ┆ ---  │
│ str      ┆ i64  ┆ i64  ┆ i64  │
╞══════════╪══════╪══════╪══════╡
│ Product1 ┆ 100  ┆ 120  ┆ 140  │
│ Product2 ┆ 150  ┆ 180  ┆ 210  │
│ Product3 ┆ 200  ┆ 240  ┆ 280  │
└──────────┴──────┴──────┴──────┘

内容的提问来源于stack exchange,提问作者Tomas Perez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:13:17