some_programmer
some_programmer

Reputation: 3548

How to merge different dfs and unstack the values?

I have a dict that has 17 df in it.

Sample 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

and so on.

I would like to merge these dfs in such a way that the key column becomes the name for each column and the respective values are filled in. In the df1 and df2 since there is only one key, the remaining keys must be filled with nans.

Desired output: enter image description here

How my dict of dfs looks like: enter image description here

Upvotes: 0

Views: 31

Answers (1)

jottbe
jottbe

Reputation: 4521

You can do that as follows:

# 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')

Upvotes: 1

Related Questions