I have an array:
t = [4, 5, 0, 7, 1, 6, 8, 3, 2, 9]
which is just a random shuffle of the range [0, 9]. I need to calculate this:
t2 = [9, 5, 7, 8, 7, 14, 11, 5, 11, 13]
which is just:
t2 = [t[0]+t[1], t[1]+t[2], t[2]+t[3], t[3]+t[4], ..., t[9]+t[0]]
Is there a way I can do this with numpy to avoid a python for loop when dealing with large arrays?
You could take advantage of a NumPy array’s ability to sum element-wise:
np.r_ is one way to concatenate sequences together to form a new numpy array. As we’ll see below, it turns out not to be the best way in this case.
Another possibility is:
It appears using
np.rollis significantly faster: