Split and merge 2 columns pandas

Question:

Is it possible to have this kind of disposition in pd.DataFrame :
enter image description here

Asked By: ArrowRise

||

Answers:

Create DataFrame by constructor with MultiIndex.from_product:

data = [('Mary',20, 'John', 22)]
df = pd.DataFrame(data,
                  columns=pd.MultiIndex.from_product([['MALE','FEMALE'],['NAME','AGE']]))

Or use header=[0,1] if need MultiIndex from header in excel file:

df = pd.read_excel(file, index_col=[0], header=[0,1])
Answered By: jezrael

for example :
enter image description here

import pandas as pd

dt = pd.read_excel("1.xlsx", header=[0,1])
print(dt.head())
print(dt.columns)

output:

                  id   male    
  Unnamed: 0_level_1   name age
0                  1   mary  19
1                  2  emily  20
MultiIndex([(  'id', 'Unnamed: 0_level_1'),
            ('male',               'name'),
            ('male',                'age')],
           )
Answered By: kerwin xu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.