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!
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.
np.sum()
Alternatively, you can use np.sum
along the first axis:
>>> np.sum(L, axis=0)
array([1300, 2300
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With