Get sums of pairs of elements in a numpy array
numpy, python, scipy
Solution
You could take advantage of a NumPy array's ability to sum element-wise:
In [5]: import numpy as np
In [6]: t = np.array([4, 5, 0, 7, 1, 6, 8, 3, 2, 9])
In [7]: t + np.r_[t[1:],t[0]]
Out[7]: array([ 9, 5, 7, 8, 7, 14, 11, 5, 11, 13])
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:
In [10]: t + np.roll(t,-1)
Out[10]: array([ 9, 5, 7, 8, 7, 14, 11, 5, 11, 13])
It appears using `np.roll` is significantly faster:
In [11]: timeit t + np.roll(t,-1)
100000 loops, best of 3: 17.2 us per loop
In [12]: timeit t + np.r_[t[1:],t[0]]
10000 loops, best of 3: 35.5 us per loop
Problem
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?