python 在函数调用之间重置可变全局数据帧

python reset mutable global dataframe between function calls

我有两个数据帧,'matches_df' 和 'ratings_df'。 matches 数据框存储了两人游戏的玩家、日期和比赛的获胜者。评级数据框存储每个玩家的当前评级,从任意值开始。我想更新这个框架,然后再重置它。

matches_df

date | player_1 | player_2 | winner
1/11    'A'         'B'        'A'
2/11    'C'         'B'        'C'
3/11    'A'         'D'        'A'
4/11    'A'         'C'        'C'

ratings_df

player | rating
'A'       1000
'B'       1000
'C'       1000
'D'       1000

我有一个执行以下操作的算法更新评级 (sudocode)。

def update_ratings(match,parameter):
    #(1) use current ratings to predict the likelihood of either player winning the match 
    #(2) using the outcome of the match to update player ratings 
    #(3) update the two players current ratings in the global dataframe based on the result of the match. 
    #(4) Return the square of the forecast's prediction error.

我想比较不同参数值在模型预测准确度上的表现。但是,我正在努力复制 'ratings' 数据框或在函数调用之间重置评级数据框。我正在使用以下代码来计算给定参数值的性能:

def calc_brier(parameter,matches_df):
    #reset dataframe to initial values (1000 for all players)
    start_ratings = np.repeat(1000.0,len(unique_players))
    ratings_df = pd.DataFrame(data=[start_ratings],columns=unique_players)
    brier = 0
    for index, row in matches_df.iterrows():
        brier += update_ratings(row,parameter)
    return brier

但是,这并没有给出正确的结果。调用 'calc_brier' 函数时不会重置全局评级数据框,因此如果使用相同的参数多次调用我的 calc_brier 函数就会不一致。我应该怎么做才能正确重置全局评级数据框 before/after 调用 'calc_brier',或者使用替代结构来实现比较不同参数值性能的最终目标?

如果我使用字典而不是数据框来存储评分,它会起作用。这是有效的版本(评级 df 现在是一个字典,名称作为键,评级作为从 1000 开始的值)。不确定原始代码有什么问题。

def calc_brier(parameter):
    for player in unique_players:
        ratings_dict[player]=1000.0
    brier = 0
    for index, row in matches_df.iterrows():
        brier += update_ratings(row,k_factor)
    return brier