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.
我有一个关于向量化函数返回的numpy数组的dtype的问题。我的函数返回一个数字,最后是一个分数。奇怪的是,分数的位置似乎影响了返回的dtype。如果函数返回一个分数,我希望该类型始终是对象。
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.
这是一个错误还是预计会像这样工作?我在Enthought Canopy Python 2.7.6上使用了numpy 1.9.2。
Thanks for any explanation!
谢谢你的解释!
2 个解决方案
#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.:
您可以通过otypes arg指定所需的输出类型,例如:
np.vectorize(foo, otypes=[np.object])
#2
This forces the return value to be an object
:
这会强制返回值为对象:
foo_vectorized = np.vectorize(foo, otypes=[object])
#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.:
您可以通过otypes arg指定所需的输出类型,例如:
np.vectorize(foo, otypes=[np.object])
#2
This forces the return value to be an object
:
这会强制返回值为对象:
foo_vectorized = np.vectorize(foo, otypes=[object])