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

Pandas, Multi Column Table

Am trying to create a multi-column table, meaning a column has three sub-columns.

I tried a solution from this: How to Insert a List of Data into Pandas Multi-Index Dataframe

But the thing is that it passes a list, each item in the list corresponds to a column; i want to pass a data frame and align the values to each sub column.

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

med = pd.DataFrame({
      'Gold':[54, 37, 37, 14, 19, 19, 9, 10, 2],
      'Silver': [42, 40, 26, 16, 22, 14, 8, 9, 9],
      'Bronze': [41, 49, 29, 32, 33, 12, 9, 7, 11],
})

colnames = ['Masculine']

cols = pd.MultiIndex.from_product([colnames, ['Gold', 'Silver', 'Bronze']])

df = pd.DataFrame([med], columns=cols)

What i need is that "Masculine" appears to the top of that "med" Dataframe and the values are aligned

>Solution :

Do you want to generate a MultiIndex?

You can use concat:

df = pd.concat({'Masculine': med}, axis=1)

# OR
df = pd.concat([med], keys=colnames, axis=1)

output:

  Masculine              
       Gold Silver Bronze
0        54     42     41
1        37     40     49
2        37     26     29
3        14     16     32
4        19     22     33
5        19     14     12
6         9      8      9
7        10      9      7
8         2      9     11
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