3qxs7na6
3qxs7na6

Reputation: 21

How to correct numpy array of offsets?

Let's say I have the following numpy array:

0 50 100 150

Each integer represents an offset, and I want to change one of the values (e.g. 50 to 60). I can do so by doing:

my_array[1] = 60

However, I want all of the offsets to update accordingly. (Every integer after 50 gets 10 added to it because I changed 50 by 10). What's the easiest way to implement something like this without over complicating anything?

Upvotes: 2

Views: 71

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114390

Let's say you have

delta = 10
index = 1

You can do

my_array[index:] += delta

Or in terms of offset = 60:

my_array[index:] += (offset - my_array[index])

Depending on the situation, you may need something more complex. For example, if you have multiple deltas you want to handle simultaneously:

deltas = np.zeros_like(my_array)
deltas[index] = delta
my_array += deltas.cumsum()

Or alternatively, operate on the diffs:

d = np.r_[my_array[0], np.diff(my_array)]
d[index] += delta
my_array = d.cumsum()

Upvotes: 1

Related Questions