nicmet
nicmet

Reputation: 520

Pandas: reorganizing a dataframe

I have this dataframe with four columns:

df = pd.DataFrame({'name': {1:'Aaron', 2:'Bobby', 3:'Carl'},  
               'job': {1:'mechanic', 2:'carpenter', 3:'plumber'},
               'experience': {1:12, 2:23, 3:14},
               'type': {1:'owner',2:'contractor',3:'assistant'}},
              columns=['name','job','experience','type'])
df

I'd like to use pandas to reshape the data so that names is the index and job is a column header, with experience and type as subheaders for the columns -- i.e., under the mechanic column, there would be a sub-column for experience and type, and the same under the carpenter column, etc.

I've tried using

df.set_index(['name', 'job']).unstack('job') 

But then experience and type are the top level rather than job. Is there a way I can change this to make job the top level of column header?

Thanks for the help!

Upvotes: 2

Views: 361

Answers (1)

jezrael
jezrael

Reputation: 862851

You can use MultiIndex.swaplevel:

df.columns = df.columns.swaplevel(0,1)
print (df)
job    carpenter   mechanic    plumber   carpenter mechanic    plumber
      experience experience experience        type     type       type
name                                                                  
Aaron        NaN       12.0        NaN        None    owner       None
Bobby       23.0        NaN        NaN  contractor     None       None
Carl         NaN        NaN       14.0        None     None  assistant

Upvotes: 4

Related Questions