You can use the ability of a NumPy array to sum over elements:
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 combine sequences together to form a new numpy array. As we will see below, it turned out that this is not the best way in this case.
Another possibility:
In [10]: t + np.roll(t,-1) Out[10]: array([ 9, 5, 7, 8, 7, 14, 11, 5, 11, 13])
Appears with np.roll
much 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