TG_01
TG_01

Reputation: 83

Python Pandas Multi-index Column: Set first level of header column as index

I have a pandas dataframe with multi-index column headers that looks like this:

enter image description here

I would like it to look like this:

enter image description here

Upvotes: 2

Views: 1053

Answers (2)

Wilian
Wilian

Reputation: 1257

df = df.unstack(level=0).unstack(level=1)

output:

                 1     2     3
A 2021-12-11  52.3  64.9  86.8
B 2021-12-11  32.3  12.6  14.7

Upvotes: 1

Corralien
Corralien

Reputation: 120391

Try stack and swaplevel:

>>> df
            A        B      
            1  2  3  1  2  3
11/12/2021  1  2  3  4  5  6

>>> df.stack(level=0).swaplevel()
              1  2  3
A 11/12/2021  1  2  3
B 11/12/2021  4  5  6

Upvotes: 2

Related Questions