如何按条件将长格式Dataframe转换为指定列的二维结构
Pandas 大数据量下的Dataframe重塑方案
需求说明
需要将源Dataframe(df)重塑为二维结构的outputdf:
- 第一列为
df中Column A的所有唯一值 - 其余列来自指定列表中的
Column B唯一值 - 单元格用对应行的
Column C值填充
示例源数据
| Column A | Column B | Column C |
|---|---|---|
| Cell 1 | Cell A | 1 |
| Cell 2 | Cell A | 2 |
| Cell 3 | Cell A | 3 |
| Cell 1 | Cell B | 4 |
| Cell 2 | Cell B | 5 |
| Cell 3 | Cell B | 6 |
| Cell 1 | Cell C | 7 |
| Cell 2 | Cell C | 8 |
| Cell 3 | Cell C | 9 |
指定列列表: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 A | Cell A | Cell B |
|---|---|---|
| Cell 1 | 1 | 4 |
| Cell 2 | 2 | 5 |
| Cell 3 | 3 | 6 |
内容的提问来源于stack exchange,提问作者ADunavent
相关产品推荐
相关产品推荐

