Miyashita Hikaru Miyashita Hikaru - 3 months ago 9
Python Question

concatinate pandas dataframe to multiindex

I have a pandas dataframe like this

df1=pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns=list('ABC'))
df1.index.name="ID1"


df2=pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns=list('ABC'))
df2.index.name="ID2"


so,How can I concatinate like below,this dataframe have multiindex.

A B C
ID1 0 7 5 7
1 6 3 8
2 6 5 4
ID2 0 3 9 7
1 8 7 5
2 3 9 9


I have tried 'pd.concat([df1,df2])' but multiindex hasnt created.

Answer

Concat is correct

pd.concat([df1,df2], keys=['id1', 'id2'])