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)
np.sum
andnp.add
callingnp.array
on the input array, in this case,[a, b]
, and it's attempting to cast it into rectangular arrays on every dimension as opposed to broadcasting it. – Favoreda
andb
are correctly written? – Denby