如何在循环中更新数据框中的值?

时间:2019-09-24 12:08:31

标签: python pandas

我正在尝试逐行更新评分。我有一个球员数据框,所有数据框都以相同的评分开头。对于每场比赛,我都希望评分改变。另一个数据框包含每个匹配项的结果。

import pandas as pd 

gamesdata = [['paul','tom'],['paul','lisa'],['tom','paul'],['lisa','tom'],['paul','lisa'],['lisa','tom'],['paul','tom']] 

games = pd.DataFrame(gamesdata, columns = ['Winner', 'Looser']) 

playersdata= ['lisa','paul','tom']

players = pd.DataFrame(playersdata, columns = ['Name']) 

mean_elo = 1000
elo_width = 400
k_factor = 64

players['elo'] = mean_elo

def update_elo(winner_elo, loser_elo):
    expected_win = expected_result(winner_elo, loser_elo)
    change_in_elo = k_factor * (1-expected_win)
    winner_elo += change_in_elo
    loser_elo -= change_in_elo
    return winner_elo, loser_elo

def expected_result(elo_a, elo_b):
    expect_a = 1.0/(1+10**((elo_b - elo_a)/elo_width))
    return expect_a

for index, row in games.iterrows():
    winnername = row['Winner']    
    losername = row['Looser']    
    web = players['elo'].loc[players['Name'] == winnername].values[0]
    wIndex = players.loc[players['Name'] == winnername]
    #I want to return just the index, so I can update the value
    print(wIndex)

    leb = players['elo'].loc[players['Name'] == losername].values[0]
    print('Winner Elo before: ' + str(web))
    winner_elo, looser_elo = update_elo(web, leb)
    print('Winner Elo after: ' + str(winner_elo))
    #here I want to update value
    #players.at[wIndex,'elo']=winner_elo  

我正在尝试使用

更新玩家表中的值
players.at[wIndex,'elo']=winner_elo  

但是我很难用下面的代码来获取索引:

wIndex = players.loc[players['Name'] == winnername]

1 个答案:

答案 0 :(得分:0)

找到了解决方法:

 wIndex = players.loc[players['Name'] == winnername].index.values

不敢相信我错过了