简体   繁体   English

合并具有不同列级别的两个数据框

[英]Merging two dataframes with different level of columns

I have two dataframes, df1 and df2 that I want to merge, both have col[0] level and col[1] level.我有两个要合并的数据框 df1 和 df2,它们都有 col[0] 级别和 col[1] 级别。 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:这是我的 dfs 的样子,我需要的结果在右边:

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.两个 dfs 都很大并且具有相同数量的 level0 列,具有相同的名称。 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.有类似问题的人大多用 .concat 或 .join 解决了他们,这些确实合并了我的 dfs,但他们没有给我我需要的结果。 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.提前致谢。

You can try concat dataframes on columns and then sort the columns您可以尝试在列上连接数据框,然后对列进行排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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