pivot in pandas: how to edit the columns and rows

i face a problem with pivot in pandas , the total_profit and numberofgoodsold columns are located above company row. i need the company row to be at the top.

in each company the total_profit and the goodsold columns should came under.

this is my code:

data = {'company': ['AMC', 'ER','CRR' , 'TYU'], 'Reg-ID': ['1222','2334','3444', '4566'], 'Total_provit': ['123300','12233', '3444444', '412222'], 'numberofgoodsold':['44','23','67','34']}

d = pd.DataFrame(data)


d.pivot(index = 'Reg-ID', columns = 'company')


Solution 1:

Update, ok then I think this is what you need:

data = {'company': ['AMC', 'ER','CRR' , 'TYU'], 'Reg-ID': ['1222','2334','3444', '4566'], 'Total_provit': ['123300','12233', '3444444', '412222'], 'numberofgoodsold':['44','23','67','34']}

d = pd.DataFrame(data)

d2 = d.pivot(index = 'Reg-ID', columns = 'company')

d2.columns = d2.columns.swaplevel(0, 1)
d2.sort_index(axis=1, level=0, inplace=True)

d2

Output:

enter image description here