Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Groupby & Pivot

Tags:

python

pandas

I have a pandas df setup as the following:

    product salesperson positionHours  levelHours 
0      soap        john            10          25
1      nuts        john            15          27
2      soap        doug            12          29
3      nuts        doug            11          24
4      soap        tory            19          20
5      nuts        tory            20          20

And I am trying to achieve the following, how can I do this in pandas?

    product     measurement   john  doug  tory 
0      soap   positionHours     10    12    19
1                levelHours     25    29    20 
3      nuts   positionHours     15    11    20
4                levelHours     27    24    20 
like image 623
guy Avatar asked Sep 06 '25 00:09

guy


1 Answers

There's going to be a multitude of ways you can do this. First couple that come to mind:

Melt, then pivot:

(df.melt(["product", "salesperson"], var_name="measurement")
 .pivot(index=["product", "measurement"], columns="salesperson", values="value")
 .rename_axis(None, axis=1))

                       doug  john  tory
product measurement                    
nuts    levelHours       24    27    20
        positionHours    11    15    20
soap    levelHours       29    25    20
        positionHours    12    10    19

pivot, then stack

(df.pivot(index="product", columns="salesperson", values=["positionHours", "levelHours"])
 .stack(0)
 .rename_axis(index=["product", "measurement"], columns=None))

                       doug  john  tory
product measurement                    
nuts    levelHours       24    27    20
        positionHours    11    15    20
soap    levelHours       29    25    20
        positionHours    12    10    19

set index, then do an unstack/stack combo

(df.set_index(["product", "salesperson"])
 .rename_axis("measurement", axis=1)
 .unstack(1)
 .stack(0)
 .rename_axis(None, axis=1))

                       doug  john  tory
product measurement                    
nuts    levelHours       24    27    20
        positionHours    11    15    20
soap    levelHours       29    25    20
        positionHours    12    10    19
like image 84
Cameron Riddell Avatar answered Sep 07 '25 16:09

Cameron Riddell