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']
最重要的是,还有关于哪些数据类型可以转换为其他数据类型的规则。我们可以玩out
和casting
参数来产生整数输出,但只需使用astype
之后就简单了。
So rint
通常返回一个匹配的浮点数,即使值是四舍五入的。
In [43]: np.rint(np.linspace(0,10,8))
Out[43]: array([ 0., 1., 3., 4., 6., 7., 9., 10.])
只需提供一个 intout
不起作用:
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])
默认casting
for 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'