2

Suppose I have a very large numpy array a, and I want to add the numerical value 1 to each element of the array. From what I have read so far:

a += 1 

is a good way of doing it rather than:

a = a + 1

since in the second case a new array a is created in a different memory slot, while in the first case the old array is effectively replaced in the same memory slot.

Suppose I want to do the following instead:

a = 1-a

What would be the memory efficient way of doing the above?

2
  • a is an numpy array? Could you add something like a = numpy.array([1,2,3,4,5,6,7,8]) so we can easily see what you mean? Commented May 9, 2018 at 1:21
  • The documentation for add.at indicates that a += 1 does a certain amount of buffering - docs.scipy.org/doc/numpy-1.13.0/reference/generated/…. Details are buried in numpy code. Commented May 9, 2018 at 1:30

2 Answers 2

6
numpy.subtract(1, a, out=a)

Using the subtract ufunc directly gives you more control than the - operator. Here, we use the out parameter to place the results of the subtraction back into a.

Sign up to request clarification or add additional context in comments.

1 Comment

@OlivierMelançon: a is a NumPy array. We're already using NumPy. The cost of importing NumPy is a sunk cost, not an additional cost to pay for using this code.
3

You could do it in place like so:

a *= -1
a += 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.