Search code examples
pythonpandasdataframemultiple-columnsmulti-index

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.

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