Home > front end >  Add header under two columns of a table
Add header under two columns of a table

Time:11-14

I want to add another header under two columns of a table.

I tried this way but I got InvalidSyntax

table = {
        'Color':color,
        'Continent':continent,
        {'Country':country,
        'Nation':season,}
        'Name':name,
        'Surname':surname,
    }

CodePudding user response:

You could use multiindex as described here. Given the structure you show in your dictionary this should do:

df.columns = pd.MultiIndex.from_tuples([('Color'),('Continent'),('Country','Nation'),('Country','Name'),('Country','Surname')])

For example:

df = pd.DataFrame({'Color':['Red','Green'],
                   'Continent':['Asia','Africa'],
                   'Nation':['China','Egypt'],
                   'Name':['X','Y'],
                   'Surname':['A','B']})
df.columns = pd.MultiIndex.from_tuples([(['Color']),(['Continent']),('Country','Nation'),('Country','Name'),('Country','Surname')])
print(df)

Outputs:

   Color    Continent  Country             
   NaN      NaN        Nation   Name    Surname
0  Red      Asia       China    X       A
1  Green    Africa     Egypt    Y       B
  • Related