1

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
1
  • look at crosstabs or pivots. Commented Sep 7, 2022 at 4:52

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

We can build MultiIndex with MultiIndex.from_arrays

df1.columns = pd.MultiIndex.from_arrays([df1.columns.map(dict_id).fillna(''), df1.columns])
print(df1)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.