Imsa
Imsa

Reputation: 1125

Pandas Pivot Table to have two rows for each group

I have a table that looks like this.

id      process     Number1    Number2
1       a           11       343
1       b           22       121
1       c           33       889
2       a           41       317
2       b           42       997
2       c           43       761

What I would like is to pivot that table so it looks like this.

        a       b       c
1       343     121     889
1       11      22      33
2       317     997     761
2       41      42      43

Essentially, process becomes a header, and each id becomes an index. One row has Number1 and second row has Number2.

I have

fail_rate_df.pivot_table(index='id', columns='process', values='Number2', aggfunc='first')

which returns

        a       b       c
1       343     121     889
2       317     997     761

How can I add a second row for each id to have Number1 also. Number2 should be first row, and Number1 second row.

Upvotes: 1

Views: 572

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Try:

(df.pivot_table(index='id', columns='process', aggfunc='first')
   .stack(level=0)
   .sort_index(level=[0,1], ascending=[True,False])
)

Output:

process       a    b    c
id                       
1  Number2  343  121  889
   Number1   11   22   33
2  Number2  317  997  761
   Number1   41   42   43

Upvotes: 1

Related Questions