【问题标题】:python reset mutable global dataframe between function callspython在函数调用之间重置可变全局数据框
【发布时间】:2016-12-30 10:18:04
【问题描述】:

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

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.

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

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 函数,则会出现不一致的情况。我应该怎么做才能在调用“calc_brier”之前/之后正确重置全局评级数据框,或者使用替代结构来实现比较不同参数值性能的最终目标?

【问题讨论】:

    标签: python pandas dataframe global-variables mutable


    【解决方案1】:

    如果我使用字典而不是数据框来存储评分,它会起作用。这是有效的版本(评级 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
    

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      相关资源
      最近更新 更多