Returned dtype of numpy vectorized function

2019-02-27 10:22发布

问题:

I have an issue regarding the dtype of the returned numpy array of a vectorized function. My function returns a number, eventually a fraction. Strangely the position of the fraction seems to influence the returned dtype. I want the type always to be object if the function returns a fraction.

import numpy as np
from fractions import Fraction

foo = lambda x: Fraction(1, 3) if x < 0.5 else 1
foo_vectorized = np.vectorize(foo)

foo_vectorized([1, 0.3]) # returns array([1, 0])
foo_vectorized([0.3, 1]) # returns array([Fraction(1, 3), 1], dtype=object)

Is this a bug or is it expected to work like this? I use numpy 1.9.2 on Enthought Canopy Python 2.7.6.

Thanks for any explanation!

回答1:

That is exactly as the documentation states:

"The output type is determined by evaluating the first element of the input, unless it is specified."

You can specify the desired output type via the otypes arg, e.g.:

 np.vectorize(foo, otypes=[np.object])


回答2:

This forces the return value to be an object:

foo_vectorized = np.vectorize(foo, otypes=[object])