【问题标题】:sum the elements of 2 NumPy arrays对 2 个 NumPy 数组的元素求和
【发布时间】:2021-02-12 12:47:09
【问题描述】:
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)

~\anaconda3\lib\site-packages\numpy\core\fromnumeric.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 

~\anaconda3\lib\site-packages\numpy\core\fromnumeric.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,) 

我正在尝试对这些数组的元素求和.....但是它在 jupiter notebook 中抛出了这个错误

【问题讨论】:

  • 您期望得到什么?两个数组中所有数字的总和?然后n1.sum() + n2.sum().
  • 提问时,请记得同时提及@YevhenKuzmovych 提到的预期结果。

标签: python arrays python-3.x numpy anaconda3


【解决方案1】:
np.sum(np.append(n1,n2))

你首先需要将两个数组追加在一起,然后你可以取总和。

【讨论】:

    猜你喜欢
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多