Numpy Vectorize Wrongly Converts The Output To Be Integer
I am struggling with the following code: import numpy as np e = np.linspace(0, 4, 10) def g(x): if x > 1: return x else: return 0 vg = np.vectorize(g)
Solution 1:
The documentation for np.vectorize
explains:
The data type of the output of
vectorized
is determined by calling the function with the first element of the input. This can be avoided by specifying theotypes
argument.
The first element of your input is 0.0
, which returns the integer 0
, so as far as numpy
knows, you want an integer dtype. As you discovered, if you change this to 0.0
so you're not changing the return type, it'll behave. Alternatively you can specify otypes
:
>>>vg = np.vectorize(g)>>>vg(e)
array([0, 0, 0, 1, 1, 2, 2, 3, 3, 4])
>>>vg = np.vectorize(g, otypes=[np.float64])>>>vg(e)
array([ 0. , 0. , 0. , 1.33333333, 1.77777778,
2.22222222, 2.66666667, 3.11111111, 3.55555556, 4. ])
Solution 2:
@amiragha
Python is looking at your input variables as ints as well, so if you wanted to keep everything float64 you would need to specify all necessary "numbers" as floats.
Post a Comment for "Numpy Vectorize Wrongly Converts The Output To Be Integer"