Pandas DataFrame: How to Create Multi Column Index

Viewed 176

I have a pandas DataFrame that looks similar to this:

          player     frameID    x          y  
  
0         Tom        0          1          3
1         Tom        1          2          3
2         Tom        2          1          3
3         John       0          4          2
4         John       1          3          1
5         John       2          2          2
6         Greg       0          5          3
7         Greg       1          3          2
8         Greg       2          2          1
.         .          .          .          .
.         .          .          .          .
.         .          .          .          .

And I want to format it so that it looks like this:

          player  Tom           John          Greg
frameID    
                  x      y      x      y      x      y

0                 1      3      4      2      5      3
1                 2      3      3      1      3      2
2                 1      3      2      2      2      1
.                 .      .      .      .      .      .
.                 .      .      .      .      .      .
.                 .      .      .      .      .      .

However, I have no clue how to go about the multi-indexing. As you can see, I want to take two of the columns and place one as an index on the columns and one as an index on the rows. Any help would be greatly appreciated.

1 Answers

Let's create a multilevel index then use stack + unstack to reshape the dataframe:

df.set_index(['frameID', 'player']).stack().unstack([1, 2])

player    Tom     John    Greg   
          x  y    x  y    x  y
frameID                       
0         1  3    4  2    5  3
1         2  3    3  1    3  2
2         1  3    2  2    2  1
Related