user1299784
user1299784

Reputation: 2097

Store result of computation in numpy array (instead of creating new one)

Suppose I have the code:

a, b, c = np.empty((3,)), np.array([1, 2, 3]), np.array([4, 5, 6])
a = b + c

What I would like is for the result of b+c to be stored in existing array a. I do not want a new array to be allocated. How can I make this happen in numpy?

Upvotes: 0

Views: 176

Answers (2)

Guillaume S
Guillaume S

Reputation: 190

If your memory is that critical and you don't want to roam around with 3 arrays (a, b and c), you can do :

b, c = np.array([1, 2, 3]), np.array([4, 5, 6])
b += c  # does in-place operation, similarly to np.add(b, c, out=b)

where b is now carrying the result you had in array a.

Upvotes: 0

user2357112
user2357112

Reputation: 281538

np.add(b, c, out=a)

NumPy ufuncs (and a few other NumPy routines) take an out parameter to place the output in.

Upvotes: 2

Related Questions