1

I have a multi-index columns df as below

  stock1        stock2        stock3       
   price volume  price volume  price volume
0      1      2      3      4      5      6
1      2      3      4      5      6      7

I want to reformat it in such a way that it looks like below

df

   price                      volume           
   stock1 stock2 stock3 stock1 stock2 stock3
0      1      3      5      2      4      6
1      2      4      6      3      5      7

How can I achieve it in pandas.

Thanks

1 Answer 1

2

Use DataFrame.swaplevel with DataFrame.sort_index:

df = df.swaplevel(1, 0, axis=1).sort_index(axis=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.