numpy.rint可以返回Int32吗?

时间:2019-03-13 16:32:35

标签: python python-3.x numpy

我在做

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

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用astype方法(docs here

ret = np.rint(y * 4).astype(np.int32)

请注意,astype将创建一个副本,因此它可能不是最有效的内存操作(大多数时候您都不在乎)。

旁注:为什么rint输出一个float整数类型的dtype数组超出了我的范围。

答案 1 :(得分:1)

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']

此外,还有关于可以将哪些dtype强制转换为其他dtype的规则。我们可以使用outcasting参数来产生整数输出,但是在此之后简单地使用astype更简单。

因此rint通常会返回一个匹配的浮点数,即使这些值已取整。

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''

我们必须授予它对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])

casting的默认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'

答案 2 :(得分:0)

看起来像这样:

ret = (y * 4)
ret = ret.astype(int)
return ret
相关问题