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

Time:04-26

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.

CodePudding user response:

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
  • Related