我正在做
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']
最重要的是,关于哪些dtypes可以施放到其他dtypes。我们可以使用out
和casting
参数来产生整数输出,但是仅使用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])
astype
的默认casting
是"不安全"。
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'
您可以使用astype
方法(在此处使用DOC)
ret = np.rint(y * 4).astype(np.int32)
请注意,astype
会创建一个副本,因此它可能不是最有效的内存操作(大多数情况下您不会照顾)。
Sidenote:为什么rint
输出float
DTYPE整数数组超出了我。
似乎会做到这一点:
ret = (y * 4)
ret = ret.astype(int)
return ret