pandas: how to run a pivot with a multi-index?

前端 未结 3 1445
轻奢々
轻奢々 2020-12-07 13:10

I would like to run a pivot on a pandas DataFrame, with the index being two columns, not one. For example, one field for the year, one for the month, an \'item\

3条回答
  •  温柔的废话
    2020-12-07 13:59

    I believe if you include item in your MultiIndex, then you can just unstack:

    df.set_index(['year', 'month', 'item']).unstack(level=-1)
    

    This yields:

                    value      
    item       item 1 item 2
    year month              
    2004 1         21    277
         2         43    244
         3         12    262
         4         80    201
         5         22    287
         6         52    284
         7         90    249
         8         14    229
         9         52    205
         10        76    207
         11        88    259
         12        90    200
    

    It's a bit faster than using pivot_table, and about the same speed or slightly slower than using groupby.

提交回复
热议问题