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

Reshaping Multi Indexed DF

I have a dataframe that is structured like so (similar to a pivot table):

A B December 2022 January 2023
A1 B1 100 200
A1 B2 101 201

I’d like to and transpose my dataframe in a way so it reads:

Month A B Value
December 2022 A1 B1 100
December 2022 A1 B2 101
January 2023 A1 B1 200
January 2023 A1 B2 201

etc. I’ve attempted

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

df.T

But it gives me:

A A1 A1
B B1 B2
December 2022 100 101
January 2023 200 201

>Solution :

You should use pd.melt:

>>> df.melt(id_vars=['A', 'B'], var_name='Month', value_name='Value')
    A   B          Month  Value
0  A1  B1  December 2022    100
1  A1  B2  December 2022    101
2  A1  B1   January 2023    200
3  A1  B2   January 2023    201

then to reorder columns, you can use this hack:

>>> df.melt(id_vars=['A', 'B'], var_name='Month', value_name='Value') \
      .set_index('Month').reset_index()

           Month   A   B  Value
0  December 2022  A1  B1    100
1  December 2022  A1  B2    101
2   January 2023  A1  B1    200
3   January 2023  A1  B2    201
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