Reputation: 10033
I have this df:
df_selected = pd.DataFrame({'player':['Keno', 'Filipe Luís', 'Thiago Galhardo'],
'selected': [2868.755, 776.147, 2696.853],
'ranking':[1,3,2]})
which prints:
player selected ranking
0 Keno 2868.755 1
1 Filipe Luís 776.147 3
2 Thiago Galhardo 2696.853 2
and this one:
df_player = pd.DataFrame({'name':['Keno', 'Filipe Luís', 'Thiago Galhardo', 'SomePlayer'],
'team': ['Atlético-MG', 'Flamengo', 'Internacional', 'SomeTeam']})
which prints:
player team
0 Keno Atlético-MG
1 Filipe Luís Flamengo
2 Thiago Galhardo Internacional
3 Fulano TimeQualquer
Now I would like to check if a given player from df_player
is in df_selected
and, if so, fetch its ranking position and add it to a new column in df_player
. If the player is not in df_selected
, then add 0 value to its ranking. I've tried:
for ind, player in df_player.iterrows():
for index, selected in df_selected.iterrows():
if player.player == selected.player:
df_player['ranking'].iloc[ind] = selected.ranking
else:
df_player['ranking'].iloc[ind] = 0
But it is not working, and there must be a simpler way of mapping those items.
Desired result for player_df
:
player team ranking
0 Keno Atlético-MG 1
1 Filipe Luís Flamengo 3
2 Thiago Galhardo Internacional 2
3 SomePlayer SomeTeam 0
What am I missing?
Upvotes: 1
Views: 239
Reputation: 26676
create dictionary of player; ranking
from df_selected
using dict(zip())
and map
to df_player['name']
df_player['ranking']=df_player['name'].map(dict(zip(df_selected.player,df_selected.ranking))).fillna(0).astype(int)
print(df_player)
name team ranking
0 Keno Atlético-MG 1
1 Filipe Luís Flamengo 3
2 Thiago Galhardo Internacional 2
3 SomePlayer SomeTeam 0
Upvotes: 1
Reputation: 1063
Here's how I do it.
merge_dict = dict(zip(df_selected['player'], df_selected['ranking']))
df_player['ranking'] = df_player['player'].map(merge_dict)
I think that solves your problem, and will be much faster than your for loop.
Upvotes: 0