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

Add label/multi-index on top of columns

Context: I’d like to add a new multi-index/row on top of the columns. For example if I have this dataframe:

tt = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]})

Desired Output: How could I make it so that I can add "Table X" on top of the columns A,B, and C?

   Table X
   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9

Possible solutions(?): I was thinking about transposing the dataframe, adding the multi-index, and transpose it back again, but not sure how to do that without having to write the dataframe columns manually (I’ve checked other SO posts about this as well)

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

Thank you!

>Solution :

If you want a data frame like you wrote, you need a Multiindex data frame, try this:

import pandas as pd

# you need a nested dict first 
dict_nested = {'Table X': {'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]}}

# then you have to reform it 
reformed_dict = {}
for outer_key, inner_dict in dict_nested.items():
    for inner_key, values in inner_dict.items():
        reformed_dict[(outer_key, inner_key)] = values
  
# last but not least convert it to a multiindex dataframe
multiindex_df = pd.DataFrame(reformed_dict)

print(multiIndex_df)
# >>   Table X      
# >>         A  B  C
# >> 0       1  4  7
# >> 1       2  5  8
# >> 2       3  6  9
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