Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy min/max in-place assignment

Tags:

python

numpy

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

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.

One way to do this is:

a = numpy.minimum(a, b)

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

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

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?

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

like image 217
alveko Avatar asked Jan 20 '13 19:01

alveko


People also ask

How do you find min and max in Numpy?

numpy. amax() will find the max value in an array, and numpy. amin() does the same for the min value.

Is NP min faster than min?

min is slower than builtin min for small arrays, occasionally VERY slow #12350.

How does Numpy calculate min?

For finding the minimum element use numpy. min(“array name”) function.

How do you find the index of the maximum value in an array in Python?

Use the enumerate() function to find out the index of the maximum value in a list. Use the numpy. argmax() function of the NumPy library to find out the index of the maximum value in a list.


1 Answers

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]])
like image 57
NPE Avatar answered Sep 22 '22 04:09

NPE