python - Join/Merge two Pandas dataframes and use columns as multiindex -


i have 2 dataframes kpis date. want combine them , use multiindex each kpi can compared other 2 df.

like this:

concat dataframes , swap multiindex

i have tried extract each kpi series, rename series accordingly (df1, df2) , concatenating them using keys argument of pd.concat doesn't seems work.

any appreciated.

let's use pd.concat keys parameter, swaplevel, , sort_index:

df1 = pd.dataframe({'a':['a0','a1','a2'],'b':['b0','b1','b2'],'c':['c0','c1','c2']},index=pd.date_range('2017-01-01',periods=3, freq='m')) df2 = pd.dataframe({'a':['a3','a4','a5'],'b':['b3','b4','b5'],'c':['c3','c4','c5']},index=pd.date_range('2017-01-01',periods=3, freq='m'))  pd.concat([df1,df2],axis=1,keys=['df1','df2']).swaplevel(0,1,axis=1).sort_index(axis=1) 

output:

                   b       c                df1 df2 df1 df2 df1 df2 2017-01-31  a0  a3  b0  b3  c0  c3 2017-02-28  a1  a4  b1  b4  c1  c4 2017-03-31  a2  a5  b2  b5  c2  c5 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -