Python Dataframes没有合并索引

问题描述 投票:2回答:2

我正在尝试合并2个数据帧,但由于某种原因,它正在抛出KeyError: Player_Id

我正在尝试合并Striker_IdPlayer_Id

这就是我的Dataframe的样子

enter image description here

合并代码:

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

我究竟做错了什么?

python pandas dataframe merge
2个回答
4
投票

嗯,从你的问题来看,似乎你正在尝试合并索引,但你把它们视为列?尝试稍微更改合并代码 -

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

此外,请确保两个索引的类型相同(在这种情况下,请考虑 str int?)

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

和,

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

2
投票

你基本上没有合并任何现有的列。这是因为reset_index创建了一个新的数据框,而不是更改它应用的数据框。使用reset_index时设置参数inplace=True应解决此问题,或者合并每个数据帧的索引。即

pd.merge(df1,df2,left_index=True,right_index=True,how='left')
© www.soinside.com 2019 - 2024. All rights reserved.