如何加速函数通过多组参数?

2024-10-01 00:26:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你有一个这样的函数,一些数据=df:

function_(df, parameter_a, parameter_b, parameter_c)

参数本身就是元素列表(字符串、日期时间对象)。结果是一个小数据帧,最多1列x 25行

result_ = function_(df, [a, b, c], [d, f], [x, y, c])
%timeit result_
10000000 loops, best of 3: 37.5 ns per loop

假设您至少有1000组参数来运行函数,现在它们的存储方式如下:

parameter_sets = [('set_1', function_(df, [a, b, c], [d, f], [x, y, c])),
                  ('set_2', function_(df, [b, c, d], [a, b], [x, x, x])),
                   ...
                   ...
                  ('set_1000', function_(df, [b, b, d], [b, b], [x, y, y]))]

如果要运行所有参数集并合并每个输出的结果,请执行以下操作:

def run1000_function():
    parameter_sets = [('set_1', function_(df, [a, b, c], [d, f], [x, y, c])),
                      ('set_2', function_(df, [b, c, d], [a, b], [x, x, x])),
                       ...
                       ...
                      ('set_1000', function_(df, [b, b, d], [b, b], [x, y, y]))]

    output_d = dict(parameter_sets) #probably unnecessary, but used for convinience
    for key, df in output_d.items():
        df['Name'] = key  #to associate the set name with the output

    final_result = pd.concat(parameter_sets.values(), axis=0)

    return final result

所有这些工作都完全符合预期,但问题是这需要花费太多时间。当我运行run1000\u function()时,需要20多分钟。运行“参数集”列表似乎有问题。问题是如何存储和读取这些参数集,从而加快整个过程?你知道吗


Tags: 数据key函数df列表foroutput参数