gpt4 book ai didi

python - numpy.rint 可以返回一个 Int32 吗?

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:31 32 4
gpt4 key购买 nike

我在做

ret = np.rint(y * 4)
return ret

我希望它返回 Int32。我尝试添加 dtype='Int32',但错误提示:TypeError: No loop matching the specified signature and casting was found for ufunc rint

如果这是一个基本问题,我深表歉意,但我试图寻找答案无济于事

最佳答案

ufuncs 对给定输入时产生的输出类型有特定的规则。对于 rint,规则是:

In [41]: np.rint.types                                                          
Out[41]: ['e->e', 'f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']

除此之外,还有关于哪些数据类型可以转换为其他数据类型的规则。我们可以使用 outcasting 参数来生成整数输出,但简单地使用 astype after 会更简单。

所以 rint 通常会返回一个匹配的 float ,即使这些值是四舍五入的。

In [43]: np.rint(np.linspace(0,10,8))                                           
Out[43]: array([ 0., 1., 3., 4., 6., 7., 9., 10.])

简单地提供一个 int out 是行不通的:

In [44]: np.rint(np.linspace(0,10,8),out=np.zeros(8,int))                       
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-e7f13fa29434> in <module>
----> 1 np.rint(np.linspace(0,10,8),out=np.zeros(8,int))

TypeError: ufunc 'rint' output (typecode 'd') could not be coerced to provided output parameter (typecode 'l') according to the casting rule ''same_kind''

我们必须允许它进行 float 到 int 的转换:

In [45]: np.rint(np.linspace(0,10,8),out=np.zeros(8,int),casting='unsafe')      
Out[45]: array([ 0, 1, 3, 4, 6, 7, 9, 10])

astype 的默认转换 是“不安全的”。

In [55]: np.rint(np.linspace(0,10,8)).astype(int,casting='safe')                
TypeError: Cannot cast array from dtype('float64') to dtype('int64') according to the rule 'safe'

关于python - numpy.rint 可以返回一个 Int32 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146871/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com