Numpy vectorize 错误地将输出转换为整数 [英] Numpy vectorize wrongly converts the output to be integer

查看:54
本文介绍了Numpy vectorize 错误地将输出转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为以下代码苦苦挣扎:

将 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:

<预><代码>>>>vg = np.vectorize(g)>>>vg(e)数组([0, 0, 0, 1, 1, 2, 2, 3, 3, 4])>>>vg = np.vectorize(g, otypes=[np.float64])>>>vg(e)数组([ 0. , 0. , 0. , 1.33333333, 1.77777778,2.22222222, 2.66666667, 3.11111111, 3.55555556, 4.])

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 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 the otypes 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.        ])

这篇关于Numpy vectorize 错误地将输出转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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