Why numpy.vectorize calls vectorized function more times than elements in the vector?

44 views Asked by At

When we call vectorized function for some vector, for some reason it is called twice for the first vector element. What is the reason, and can we get rid of this strange effect (e.g. when this function needs to have some side effect, e.g. counts some sum etc)

Example:

import numpy

@numpy.vectorize
def test(x):
    print(x)

test([1,2,3])

Result:

1
1
2
3

numpy 1.26.4

1

There are 1 answers

3
mozway On BEST ANSWER

This is well defined in the vectorize documentation:

If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs.

If you don't want this, you can define otypes:

import numpy

def test(x):
    print(x)
    
test = numpy.vectorize(test, otypes=[float])
test([1,2,3])

1
2
3

In any case, be aware that vectorize is just a convenience around a python loop. If you need to have side effects you might rather want to use an explicit python loop.