pandas: how to pivot a table with defined levels

Viewed 73

My case is slightly different to what I have found so far online. I would like to pivot a pandas dataframe with a specific levels in the header. The pivot_table function requires values to be numeric, and the pandas.pivot function does not seem to do exactly what I want.

This is the starting code.

import pandas as pd
df = pd.DataFrame({'session':['2017', '2018','2017','2018','2017','2018'], 'domain':['network', 'network', 'facility', 'facility', 'access', 'access'], 'vendor':['vendorA', 'vendorA', 'vendorB','vendorB','vendorB','vendorB'], 'cost':[10,20,30,40,50,60]})
print df.to_string()
   cost    domain session   vendor
0    10   network    2017  vendorA
1    20   network    2018  vendorA
2    30  facility    2017  vendorB
3    40  facility    2018  vendorB
4    50    access    2017  vendorB
5    60    access    2018  vendorB

What I am after is something like that, where the first column level has only the 'domain' values, the 2nd column level the 'vendor' and 'cost' for each domain per 'session':

domain   network        facility       access 
session  vendor   cost  vendor   cost  vendor   cost
2017     vendorA  10    vendorB  30    vendorB  50
2018     vendorA  20    vendorB  40    vendorB  60
1 Answers
Related