0

I have pandas df like below:

Id Period Value1 Value2
1 3 20 60
1 4 30 70
2 3 40 80
2 4 50 90

How can I use Period as additional column, like this: (to have Period 3, 4 as separate columns and under each column with periods I have subcolumns Value1 and Value2)?

MultiIndex DF

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
  • This is a basic pivot, you just need to specify the index and columns, which puts everything else into the values argument: `df.pivot(index='Id', columns='Period')`. Then you can clean it up a bit by adding on a `.swaplevel(0, 1, axis=1).sort_index(axis=1)` to get the ordering you want – ALollz May 23 '22 at 16:30

1 Answers1

1

You can try pivot then swaplevel and sort_index

out = (df.pivot(index='Id', columns='Period', values=['Value1', 'Value2'])
       .swaplevel(0,1,1)
       .sort_index(axis=1))
print(out)

Period      3             4
       Value1 Value2 Value1 Value2
Id
1          20     60     30     70
2          40     80     50     90
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52