Reputation: 1157
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?
Upvotes: 3
Views: 202
Reputation: 176938
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.
Upvotes: 3