Concatenate Two DataFrames With Hierarchical Columns

first case can be ordered arbitrarily among A,B (not the columns, just the order A or B) 2nd should preserve ordering

IMHO this is pandonic!

In [5]: concat(dict(A = A, B = B),axis=1)
Out[5]: 
   A        B      
   a  b  c  a  b  c
0  0  1  2  0  1  2
1  3  4  5  3  4  5
2  6  7  8  6  7  8

In [6]: concat([ A, B ], keys=['A','B'],axis=1)
Out[6]: 
   A        B      
   a  b  c  a  b  c
0  0  1  2  0  1  2
1  3  4  5  3  4  5
2  6  7  8  6  7  8

Here's one way, which does change A and B:

In [10]: from itertools import cycle

In [11]: A.columns = pd.MultiIndex.from_tuples(zip(cycle('A'), A.columns))

In [12]: A
Out[12]:
   A
   a  b  c
0  0  1  2
1  3  4  5
2  6  7  8

In [13]: B.columns = pd.MultiIndex.from_tuples(zip(cycle('B'), B.columns))

In [14]: A.join(B)
Out[14]:
   A        B
   a  b  c  a  b  c
0  0  1  2  0  1  2
1  3  4  5  3  4  5
2  6  7  8  6  7  8

I actually think this would be a good alternative behaviour, rather than suffixes...

Tags:

Python

Pandas