'Add some values at some range in numpy array?

I have an numpy array that looks like this

[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]

Now I have an 2d array that tells the start index and the end index and the value to sum. like this

[[5, 12, 29] [8, 22, 719]]

I want to add these numbers to my initial array faster.

Currently my solution is

f= np.zeros(n+1, dtype = int)

# print(rounds)
for elem in rounds:
    print('rounds : ',elem)
    one = elem[0]
    two = elem[1]
    value_add = elem[2]
# for i in range(0,n+1):
    for i in range(one-1,two):
        f[i-1] += value_add
        # print(f)

Its very slow when matrix gets too long, Any other way to optimize ?

2nd Iteration try for optimization

import numpy as np

f= np.zeros(n+1, dtype = int)

# print(rounds)
new = np.zeros(n+1)
for elem in rounds:
    # prin  t('rounds : ',elem)
    one = elem[0]
    two = elem[1]
    value_add = elem[2]
# for i in range(0,n+1):

    new[one-1:two] += value_add


Solution 1:[1]

How about this?

a = np.array([1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2])
instr_array = np.array([[5, 12, 29], [8, 22, 719]])

for start, end, incr in instr_array:
    a[start:end] += incr

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 navneethc