更快的分割 - 应用 - 组合

时间:2018-01-17 16:19:00

标签: python pandas numpy dataframe

我正在开发一个大型函数,可以预测超过N年的数据,然后将数据从宽到长重新整形,最后在返回数据框之前再应用几个操作。大多数函数运行速度非常快,最后4行左右占用函数运行时间的50%以上。由于数据框非常大,我需要减少运行这些基本上是拆分应用组合的线路所花费的时间。

以下是输入的示例:

     df

     Year Number ACost BCost Condition  Data_set Backlog
      1   2002    8       0      10           A      1
      1   2002    6       0      4            A      6
      1   X       0       5      2            B      2
      2   2004    10      0      10           A      0

以下是减慢所有内容的代码,基本上是按照加权平均值进行预测并按群组求和:

     final = df.set_index(['Year',Number, Data_set])
     final = final.sort_index(axis =1)
     final['ACost_cond'] = final['ACost'] * final['Condition']

     final = final.sum(level='Year',Number, Data_set)
     final['Resulting_cond'] = final['ACost_cond'].div(final['ACost'])
      L = final.reset_index()
      L['Final_cond'] = np.where((L['Data_set'] == 'B'),L['Resulting_cond'],L['Condition']) 
      L.drop(['ACost', 'BCost', 'ACost_cond', 'Resulting_cond'], axis =1 , inplace = True)

预期产出:

     L

     Year Number         Final_Condition   Data_set Backlog
      1   2002                7.43             A      7
      1   X                   2                B      2
      2   2004                10               A      0

为这些加速SAC的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

保留对您要分组的列的引用。

c = [df.Year, df.Number, df.Data_set]

接下来,在sum内找到BacklogConditionACost的{​​{1}}。

groupby

接下来,计算i = df[['Backlog', 'Condition', 'ACost']].groupby(c).sum() 的值,这些也需要groupby操作。

Final_condition

最后,j = (df.ACost * df.Condition).groupby(c).sum() / i.ACost i['Final_condition'] = j.fillna(i.Condition) 不需要的列并重置索引。

drop

编辑;试图挤出更多的表现。

i.drop(['Condition', 'ACost'], 1).reset_index()

   Year Number Data_set  Backlog  Final_condition
0     1   2002        A        7         7.428571
1     1      X        B        2         2.000000
2     2   2004        A        0        10.000000
相关问题