Python数据框无法按索引合并

4

我正尝试合并2个数据框,但出现了KeyError: Player_Id错误。

我尝试基于Striker_IdPlayer_Id进行合并。

这是我数据框的外观:

enter image description here

合并代码:

player_runs.merge(matches_played_by_players,left_on='Striker_Id',right_on='Player_Id',how='left')

我做错了什么?

2个回答

4

看起来您的问题是想要按索引合并,但是您将它们视为列了?尝试稍微修改一下合并代码 -

player_runs.merge(matches_played_by_players,
                  left_index=True,
                  right_index=True,
                  how='left')

此外,请确保两个索引的类型相同(在这种情况下,考虑使用int而不是str)。

player_runs.index = player_runs.index.astype(int)

And,

matches_played_by_players.index = matches_played_by_players.index.astype(int)      

两个索引都是 Int64 类型,我运行了你的代码,出现了一个新的错误:ValueError: left_index parameter must be of type bool, not <class 'str'> - Jaskaran Singh Puri
@JaskaranSinghPuri 你应该输入 True,而不是 "True" :-) - cs95
完成了!谢谢,但我们没有定义左右索引的index_name,它是怎么知道要在它们上面连接的? - Jaskaran Singh Puri
@JaskaranSinghPuri 指定您要加入的索引即可。这是 pandas 执行合并所需的所有信息 :) - cs95

2

你基本上是在不存在的列上进行合并。这是因为 reset_index 创建了一个新的数据框,而不是改变应用它的数据框。当使用 reset_index 时设置参数 inplace=True 应该可以解决这个问题,或者在每个数据框的索引上进行合并。例如:

pd.merge(df1,df2,left_index=True,right_index=True,how='left')

我只是在解释错误背后的原因。 - sgDysregulation

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接