Consider the following code:
a = numpy.array([1,2,3,4])
b = numpy.array([5,6,7,8])
# here a new array (b*2) will be created and name 'a' will be assigned to it
a = b * 2
So, can numpy write the result of b*2 directly to memory already allocated for a, without allocating a new array?
Yes this is possible - you need to use np.multiply with its out parameter:
np.multiply(b, 2, out=a)
The array a is now filled with the result of b * 2 (and no new memory was allocated to hold the output of the function).
All of NumPy's ufuncs have the out parameter which is especially handy when working with large arrays; it helps to keep memory consumption to a minimum by allowing arrays to be reused. The only caveat is that the array has to the correct size/shape to hold the output of the function.
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