4

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

enter image description here

Merge Code:

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

What am I doing wrong?

2 Answers 2

4

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)      
Sign up to request clarification or add additional context in comments.

4 Comments

both indexes are of Int64, I ran your code, got a new error: ValueError: left_index parameter must be of type bool, not <class 'str'>
@JaskaranSinghPuri you should type True, not "True" :-)
worked! thanks, but we didn't define what is the index_name for left and right index, how did it know to join on them?
@JaskaranSinghPuri Specify that you want to join on the index. That's all the information that pandas needs to perform the merge :)
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')

1 Comment

I was merely explaining the reason behind the error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.