Home > Blockchain >  Merging two dataframes with different level of columns
Merging two dataframes with different level of columns

Time:05-01

I have two dataframes, df1 and df2 that I want to merge, both have col[0] level and col[1] level. I need to merge them but I'm not sure how to describe the situation. Maybe a visual example will be much easier to understand. Here is how my dfs look like, and the result I need is on the right:

df1:                |      df2:         |  result I need: df_merged:
    A    B    C     |       A   B   C   |      A      B      C
    x y  x y  x y   |       z   z   z   |      x y z  x y z  x y z
0                   |  0                | 0
1                   |  1                | 1
2                   |  2                | 2

Both dfs are huge and have the same number of level0 columns, with identical names. People with similar problems mostly solved them with .concat or .join, these do merge my dfs but they don't give me the result I need. I have tried many things with no success but I feel like something like these will be the solution I need, I just can't figure it out myself.

pd.concat([df1, df2], axis=0, ignore_index=False)

or

df1.concat(df2).groupby(level=0)

Thanks in advance.

CodePudding user response:

You can try concat dataframes on columns and then sort the columns

df = pd.concat([df1, df2], axis=1).sort_index(axis=1)
  • Related