Skip to main content
 首页 » 编程设计

python之将 3D pandas 数据帧转换为 2d

2024年12月31日9wuhuacong

<分区>

我有一个具有 2 级索引和一列的 3D 数据框,如下所示:

          col1 
0   0      67.23 
0   1      7382 
0   2      43 
    . 
    . 
0   8002   54 
0   8003   87 
1   0      348 
1   1      83 
1   2      234 
    . 
    . 
1   8002   23 
1   8003   87 
.... 
9   0      348 
9   1      833 
9   2      43433 
    . 
    . 
9   8002   23 
9   8003   87 

第一级有10个索引,第二级每级有8004个元素。我需要将其 reshape 为二维数据框,如下所示:

    0 | 1 | 2 | 3 | ... | 8000 | 8001 | 8002 | 8003 
-------------------------------------------------- 
0     |   |   |   |     |      |      |      |  
1     |   |   |   |     |      |      |      |        
2     |   |   |   |     |      |      |      |        
.     |   |   |   |     |      |      |      |  
.     |   |   |   |     |      |      |      |  
8     |   |   |   |     |      |      |      |        
9     |   |   |   |     |      |      |      |        

为此,我创建了一个新索引:new_idx = pd.Index(range(0,10))

和新列为:cols = range(0,8004)

然后尝试使用 pivot 如下:

2d_df = df.pivot(index=new_idx, columns=cols, values='var1')

但这给了我一个错误:Int64Index([0,1,2,3,4,5,6,7,8,9], dtype='int64') not in index .我应该怎么做?