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

Reorganise Columns in MultiIndex Matrix Pandas

I have a pandas data frame where every row has a some readings from a sensor at different altitudes. I managed to get these readings in a matrix using the df.pivot function, where the index the identifier is, the columns the different altitude and three values of data at those altitudes.

My matrix looks like this (Data is level 0 column header, Alt is level 1)

Data_1. Data_2 Data_3.
Alt_1 – Alt_2 – Alt_3 – … Alt-1 – Alt_2 – Alt_3 – … Alt_1 – Alt_2 – Alt_3 – …

What I want is to get the multi-index columns rearranged so that the level 0 as the altitudes and the level 1 is the data.

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

I tried various ways of changing levels, renaming tuples etc.. but found nothing useful.
I expect the table to look like this:

Alt 1. Alt_2 Alt_3
Data_1-Data_2-Data_3 Data_1-Data_2-Data_3 Data_1-Data_2-Data_3 Data_1-Data_2-Data_3

>Solution :

I think this is where swaplevel shines. Try with:

df.swaplevel(axis=1)

Example:

df = pd.DataFrame(
    {"Grade": ['A','B','C','D','E','F','G','H','I']},
    index=[
        ['Data_1']*3 + ['Data_2']*3 + ['Data_3']*3,
        ['Alt_1','Alt_2','Alt_3']*3]).T

Which looks as follows:

      Data_1             Data_2             Data_3            
       Alt_1 Alt_2 Alt_3  Alt_1 Alt_2 Alt_3  Alt_1 Alt_2 Alt_3
Grade      A     B     C      D     E     F      G     H     I

After the transformation:

df.swaplevel(axis=1)

We get:

       Alt_1  Alt_2  Alt_3  Alt_1  Alt_2  Alt_3  Alt_1  Alt_2  Alt_3
      Data_1 Data_1 Data_1 Data_2 Data_2 Data_2 Data_3 Data_3 Data_3
Grade      A      B      C      D      E      F      G      H      I
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