熊猫-将值从一个数据框映射到另一个

时间:2020-10-12 20:16:58

标签: pandas

我有这个df:

 df_selected = pd.DataFrame({'player':['Keno', 'Filipe Luís', 'Thiago Galhardo'],
                             'selected': [2868.755, 776.147, 2696.853],
                             'ranking':[1,3,2]})

打印:

            player        selected  ranking
0             Keno        2868.755        1
1      Filipe Luís         776.147        3
2  Thiago Galhardo        2696.853        2

和这个:

df_player = pd.DataFrame({'name':['Keno', 'Filipe Luís', 'Thiago Galhardo', 'SomePlayer'],
                    'team': ['Atlético-MG', 'Flamengo', 'Internacional', 'SomeTeam']})

打印:

            player           team
0             Keno    Atlético-MG
1      Filipe Luís       Flamengo
2  Thiago Galhardo  Internacional
3           Fulano   TimeQualquer

现在我想检查来自df_player的给定玩家是否在df_selected中,如果是,则获取其排名位置并将其添加到df_player的新列中。如果玩家不在df_selected中,则将0值添加到其排名中。我尝试过:

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

但是它不起作用,并且必须 有一种更简单的映射这些项目的方法。

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

我想念什么?

2 个答案:

答案 0 :(得分:0)

这就是我的方法。

merge_dict = dict(zip(df_selected['player'], df_selected['ranking']))
df_player['ranking'] = df_player['player'].map(merge_dict)

我认为这可以解决您的问题,并且比您的for循环快得多。

答案 1 :(得分:0)

使用player; rankingdf_selecteddict(zip())map创建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