-2

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')

Pythona
  • 9
  • 5
  • Hi and welcome Pythona. Please don't post screenshots. Use the codeblock and provide some reproducible data. – Marco_CH Jan 16 '22 at 15:52
  • 1
    i deleted the link. thank you – Pythona Jan 16 '22 at 15:56
  • 1
    Can you explain why the result in your screenshot is not what you want? It looks like the expected result... – SamR Jan 16 '22 at 15:56
  • 1
    no, what i need is company sort at the top, then all columns came under the company. under each company i want to see the total_profit and numberofgoodsold. – Pythona Jan 16 '22 at 15:58
  • 2
    Thanks Pythona, please read: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples . This makes it way easier to help . If you post a reproducible dataset the chance you're getting an answer is much bigger. – Marco_CH Jan 16 '22 at 16:00
  • 1
    Thanks for the update Pythona. Tried to answer your question below. But besides that I'd suggest to read [How to I ask a good question?](https://stackoverflow.com/help/how-to-ask). It really helped me at beginning here. Before it was sometimes quite frustrating, but only because I didn't know some basic rules :-) PS: I upvoted your question now, because I think that a negative vote is no longer appropriate. – Marco_CH Jan 16 '22 at 16:36

1 Answers1

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

Marco_CH
  • 3,243
  • 8
  • 25