pandas 与多索引列合并,但与单索引索引合并

时间:2021-06-16 17:48:39

标签: python pandas dataframe multi-index

我使用 Python 3.8.6 和 pandas 1.2.4 版

我想使用此数据框对前几行进行自连接:

            bar   
            one  
index                                                                                
0      0.238307 
1      0.610819 

所以我在做熊猫合并之前准备数据帧

“左”合并数据如下所示:

        bar   
        one  
0  0.238307  
1  0.610819 

“正确”的合并数据如下所示:

        bar   index1
        one         
0  0.238307      1
1  0.610819      2

现在我尝试合并:

pd.merge(left, right, left_index=True, right_on=('index1',''), suffixes=('_n','_p'))

它抛出一个ValueError: len(right_on) 必须等于“left”索引中的层数

对我来说,这毫无意义。重要的是 ('index1,'') 的值与 left.index

相当

我错过了什么?

我还尝试了以下方法: 左

  index       bar  
              one  
0     0  0.972453 
1     1  0.278209 

        bar  index1
        one         
0  0.972453      1
1  0.278209      2

合并表达式

pd.merge(left,right,left_on=('index',''),right_on=('index1',''),suffixes=('_n','_p'))

错误

 raise KeyError(key)
KeyError: ''

注意

left.loc[:,('index','')]
0    0
1    1
2    2
right.loc[:,('index1','')]
0    1
1    2
2    3

再说一遍,有些问题我不明白

谢谢 马丁

2 个答案:

答案 0 :(得分:0)

是否如您所愿:

>>> pd.merge(dfL, dfR, left_index=True, right_on='index1', suffixes=('_n','_p'))

      bar_n     bar_p index1
        one       one
0  0.610819  0.238307      1

来自 merge documentation如果是 MultiIndex,则其他 DataFrame 中的键数(索引或列数)必须与级别数匹配。

答案 1 :(得分:0)

我发现的答案是:

left=left.set_index(('index',''))
right=right.set_index(('index1',''))
dfJoined=pd.merge(left,right,left_index=True,right_index=True,suffixes=('_n','_p'))

生产

      bar_n     bar_p     
        one       one
1  1.719833 -0.540152 #different random numbers from question above
相关问题