'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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | richardec |
