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

pandas merge with multiindex columns but single index index

我正在使用 Python 3.8.6 和 pandas 版本 1.2.4

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

            bar   
            one  
index                                                                                
0      0.238307 
1      0.610819 

所以我在执行 pandas 合并

之前准备数据框

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

        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) must equal the number of levels in the index of "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

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

谢谢 马丁

是否如你所愿:

>>> 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中的键数(索引或列数)必须与级别数匹配。

我发现的答案是:

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