Pandas:按条件将其他 Dataframe 中的值添加到新列中

izkcnapc  于 2022-12-17  发布在  其他
关注(0)|答案(2)|浏览(181)

我有两个包含以下数据的 Dataframe :

fixtures = pd.DataFrame(
    {'HomeTeam': ["A", "B", "C", "D"], 'AwayTeam': ["E", "F", "G", "H"]})

ratings = pd.DataFrame({'team': ["A", "B", "C", "D", "E", "F", "G", "H"], "rating": [
                       "1,5", "0,2", "0,5", "2", "3", "4,8", "0,9", "-0,4"]})

现在我想Map值从ratings["rating"]到各自的队名但我不能得到它工作.是它可能有新的列与ratings appeared到这右边的HomeTeamAwayTeam列?
预期产出:
固定装置:

homeTeam  homeTeamRating  awayTeam  AwayTeamRating  
Team A    1,5             Team E    3
rqqzpn5f

rqqzpn5f1#

您可以用途:

to_replace=dict(zip(ratings.team,ratings.rating)) #create a dict. Key is team name value is rating.
#{'A': '1,5', 'B': '0,2', 'C': '0,5', 'D': '2', 'E': '3', 'F': '4,8', 'G': '0,9', 'H': '-0,4'}

fixtures['homeTeamRating']=fixtures['HomeTeam'].map(to_replace) #use map and  replace team column as a new column.
fixtures['AwayTeamRating']=fixtures['AwayTeam'].map(to_replace)

fixtures=fixtures[['HomeTeam','homeTeamRating','AwayTeam','AwayTeamRating']]

'''
  HomeTeam homeTeamRating AwayTeam AwayTeamRating
0        A            1,5        E              3
1        B            0,2        F            4,8
2        C            0,5        G            0,9
3        D              2        H           -0,4
'''
gcmastyq

gcmastyq2#

如果您需要在现有列上应用一个方法来计算一些值,这些值最终将作为新列添加到现有的DataFrame中,那么pandas.DataFrame.apply()方法应该可以做到这一点。

相关问题