Numpy Ceil和Floor"out"Argument

mch*_*gun 8 python numpy

ceil的NumPy 文档中 ,该numpy.ceil函数有两个参数,第二个是out.文档没有说明这个out参数是做什么的,但我假设你可以设置这个函数返回的输出类型,但是我无法让它工作:

In [107]: np.ceil(5.5, 'int')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-107-c05bcf9f1522> in <module>()
----> 1 np.ceil(5.5, 'int')

TypeError: return arrays must be of ArrayType

In [108]: np.ceil(5.5, 'int64')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-108-0937d09b0433> in <module>()
----> 1 np.ceil(5.5, 'int64')

TypeError: return arrays must be of ArrayType
Run Code Online (Sandbox Code Playgroud)

是否可以使用此参数使np.ceil返回为整数?

谢谢.

NPE*_*NPE 9

out是输出数组(必须与输入具有相同的形状).

如果你构建它是你想要的dtype,那就是dtype你得到的:

>>> arr = np.array([5.5, -7.2])
>>> out = np.empty_like(arr, dtype=np.int64)
>>> np.ceil(arr, out)
array([ 6, -7], dtype=int64)
>>> out
array([ 6, -7], dtype=int64)
Run Code Online (Sandbox Code Playgroud)


hpa*_*ulj 7

np.ceil是其中之一ufuncs。此类别的一般文档是:

op(X, out=None)
Apply op to X elementwise

Parameters
----------
X : array_like
    Input array.
out : array_like
    An array to store the output. Must be the same shape as `X`.

Returns
-------
r : array_like
    `r` will have the same shape as `X`; if out is provided, `r`
    will be equal to out.
Run Code Online (Sandbox Code Playgroud)

out并且r是获取函数输出的不同方式。最简单的就是让函数返回值。但有时你可能想给它一个out它将填充的数组。控制dtype是使用out. 另一种方法是通过“重用”已经存在的数组来节省内存。

返回的数组np.ceil也可以转换为您想要的类型,例如np.ceil(x).astype('int').