Skip to content
Advertisement

How to vectorize a function with lists as argument?

I need help vectorizing a function in numpy. In Julia, I can do something like that:

JavaScript

which returns

JavaScript

It takes one sublist at a time from the iterables and expands nothing.

In Python, I just can’t get to have a similar behaviour. I tried:

JavaScript

but it returns:

JavaScript

If I do:

JavaScript

I get back:

JavaScript

I tried with excluded parameter, but il excludes the whole array:

JavaScript

prints:

JavaScript

By the way, the actual function is a sklearn function, not a lambda one.

Advertisement

Answer

You gave it a (2,2), (2,2) and scalar arguments. np.vectorized called your function 4 times, each time with a tuple of values from those 3 (broadcasted together).

You also see that with the print version. There’s an additional tuple at the start, used to determine the return dtype, which in this case is a list, so dtype=object.

With the exclude it doesn’t iterate on the values of the 1st argument, rather it just passes it whole.

Here’s the right way to create your list of lists:

JavaScript

If we add a signature (and otypes):

JavaScript

Now it calls the function only twice. But the result is much slower. Read, and reread, the notes about performance.

If we make the list arguments into arrays first:

JavaScript

the signature f returns the same thing, showing that vectorize does convert the lists to arrays:

JavaScript

If we passed the arrays to the list comprehension, we can get:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement