问题描述
我正在为以下代码苦苦挣扎:
将 numpy 导入为 npe = np.linspace(0, 4, 10)定义 g(x):如果 x >1:返回 x别的:返回 0vg = np.vectorize(g)打印(vg(e))
结果如下:
[0 0 0 1 1 2 2 3 3 4]
我还检查了 dtype.似乎vectorize函数正在将类型从float64转换为int64!
np.vectorize
的文档说明:
vectorized
输出的数据类型由调用决定具有输入的第一个元素的函数.这是可以避免的通过指定 otypes
参数.
你输入的第一个元素是0.0
,它返回整数0
,所以据numpy
知道,你想要一个整数数据类型.正如您所发现的,如果您将其更改为 0.0
以便您不更改返回类型,它就会正常运行.或者,您可以指定 otypes
:
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)
print(vg(e))
the result looks like this:
[0 0 0 1 1 2 2 3 3 4]
I also checked the dtype. It seems that the vectorize function is conveting the type to int64 from float64!
The documentation for np.vectorize
explains:
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. ])
这篇关于Numpy vectorize 错误地将输出转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!