【问题标题】:Pandas Dataframe Faster ApproachPandas Dataframe 更快的方法
【发布时间】:2018-01-08 13:39:54
【问题描述】:

我的代码中有一部分需要从一个数据帧中获取值,并将其应用于另一个数据帧。例如,假设第一个数据框是学生数据框的分数,第二个是学生数据框的组合。我想遍历每个组合_DF,得到学生的分数,然后为那一行总结。

print scores_DF

Name     Value
Dennis   39.66
James    45.38
Leo      40.63
Joe      20.10
etc...


print combination_DF

name1     name2     name3  
Dennis    James     Leo    
Leo       Joe       Dennis  

现在我的程序正在遍历每个combination_DF,查找每个名称的分数并将其添加到一个包含每个组合总分的列,这确实减慢了我的程序,因为我处理了数千个条目。所以它看起来像这样......

    for index,row in combination_df.iterrows():
        value0 = scores_df[scores_df['Name'] == row[0]]
        value1 = scores_df[scores_df['Name'] == row[1]]
        value3 = scores_df[scores_df['Name'] == row[2]]
        total_score =  value0['Value'].values + value1['Value'].values+ value2['Value'].values

我是 Pandas 的新手,当时这是我知道的唯一方法,但随着我的程序不断发展,这部分代码需要尽可能快地工作,谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我认为你需要 groupby 并首先聚合 sum 然后 replacesum

    s = scores_DF.groupby('Name')['Value'].sum()
    
    combination_DF['sum'] = combination_DF.replace(s).sum(axis=1)
    

    替代map + stack + unstack:

    combination_DF['sum'] = combination_DF.stack().map(s).unstack().sum(axis=1)
    
    print (combination_DF)
        name1  name2   name3     sum
    0  Dennis  James     Leo  125.67
    1     Leo    Joe  Dennis  100.39
    

    详情:

    print (combination_DF.replace(s))
       name1  name2  name3
    0  39.66  45.38  40.63
    1  40.63  20.10  39.66
    

    【讨论】:

      【解决方案2】:

      你可以更花哨一点。首先,让我们创建一个函数

      f = lambda x: scores_DF.ix[x]["Value"]
      

      用 f("Dennis") 测试它...

      不需要迭代:

      combintation.apply(f, axis=1).sum(axis=1)
      

      应该可以 更多铁杆用户直接插入 f 作为 apply 函数的参数...

      【讨论】:

        猜你喜欢
        • 2021-09-30
        • 2019-05-25
        • 2019-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        相关资源
        最近更新 更多