如何将字典的键作为mergerd数据帧的索引?

2024-06-07 18:43:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为percent_dictdict,里面有17dfs

样本dfs

Hffpw

          key                percentage
0   step19_without_lof  14.534883720930232

Hflpw

           key                percentage
0   step19_without_lof  14.970930232558139

Bgf

             key             percentage
0   step1_without_lof   1.5988372093023255
1   step2_without_lof   30.377906976744185
2   step5_without_lof   3.197674418604651
3   step7_without_lof   9.738372093023257
4   step12_without_lof  5.377906976744186
5   step15_without_lof  4.215116279069767
6   step16_without_lof  6.8313953488372094
7   step19_without_lof  13.80813953488372
8   step24_without_lof  9.883720930232558
9   step25_without_lof  11.337209302325581
10  step26_without_lof  9.738372093023257
11  step27_without_lof  9.738372093023257

等等

我将它们旋转如下:

def pivoting(df):
    d = pd.pivot_table(df, values = 'percentage', columns = ['key'])
    return d

pivoting('Hffpw')
pivoting('Hflpw')
pivoting('Bgf')

旋转后dfs的dict如下所示:

enter image description here

我正在尝试合并所有这些数据帧(值在percent_dict)并且键必须是结果数据帧的索引

我做了如下工作:

a = pd.concat(percent_dict.values())

它给了我:

enter image description here

在图中,我们可以看到percentage是索引。但是我想知道如何从percent_dict中指定Keys作为数据帧的索引


Tags: 数据keydfdictpdwithoutpercentpercentage
1条回答
网友
1楼 · 发布于 2024-06-07 18:43:44

一个想法是首先^{},然后将MultiIndex转换为列,最后使用pivot_table

df = (pd.concat(percent_dict)
        .reset_index()
        .pivot_table(index='level_0', values = 'percentage', columns = 'key'))

print (df)
key      step12_without_lof  step15_without_lof  step16_without_lof  \
level_0                                                               
Bgf                5.377907            4.215116            6.831395   
Hffpw                   NaN                 NaN                 NaN   
Hflpw                   NaN                 NaN                 NaN   

key      step19_without_lof  step1_without_lof  step24_without_lof  \
level_0                                                              
Bgf               13.808140           1.598837            9.883721   
Hffpw             14.534884                NaN                 NaN   
Hflpw             14.970930                NaN                 NaN   

key      step25_without_lof  step26_without_lof  step27_without_lof  \
level_0                                                               
Bgf               11.337209            9.738372            9.738372   
Hffpw                   NaN                 NaN                 NaN   
Hflpw                   NaN                 NaN                 NaN   

key      step2_without_lof  step5_without_lof  step7_without_lof  
level_0                                                           
Bgf              30.377907           3.197674           9.738372  
Hffpw                  NaN                NaN                NaN  
Hflpw                  NaN                NaN                NaN  

相关问题 更多 >

    热门问题