Save the result of multiplication with an existing array
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 b*2
directly to the memory already allocated for a
, without allocating a new array?
source to share
Yes it is possible - you need to use np.multiply
with out
:
np.multiply(b, 2, out=a)
The array a
is now filled with the result b * 2
(and no new memory has been allocated to hold the function's output).
All NumPy ufuncs have a parameter out
, which is especially useful when working with large arrays; this helps keep memory consumption to a minimum while allowing reuse of arrays. The only caveat is that the array must be the correct size / shape to hold the function's output.
source to share