1

I have a Pandas DataFrame similar to this one:

    player  unit    stat1   stat2
0   p1      u1      10      8
1   p1      u2      21      2
3   p2      u1      2       7
4   p2      u2      32      34

One row exists for each combination of player and unit. I would like to transform this DataFrame into one looking like this:

            p1      p2
u1  stat1   10      2
    stat2   8       7
u2  stat1   21      32
    stat2   2       34

where units and the various stats are turned into a multi-level index and players are turned into columns. How can I achieve this?

abey
  • 593
  • 10
  • 26

1 Answers1

1

Try:

df.pivot(index='unit', columns='player').stack(level=0)

or without pivot:

df.set_index(['unit','player']).stack().unstack('player')

Output:

player      p1  p2
unit              
u1   stat1  10   2
     stat2   8   7
u2   stat1  21  32
     stat2   2  34
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74