简体   繁体   English

在 MultiIndex 列值上合并 Pandas DataFrames

[英]Merging Pandas DataFrames on MultiIndex column values

I have two multi level column dataframes.我有两个多级列数据框。

import pandas as pd
df1 = pd.DataFrame({'col1':[1,1,2,2],'col2':[10,10,20,20]})
df1.columns = pd.MultiIndex.from_product([['df1_labels'],df1.columns])
df1

 df1_labels
   col1 col2
0   1   10
1   1   10
2   2   20
3   2   20

df2 = pd.DataFrame({'col3':[100,200],'col4':[10,20]})
df2.columns = pd.MultiIndex.from_product([['df2_labels'],df2.columns])
df2

   df2_labels
   col3  col4
0   100  10
1   200  20

I would like to merge them on the values in colunm 'df1_labels','col2' in df1 and column 'df2_labels','col2' in df2.我想将它们合并到 df1 列 'df1_labels','col2' 和 df2 列 'df2_labels','col2' 中的值上。 My expected result would be:我的预期结果是:

  df1_labels  df2_labels
  col1  col2  col3  col4
0   1   10    100    10
1   1   10    100    10
2   2   20    200    20
3   2   20    200    20

I have tried this:我试过这个:

df3 = pd.merge(df1,df2, left_on=('df1_labels','col2'), right_on=('df2_labels','col4'))
df3

And this:和这个:

df3 = pd.merge(df1,df2, left_on=['df1_labels','col2'], right_on=['df2_labels','col4'])
df3

Both giving me the following error:两者都给了我以下错误:

ValueError: The column label 'df2_labels' is not unique. ValueError:列标签“df2_labels”不是唯一的。 For a multi-index, the label must be a tuple with elements corresponding to each level.对于多索引,标签必须是一个元组,每个级别对应的元素。

I must be doing something wrong syntactically.我一定是在语法上做错了什么。 With single column levels it works:使用单列级别它可以工作:

pd.merge(pd.DataFrame({'col1':[1,1,2,2],'col2':[10,10,20,20]}),
         pd.DataFrame({'col3':[100,200],'col4':[10,20]}), 
         left_on='col2',right_on='col4')

 col1 col2 col3 col4
0   1   10  100 10
1   1   10  100 10
2   2   20  200 20
3   2   20  200 20

Any help would be welcomed!欢迎任何帮助!

For me working add [] for tuples :对我来说,为tuples添加[]

df = pd.merge(df1,df2, left_on=[('df1_labels','col2')], right_on=[('df2_labels','col4')])
print (df)
  df1_labels      df2_labels     
        col1 col2       col3 col4
0          1   10        100   10
1          1   10        100   10
2          2   20        200   20
3          2   20        200   20

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

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