【发布时间】:2021-09-01 13:44:27
【问题描述】:
我正在使用 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 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
再说一遍,有些问题我不明白
谢谢 马丁
【问题讨论】:
标签: python pandas dataframe multi-index