adamvagyok
adamvagyok

Reputation: 175

Numpy - summing up a list of vectors

I am trying to sum a list of NumPy vectors in a list. (In this example it's a list of 2 items, 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 it's not a list. I have already tried np.add(*my_list) and np.add(np.array(my_list)) as well as np.add(np.array([my_list])), but without any success. What would be the correct way to do this? Thanks!

Upvotes: 6

Views: 15285

Answers (4)

Mike Müller
Mike Müller

Reputation: 85472

Solution 1 np.add.reduce()

You can use the reduce attribute of 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)

results in:

array([1300, 2300])

All universal function that take two in-arguments have a reduce attribute, that applies this function like reduce, i.e.:

np.add.reduce(L)

becomes:

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

Add more parenthesis and appropriate np.add calls if the list L gets larger.

From the docs:

Docstring:

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

Reduces a's dimension by one, by applying ufunc along one axis.

Solution 2 np.sum()

Alternatively, you can use np.sum along the first axis:

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

Performance

The performance of both seems to be the same.

For small arrays:

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 is a little bit faster:

%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

For large arrays:

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]

There is no difference:

%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

Upvotes: 14

uhoh
uhoh

Reputation: 3745

Is this what you mean?

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]

Upvotes: 1

Ramakrishnan G
Ramakrishnan G

Reputation: 68

Probably an ideal candidate for reduce

>>> 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])

Upvotes: 0

Anton Protopopov
Anton Protopopov

Reputation: 31672

You could use np.hstack or 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])

Upvotes: 0

Related Questions