5

如标题所示,我需要numpy.exp在一个非常大的 ndarray 上执行,比如说ar,并将结果存储在ar自身中。可以就地执行此操作吗?

4

2 回答 2

10

您可以使用的可选out参数exp

a = np.array([3.4, 5])
res = np.exp(a, a)
print(res is a)
print(a)

输出:

True
[  29.96410005  148.4131591 ]

exp(x[, 出])

计算输入数组中所有元素的指数。

退货

out : ndarray 输出数组,元素的指数x

这里的所有元素都a将替换为 的结果exp。返回值res与 相同a。没有创建新数组

于 2016-12-20T15:27:55.880 回答
5

Mike Mueller 的回答很好,但请注意,如果您的数组是,等类型int32,它将抛出. 因此,执行此操作的一种安全方法是将数组类型转换为等,然后再执行类似操作,intint64TypeErrorfloat64float32exp

In [12]: b
Out[12]: array([1, 2, 3, 4, 5], dtype=int32)

In [13]: np.exp(b, b)
--------------------------------------------------------------------------
TypeError: ufunc 'exp' output (typecode 'd') could not be coerced to provided 
output parameter (typecode 'i') according to the casting rule ''same_kind''

类型铸造和经验:

# in-place typecasting
In [14]: b = b.astype(np.float64, copy=False)
In [15]: b
Out[15]: array([ 1.,  2.,  3.,  4.,  5.], dtype=float64)

# modifies b in-place
In [16]: np.exp(b, b)
Out[16]: array([   2.718,    7.389,   20.086,   54.598,  148.413], dtype=float64)
于 2016-12-20T17:02:50.790 回答