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

求助:如何用Pivot Table实现可变行数的行转列?

需求说明

已查阅透视表相关资料,但仍无法实现以下数据转换需求:
现有表格包含四列:Productnr、LHS、Productnr2、RHS,每个Productnr对应的Productnr2条目数为1-5个(数量不定),需将多行数据按Productnr合并为单行,把对应的Productnr2和RHS依次排列到1-5的列组中,无数据的列留空。

原始数据

Productnr  LHS  Productnr2    RHS
060009     411  099088        5
060013     228  194139        25
060013     228  194141        17
060013     228  175823        75
060022     951  147071        90
060034     424  099088        14
060034     424  102704        88
060034     424  080034        82
060034     424  108436        87
060034     424  108437        58

期望输出

Productnr |  LHS |  1  |  RHS  |  2  |  RHS  |  3  |  RHS  |  4  |  RHS  |  5  |  RHS  |   
----- 
060009       411  099088   5    
060013       228  194139   25   194141   17   175823   75
060022       951  147071   90
060034       424  099088   14   102704   88   080034   82   108436   87   108437   58

解决方案

方法1:Excel 操作步骤

  • 添加组内序号列:在原始数据右侧新增一列,命名为序号,在首行数据对应的单元格输入公式 =COUNTIF($A$2:A2,A2),下拉填充整列,实现按Productnr分组生成1-5的序号。
  • 创建透视表:选中所有数据插入透视表,将Productnr、LHS拖到「行」区域,序号拖到「列」区域,Productnr2、RHS拖到「值」区域,值字段设置为「最大值」(每个分组序号对应唯一值,最大值即为本身)。
  • 调整列顺序:将透视表的列调整为Productnr、LHS、1(Productnr2)、1(RHS)、2(Productnr2)、2(RHS)...的顺序,空列保留即可。

方法2:Python(Pandas)代码实现

import pandas as pd

# 读取原始数据(根据实际存储格式调整读取方式)
df = pd.read_csv("your_data.csv", sep="\s+")

# 按Productnr分组生成组内序号
df["序号"] = df.groupby("Productnr").cumcount() + 1

# 生成透视表
pivot_df = df.pivot(index=["Productnr", "LHS"], columns="序号", values=["Productnr2", "RHS"])

# 重排列顺序,匹配需求格式
pivot_df.columns = [f"{col[1]}" if col[0] == "Productnr2" else "RHS" for col in pivot_df.columns]
pivot_df = pivot_df.reindex(columns=["1", "RHS", "2", "RHS", "3", "RHS", "4", "RHS", "5", "RHS"])

# 重置索引并输出
result_df = pivot_df.reset_index()
print(result_df.to_string(index=False))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:18:34