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?
numpy. amax() will find the max value in an array, and numpy. amin() does the same for the min value.
min is slower than builtin min for small arrays, occasionally VERY slow #12350.
For finding the minimum element use numpy. min(“array name”) function.
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With