Python Dataframes not merging on index

喜欢而已 提交于 2020-01-13 05:56:19

问题


I'm trying to merge 2 dataframes, but for some reason it's throwing KeyError: Player_Id

I'm trying to merge on Striker_Id and Player_Id

This is how my Dataframe looks like

Merge Code:

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

What am I doing wrong?


回答1:


Hmm, from looking at your problem, it seems like you're trying to merge on the indexes, but you treat them as columns? Try changing your merge code a bit -

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

Furthermore, make sure that both indexes are of the same type (in this case, consider strint?)

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

And,

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



回答2:


you're basically merging on none existing columns. this is because reset_index creates a new data-frame rather than changing the data frame it's applied to. setting the parameter inplace=True when using reset_index should resolve this issue, alternatively merge on the index of each data-frame. i.e.

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


来源:https://stackoverflow.com/questions/48026254/python-dataframes-not-merging-on-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!