NumPy最小/最大就地分配 [英] NumPy min/max in-place assignment

查看:85
本文介绍了NumPy最小/最大就地分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在没有额外副本的情况下使用NumPy多维数组执行最小/最大就地分配?

Is it possible to perform min/max in-place assignment with NumPy multi-dimensional arrays without an extra copy?

说,ab是两个2D numpy数组,我希望所有ij都具有a[i,j] = min(a[i,j], b[i,j]).

Say, a and b are two 2D numpy arrays and I would like to have a[i,j] = min(a[i,j], b[i,j]) for all i and j.

一种方法是:

a = numpy.minimum(a, b)

但是根据文档,numpy.minimum创建并返回一个新数组:

But according to the documentation, numpy.minimum creates and returns a new array:

numpy.minimum(x1,x2 [,out])
数组元素的按元素最小值.
比较两个数组,并返回一个新的数组,其中包含按元素的最小值.

numpy.minimum(x1, x2[, out])
Element-wise minimum of array elements.
Compare two arrays and returns a new array containing the element-wise minima.

因此在上面的代码中,它将创建一个新的临时数组(ab的最小值),然后将其分配给a并进行处理,对吧?

So in the code above, it will create a new temporary array (min of a and b), then assign it to a and dispose it, right?

有什么办法可以像a.min_with(b)那样将最小结果就地分配回a吗?

Is there any way to do something like a.min_with(b) so that the min-result is assigned back to a in-place?

推荐答案

numpy.minimum()采用可选的第三个参数,即输出数组.您可以在那里指定a对其进行修改:

numpy.minimum() takes an optional third argument, which is the output array. You can specify a there to have it modified in place:

In [9]: a = np.array([[1, 2, 3], [2, 2, 2], [3, 2, 1]])

In [10]: b = np.array([[3, 2, 1], [1, 2, 1], [1, 2, 1]])

In [11]: np.minimum(a, b, a)
Out[11]: 
array([[1, 2, 1],
       [1, 2, 1],
       [1, 2, 1]])

In [12]: a
Out[12]: 
array([[1, 2, 1],
       [1, 2, 1],
       [1, 2, 1]])

这篇关于NumPy最小/最大就地分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆