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

如何用Python将含重复索引的DataFrame转换为目标格式?

如何将原始DataFrame转换为目标Final DataFrame?

原始DataFrame

test1  test2 class value1
0       1      5  type  type1
1       1      5  type  type3
2       2      6  type  type1
3       3      7  type  type2
4       1      5   lat     40
5       1      5   lat     20
6       2      6   lat     50
7       3      7   lat     60
8       1      5   lon      1
9       1      5   lon      2
10      2      6   lon      2
11      3      7   lon      3

目标Final DataFrame

test1  test2   type  lat  lon
0      1      5  type1   40    1
1      2      6  type1   50    2
2      3      7  type2   60    3
3      1      5  type3   20    2 

为啥用pivot会报错?

你写的pivot代码报错,是因为index=['test1','test2'] + columns='class'的组合存在重复项(比如test1=1、test2=5、class=type对应两条记录),而pivot要求每个(index, columns)的组合必须唯一,所以无法直接完成透视。

解决方案

先给每个test1+test2+class分组内的行添加序号,确保每个组合唯一,再执行透视操作:

import pandas as pd

# 构造原始DataFrame(如果已有可以跳过这步)
df_orig = pd.DataFrame({
    'test1': [1,1,2,3,1,1,2,3,1,1,2,3],
    'test2': [5,5,6,7,5,5,6,7,5,5,6,7],
    'class': ['type','type','type','type','lat','lat','lat','lat','lon','lon','lon','lon'],
    'value1': ['type1','type3','type1','type2','40','20','50','60','1','2','2','3']
})

# 给每个(test1, test2, class)分组内的行分配序号
df_orig['seq'] = df_orig.groupby(['test1', 'test2', 'class']).cumcount()

# 执行透视,索引包含test1、test2、seq,列是class,值是value1
df_pivoted = df_orig.pivot(
    index=['test1', 'test2', 'seq'],
    columns='class',
    values='value1'
).reset_index()

# 清理不必要的列并调整列顺序
df_final = df_pivoted.drop('seq', axis=1)[['test1', 'test2', 'type', 'lat', 'lon']]

# 将lat和lon转为数值类型(可选,根据需求调整)
df_final['lat'] = df_final['lat'].astype(int)
df_final['lon'] = df_final['lon'].astype(int)

# 若需要和目标行顺序完全一致,添加排序
df_final = df_final.sort_values(by=['test1', 'test2', 'type']).reset_index(drop=True)

print(df_final)

运行结果:

test1  test2   type  lat  lon
0      1      5  type1   40    1
1      2      6  type1   50    2
2      3      7  type2   60    3
3      1      5  type3   20    2

内容的提问来源于stack exchange,提问作者Adam J. Berlier

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:07:42