Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas multi-level index series: index value convert to dataframe columns name

Pandas question: I have a multi-level index series as following

index1    index2
A         2022-01-01    1.0
          2022-01-02    2.0
          2022-01-03    3.0
          2022-01-04    4.0
B         2022-01-01    5.0
          2022-01-02    6.0
          2022-01-03    7.0
          2022-01-04    8.0

change it into a single level dataframe as following

              A       B
index2
2022-01-01    1.0     5.0
2022-01-02    2.0     6.0
2022-01-03    3.0     7.0
2022-01-04    4.0     8.0

I know that a set of for loop will do the trick,
but is there any simple and elegant way to implement this?
please help here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Series.unstack with level=0:

new_df = s.unstack(level=0)

Output:

>>> new_df
index1        A    B
index2              
2022-01-01  1.0  5.0
2022-01-02  2.0  6.0
2022-01-03  3.0  7.0
2022-01-04  4.0  8.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading