首页 > 解决方案 > 如何合并不同的dfs并取消堆叠值?

问题描述

我有一个里面dict有17个df

样品dfs

df1

          key                percent
0   step19_without_lof  14.534883720930232

df2

           key                   percent
0   step19_without_lof  14.970930232558139

df3

             key             percent
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

等等。

我想以dfs这样的方式合并这些key列成为每列的名称并填写相应的值。在df1anddf2由于只有一个key,其余的keys必须填写nans

期望的输出: 在此处输入图像描述

我的 dfs 字典看起来如何: 在此处输入图像描述

标签: pythonpandas

解决方案


你可以这样做:

# append the key to the index (first level is the old index)
# then unstack the key, so the key is converted to columns
df.set_index('key', append=True).unstack('key')

推荐阅读