【问题标题】:operands could not be broadcast together with shapes (5,2) (1,5)操作数不能与形状一起广播 (5,2) (1,5)
【发布时间】:2021-03-03 18:29:02
【问题描述】:

我想将这两个 np.array 相乘,我相信它应该返回一个 (5,2) np.array,但它会引发错误。

a = np.array([1, 2, 3, 4, 5])
b = np.arange(10)
b = b.reshape((5,2))
print(a.shape, b.shape)
print(b * a)

【问题讨论】:

  • 我注意到如果我将 b 重新整形为 (2,5) 就不会出错,为什么会出现这种情况???

标签: python numpy broadcasting


【解决方案1】:

如果你想在每一列上将 a 和 b 元素相乘,你需要添加

a = a.reshape((5,1))

【讨论】:

  • 我知道我可以这样做,但我不明白为什么不能这样做,因为如果我们设置 a = np.array([1,2]),它不会引发错误。
猜你喜欢
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多