Get sums of pairs of elements in a numpy array

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 fair:

 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 to do this with numpy to avoid a python loop to work with large arrays?

+6
source share
3 answers

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 
+18
source

You can do this pretty happily with zip() , list slice and list comprehension :

 t2 = [a+b for (a, b) in zip(t, t[1:])] t2.append(t[0]+t[-1]) 

We need an additional append() to add to the last element, since zip() only works until the shortest iterator ends. Understanding a list is significantly faster than a regular for loop, since it implemented the C side in Python, and not like a Python loop.

An alternative is to use itertools.zip_longest :

 from itertools import zip_longest t2 = [a+b for (a, b) in zip_longest(t, t[1:], fillvalue=t[0])] 

To fill in an extra value. Notice that this function itertools.izip_longest in Python 2.x.

+1
source

What about

 import numpy as np t = np.array([4, 5, 0, 7, 1, 6, 8, 3, 2, 9]) new_t = t + np.hstack((t[1:], [t[0]])) 

Result:

 >>> new_t array([ 9, 5, 7, 8, 7, 14, 11, 5, 11, 13]) 
+1
source

Source: https://habr.com/ru/post/914427/


All Articles