Numpy - Summing a Vector List

I am trying to summarize a list of NumPy vectors in a list. (In this example, this is a list of two elements, but in my case the list can be of any size.) How to sum them into a new vector?

a = np.array([100, 100])
b = np.array([200, 200])
my_list = [a, b]

ab = np.add(my_list)

np.add(a, b)works, but this is not a list. I have already tried np.add(*my_list)and np.add(np.array(my_list))as well np.add(np.array([my_list])), but without any success. What would be the right way to do this? Thanks!

+4
source share
4 answers

Solution 1 np.add.reduce()

You can use the attribute reduce np.add:

a = np.array([100, 100])
b = np.array([200, 200])
c = np.array([1000, 2000])
L = [a, b, c]
np.add.reduce(L)

leads to:

array([1300, 2300])

An entire universal function that takes two arguments has an attribute reducethat applies this function as reduce, ie:

np.add.reduce(L)

becomes:

np.add(np.add(L[0], L[1]), L[2])

np.add, L .

:

:

  reduce(a, axis=0, dtype=None, out=None, keepdims=False)

a , ufunc .

2 np.sum()

np.sum :

>>> np.sum(L, axis=0)
array([1300, 2300

, , .

:

a = np.array([100, 100])
b = np.array([200, 200])
c = np.array([1000, 2000])
L = [a, b, c, a, b, c, a, b, c]

reduce :

%timeit np.sum(L, axis=0)

10000 loops, best of 3: 20.7 µs per loop

%timeit np.add.reduce(L)
100000 loops, best of 3: 15.7 µs per loop

:

size = int(1e6)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
L = [a, b, c, a, b, c, a, b, c]

:

%timeit np.sum(L, axis=0)
10 loops, best of 3: 41.5 ms per loop

%timeit np.add.reduce(L)
10 loops, best of 3: 41.9 ms per loop
+5

, ?

import numpy as np

a = np.array([100, 100])
b = np.array([200, 200])
my_list = [a, b]

# add them up "vertically"

print np.vstack(my_list).sum(axis=0)

print np.vstack(tuple(my_list)).sum(axis=0)  # I thought it had to be a tuple but apparently not!


[300 300]
[300 300]
+1

You can use np.hstackor np.concatenate:

l = [a, b]

In [560]: np.hstack(l)
Out[560]: array([100, 100, 200, 200])

In [561]: np.concatenate(l)
Out[561]: array([100, 100, 200, 200])
0
source

Probably the perfect candidate for downsizing

>>> a = np.array([100, 100])
>>> b = np.array([200, 200])
>>> c = np.array([300, 300])
>>> reduce(lambda x,y: np.add(x,y), [a,b,c])
array([600, 600])
0
source

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


All Articles