numpy向量化函数的返回dtype [英] Returned dtype of numpy vectorized function

查看:136
本文介绍了numpy向量化函数的返回dtype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对向量化函数返回的numpy数组的dtype有问题.我的函数返回一个数字,最终是一个分数.奇怪的是,分数的位置似乎会影响返回的dtype.如果函数返回小数,我希望类型始终为object.

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)

这是一个错误还是应该可以这样工作?我在Enthought Canopy Python 2.7.6上使用numpy 1.9.2.

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.

谢谢您的解释!

推荐答案

文档指出:

除非已指定,否则通过评估输入的第一个元素来确定输出类型."

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

您可以通过otypes arg指定所需的输出类型,例如:

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

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

这篇关于numpy向量化函数的返回dtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆