Home > Mobile >  How to sum across n elements of numpy array
How to sum across n elements of numpy array

Time:06-01

I hope that someone can help me with my problem since I'm not used to python and numpy yet. I have the following array with 24 elements:

load = np.array([10, 12, 9, 13, 17, 23, 25, 28, 26, 24, 22, 20, 18, 20, 22, 24, 26, 28, 23, 24, 21, 18, 16, 13])

I want to create a new array with the same length as "load" and calculate for each element in the array the sum of the current and the next two numbers, so that my objective array would look like this:

[31, 34, 39, 53, 65, 76, 79, 78, 72, 66, 60, 58, 60, 66, 72, 78, 77, 75, 68, 63, 55, 47, 29, 13]

I tried to solve this with the following code:

output = np.empty(len(load))
for i in range((len(output))-2):
    output[i] = load[i] load[i 1] load[i 2]
print(output)

The output array looks like this:

array([31. , 34. , 39. , 53. , 65. , 76. , 79. , 78. , 72. , 66. , 60. ,
       58. , 60. , 66. , 72. , 78. , 77. , 75. , 68. , 63. , 55. , 47. ,
        6. ,  4.5])

The last two numbers are not right. For the 23th element I want the sum of just 16 and 13 and for the last number to stay 13 since the array ends there. I don't unterstand how python calculated these numbers. Also I would prefer the numbers to be integers without the dot.

Does anyone have a better solution in mind? I know that this probably is easy to solve, I just don't know all the functionalities of numpy.

Thank you very much!

CodePudding user response:

np.empty creates an array containing uninitialized data. In your code, you initialize an array output of length 24 but assign only 22 values to it. The last 2 values contain arbitrary values (i.e. garbage). Unless performance is of importance, np.zeros is usually the better choice for initializing arrays since all values will have a consistent value of 0.

You can solve this without a for loop by padding the input array with zeros, then computing a vectorized sum.

import numpy as np

load = np.array([10, 12, 9, 13, 17, 23, 25, 28, 26, 24, 22, 20, 18, 20, 22, 24, 26, 28, 23, 24, 21, 18, 16, 13])
tmp = np.pad(load, [0, 2])
output = load   tmp[1:-1]   tmp[2:]

print(output)

Output

[31 34 39 53 65 76 79 78 72 66 60 58 60 66 72 78 77 75 68 63 55 47 29 13]

CodePudding user response:

If the array is not super long, you could use:

output = [sum(x, y, z) for x, y, z in zip(load, load[1:], load[2:])]
  • Related