pandasdataframecrosstab

Pandas change single column head to multi index header - python


I want to take a dataframe that has single head and add mutli-index head columns. The columns that will be multi head are all IDs. I then have IDs and names in a 2nd dataframe.

Here is my example data

df = pd.DataFrame({"A": ['fay','fee','fie','foe']})

df1 = pd.DataFrame(np.random.randint(0,10,size=(4,4)), columns=['012','015','016','018'])
df1 = pd.merge(df,df1, right_index = True, left_index = True)

df2 = pd.DataFrame({'id':['018','015','012','016'], 'name':['boom','bing', 'bota','bada']})
dict_id = dict(zip(df2.id,df2.name))

for the next part how do I make it multilayered like show below?

        bota  bing bada boom
     A  012   015  016  018
____________________________
0   fay   0    3    1    5
1   fee   1    2    9    7
2   fie   5    1    0    3
3   foe   0    7    8    5

Solution

  • Create MultiIndex by Index.map with assign list to columns names:

    df1.columns = [df1.columns.map(dict_id).fillna(''), df1.columns]
    print (df1)
           bota bing bada boom
         A  012  015  016  018
    0  fay    9    7    4    4
    1  fee    2    3    1    1
    2  fie    6    4    5    1
    3  foe    8    6    4    4