Is there a way to add (as opposed to sum) multiple arrays together in a single operation? Obviously, np.sum and np.add are different operations, however, the problem I'm struggling with right now is that np.add only takes two arrays at once. I could utilize either
output = 0
for arr in arr_list:
output = output + array
or
output = 0
for arr in arr_list:
output = np.add(output, array)
and, yes, this is workable. However, it would be nice if I could simply do some variant of
output = np.add_multiple(arr_list)
Does this exist?
EDIT: I failed to be clear initially. I specifically require a function that does not require an array of arrays to be constructed, as my arrays are not of equal dimensions and require broadcasting, for example:
a = np.arange(3).reshape(1,3)
b = np.arange(9).reshape(3,3)
a, b = a[:,:,None,None], b[None,None,:,:]
These work:
a + b # Works
np.add(a, b) # Works
These do not, and fail with the same exception:
np.sum([a, b], axis = 0)
np.add.reduce([a, b])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,1,1) into shape (1)
You can just use the Python's sum built-in:
output = sum(arr_list)
For many other numpy functions, np.<ufunc>.reduce can be used as shown by @hpaulj.
You can use the sum() to add multiple arrays.
arr = np.array([[6,2,3,5,4,3],
[7,7,2,4,6,7],
[10,6,2,4,5,9]])
np.add(0, arr.sum(axis=0))
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