Mark van der Wilk
Mark van der Wilk

Reputation: 807

Pandas hierarchical columns

Say I have two dataframes, is it possible to concatenate them by columns, but with the second one appearing as a single column in the concatenated dataframe?

Pictorially, I'm looking for:

df_A:
C1 C2 C3
1  2  3
11 22 33

df_B:
D1 D2 D3
3  4  5
33 44 55

Concatenated:
C1 C2 C3 df_B
         D1   D2   D3
1  2  3  3    4    5
11 22 33 33   44   55

Upvotes: 1

Views: 286

Answers (1)

unutbu
unutbu

Reputation: 880987

You can contruct a MultiIndex to created a DataFrame with the desired appearance:

import pandas as pd
df_A = pd.DataFrame([(1,2,3), (11,22,33)], columns=['C1', 'C2', 'C3'])
df_B = pd.DataFrame([(3,4,5), (33,44,55)], columns=['D1', 'D2', 'D3'])
result = pd.concat([df_A, df_B], axis=1)
result.columns = pd.MultiIndex.from_tuples([(col,'') for col in df_A] 
                                           + [('df_B', col) for col in df_B])
print(result)

yields

   C1  C2  C3 df_B        
                D1  D2  D3
0   1   2   3    3   4   5
1  11  22  33   33  44  55

Upvotes: 4

Related Questions