Search code examples
pythonnumpyvectorization

How to pass *args in vectorized function


For the usual *args technique in python, but the function is np.vectorized. Normally, *args would work, but when I've vectorized the function and the args are a vector, it thinks the all the rows combined are the arguments rather than each row being the argument. I can obviously have my_function(a,b,c,d,e), but my actual function has many many inputs. How do I do this with the *args technique?

import numpy as np

a = np.random.rand(50,1)
b = np.random.rand(50,1)

args = np.random.rand(50,3)

def my_function(a,b,c,d,e):
    
    result = a * b * c * d * e
    

    return result


my_func_vec = np.vectorize(my_function)
res = my_func_vec(a,b,*args)

# TypeError: my_function() takes 5 positional arguments but 52 were given

Solution

  • Using *args will unpack args along the rows. You want to do it along the columns, so you can transpose first.

    my_func_vec(a, b, *args.T)
    

    But this example doesn't require np.vectorize, and you should reexamine your actual case to see if it needs it. The code is much faster without it.

    %timeit my_function(a, b, *args.T)
    14.8 µs ± 490 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
    %timeit my_func_vec(a, b, *args.T)
    468 µs ± 13.1 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)