1

I have an array:

my_array = [1, 13, 6, 100, 12,23,45] and would like to create a new array that for each index in my_array is the sum of 3 next index values

summed_array = [119, 118, 135, 80, 68,45,0] I tried something like np.cumsum but this cumlative values

import numpy as np

sum_value = 0

my_array = [1, 13, 6, 100, 12,23,45]
summed_array = [0, 0, 0, 0, 0,0,0]
print(len(my_array))
for ind,i in enumerate(my_array):
    if ind+3< len(my_array):
        summed_array[ind] =my_array[ind+1]+my_array[ind+2]+my_array[ind+3]
    elif ind+2 < len(my_array):
         summed_array[ind] =my_array[ind+1]+my_array[ind+2]
    elif ind+1 < len(my_array):
        summed_array[ind]=my_array[ind+1]
    else:
        summed_array[ind] = 0
print(summed_array)  ``` 
Cleancode
  • 25
  • 5

5 Answers5

1

This should do the trick using slices.

import numpy as np

sum_value = 0

my_array = [1, 13, 6, 100, 12,23,45]
summed_array = [0, 0, 0, 0, 0,0,0]
n = 3;
print(len(my_array))
for i in range(len(summed_array)):
    summed_array[i] = sum(my_array[i+1:i+1+n])
print(summed_array)
Simon Tulling
  • 176
  • 1
  • 7
1

With a being your array:

>>> c = a.cumsum()
>>> np.concatenate((c[3:], [a.sum()] * 3)) - c
array([119, 118, 135,  80,  68,  45,   0])
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
0

You can also do it in list comprehension:

sum_array = [ sum(my_array[pos+1:pos+4]) for pos in range(len(my_array)) ]

This way there is no need for declaring the sum_array, as it will always be already created with the correct size.

Edit: Fixed the 'next 3 values', since I hadn't realised it in the first place.

LombardiD
  • 301
  • 1
  • 2
  • 9
  • 1
    It should be `sum(my_array[pos+1:pos+4])` as the op asked for the next 3 values. – bj0 Aug 11 '20 at 17:58
0

If you are trying to minimize the number of additions performed, it might be a good idea to have a pointer so that you add and subtract once for each index instead of adding 3 times. You might find a different solution more optimum than this though. If so, please let me know :) Let a be your array.

# Initialize sum array sa with first index
val = sum(a[1:4])
sa = [val]
i = 1

# Get sum for all except last 3 indices
for i in range(1, len(a) - 3):
  val = val + a[i + 3] - a[i]
  sa.append(val)

# Account for the last 3 indices
while i < len(a):
  val -= a[i]
  sa.append(val)
  i += 1

# sa is the array needed at this point

Please note that empty array would currently return [0]. If you intend to return an empty array instead, that would be an edge case that can be handled by an if statement in the beginning

-1

This can be done

a = my_array
summed_array= [sum(a[i:i+3]) for i in range(len(a))]
Kuldip Chaudhari
  • 1,112
  • 4
  • 8
  • 1
    The `min` is unnecessary, as slicing automatically stops before going out of the index bounds. – bj0 Aug 11 '20 at 17:57