Multi-index pivoting in Pandas Multi-index pivoting in Pandas python python

Multi-index pivoting in Pandas


If I understand what you are asking I think what you want is pandas.pivot_table(...) which you can use like so:

table = pd.pivot_table(df, index=['item_id', 'hour', 'date'], columns='when', values='quantity')

which with a sample data frame of

    item_id  hour  when      date     quantity0       a     1  before  2015-01-26        251       b     1  before  2015-01-26        142       a     1   after  2015-01-26         43       d     1  before  2015-01-26        434       b     1   after  2015-01-26        305       d     1   after  2015-01-26        12

produces

when                     after  beforeitem_id hour date                     a       1    2015-01-26      4      25b       1    2015-01-26     30      14d       1    2015-01-26     12      43