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

如何按条件将长格式Dataframe转换为指定列的二维结构

Pandas 大数据量下的Dataframe重塑方案

需求说明

需要将源Dataframe(df)重塑为二维结构的outputdf:

  • 第一列为df中Column A的所有唯一值
  • 其余列来自指定列表中的Column B唯一值
  • 单元格用对应行的Column C值填充

示例源数据

Column AColumn BColumn C
Cell 1Cell A1
Cell 2Cell A2
Cell 3Cell A3
Cell 1Cell B4
Cell 2Cell B5
Cell 3Cell B6
Cell 1Cell C7
Cell 2Cell C8
Cell 3Cell C9

指定列列表:target_cols = ['Cell A', 'Cell B']

无效的循环Merge尝试

你之前的循环逻辑存在两个问题:一是merge的on参数错误(x是Column B的取值,不是列名),二是循环merge在大数据量下计算效率极低,代码如下:

for x in list:
    outputdf[x] = outputdf.merge(df, on=['ColumnA', x], how='left').set_index('ColumnA')

大数据量友好的正确方案

直接用Pandas原生的pivot或pivot_table方法,这两个方法是专门为行列转换场景优化的,比循环merge效率高几个量级,完全适配大数据场景:

方法1:使用pivot(适合无重复(Column A, Column B)组合的场景)

import pandas as pd

# 1. 先过滤出目标列的数据,减少计算量
filtered_df = df[df['Column B'].isin(target_cols)]

# 2. 执行pivot重塑
outputdf = filtered_df.pivot(
    index='Column A',
    columns='Column B',
    values='Column C'
).reset_index()

# 3. 清理列名(可选,让结构更整洁)
outputdf.columns.name = None

方法2:使用pivot_table(适合存在重复(Column A, Column B)组合的场景)

如果数据中同一Column A和Column B组合有多行,可以用pivot_table指定聚合函数处理重复值,比如取第一个值、求和或均值:

outputdf = filtered_df.pivot_table(
    index='Column A',
    columns='Column B',
    values='Column C',
    aggfunc='first'  # 可替换为'sum'/'mean'等聚合逻辑
).reset_index()
outputdf.columns.name = None

最终结果

执行后得到的outputdf如下:

Column ACell ACell B
Cell 114
Cell 225
Cell 336

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:25:53