sum the elements of 2 NumPy arrays

Tags: , , , ,



import numpy as np
n1=np.array([10,20,30,40,50,60])
n2=np.array([50,60,70,80])

np.sum([n1,n2])

ValueError                                Traceback (most recent call last)
<ipython-input-19-d22debd88ae6> in <module>
      3 n2=np.array([50,60,70,80])
      4 
----> 5 np.sum([n1,n2])

<__array_function__ internals> in sum(*args, **kwargs)

~anaconda3libsite-packagesnumpycorefromnumeric.py in sum(a, axis, dtype, out, keepdims, initial, where)
   2239         return res
   2240 
-> 2241     return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
   2242                           initial=initial, where=where)
   2243 

~anaconda3libsite-packagesnumpycorefromnumeric.py in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
     85                 return reduction(axis=axis, out=out, **passkwargs)
     86 
---> 87     return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
     88 
     89 

ValueError: operands could not be broadcast together with shapes (6,) (4,) 

I am trying the sum the elements of these arrays…..but it is throwing this error in jupiter notebook

Answer

np.sum(np.append(n1,n2))

You first need to append the two arrays together, then you can take the total sum.



Source: stackoverflow