简体   繁体   中英

lining up several pandas dataframes

I have three data frames (A, B, C) of the following type

          2006   2007   2008   2009   2010   2011   
Age                                                                         
     0    1556   1623   5943   6133   6111   6345   
     1    5707   5838   0355   6049   2366   5828  
     2    5616   5770   5899   6080   6137   6303   
     3    5564   5593   8129   9388   1341   6215
     4    5702   5598   7030   8576   9827   2007

I would like to get them into one dataframe with the following design (multi-index0

           A     B     C
Year Age
2006 0    1556  3532   23
     1    5707  4352   53
     2    5616  2533   67
...
2011 3    6215  4255   55
     4    9827  3333   50

Any suggestions?

Cheers, Mike

You can use concat with unstack :

df1 = pd.DataFrame({
'2010': [6111, 2366, 6137, 1341, 9827],
'2007': [1623, 5838, 5770, 5593, 5598], 
'2008': [5943, 355, 5899, 8129, 7030], 
'2011': [6345, 5828, 6303, 6215, 2007], 
'2006': [1556, 5707, 5616, 5564, 5702], 
'2009': [6133, 6049, 6080, 9388, 8576]})

print (df1)
   2006  2007  2008  2009  2010  2011
0  1556  1623  5943  6133  6111  6345
1  5707  5838   355  6049  2366  5828
2  5616  5770  5899  6080  6137  6303
3  5564  5593  8129  9388  1341  6215
4  5702  5598  7030  8576  9827  2007

df2 = df1*2
df3 = df1*3
print (pd.concat([df1.unstack(),df2.unstack(),df3.unstack()], axis=1, keys=list('ABC'))
         .rename_axis(('Year','Age')))

             A      B      C
Year Age                    
2006 0    1556   3112   4668
     1    5707  11414  17121
     2    5616  11232  16848
     3    5564  11128  16692
     4    5702  11404  17106
2007 0    1623   3246   4869
     1    5838  11676  17514
     ...

Or concat with stack , but then is necessary swaplevel with sort_index , last rename levels names by rename_axis :

print (pd.concat([df1,df2,df3], axis=1, keys=list('ABC'))
         .stack()
         .swaplevel(0,1)
         .sort_index()
         .rename_axis(('Year','Age')))

             A      B      C
Year Age                    
2006 0    1556   3112   4668
     1    5707  11414  17121
     2    5616  11232  16848
     3    5564  11128  16692
     4    5702  11404  17106
2007 0    1623   3246   4869
     1    5838  11676  17514
     2    5770  11540  17310
     3    5593  11186  16779
     4    5598  11196  16794
2008 0    5943  11886  17829
     1     355    710   1065
     2    5899  11798  17697
     ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM