14

Is there a simpler and more memory efficient way to do the following in numpy alone.

import numpy as np
ar = np.array(a[l:r])
ar += c
a = a[0:l] + ar.tolist() + a[r:]

It may look primitive but it involves obtaining a subarray copy of the given array, then prepare two more copies of the same to append in left and right direction in addition to the scalar add. I was hoping to find some more optimized way of doing this. I would like a solution that is completely in Python list or NumPy array, but not both as converting from one form to another as shown above would cause serious overhead when the data is huge.

2
  • 6
    So you want to add c to a slice of a inplace... does a[l:r] += c work for your example (assuming a is a NumPy array)? Commented Sep 12, 2015 at 19:17
  • Yes. That's the idea. Commented Sep 12, 2015 at 19:23

1 Answer 1

30

You can just do the assignment inplace as follows:

import numpy as np

a = np.array([1, 1, 1, 1, 1])
a[2:4] += 5
>>> a
array([1, 1, 6, 6, 1])
Sign up to request clarification or add additional context in comments.

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.