相关疑难解决方法(0)

numpy从2d数组中减去/添加1d数组

我有以下2D数组:

a = array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12],
           [13, 14, 15]])
Run Code Online (Sandbox Code Playgroud)

和另一个1D阵列:

b = array([ 1,  2,  3,  4,  5])
Run Code Online (Sandbox Code Playgroud)

然后我想计算类似的东西

c = a - b
Run Code Online (Sandbox Code Playgroud)

旨在获得:

c = array([[0, 1,  2],
           [2, 3,  4],
           [4, 5,  6],
           [6, 7,  8],
           [8, 9, 10]])
Run Code Online (Sandbox Code Playgroud)

但我得到错误信息:

Traceback (most recent call last):
  Python Shell, prompt 79, line 1
ValueError: operands could not be broadcast together with shapes (5,3) (5,)
Run Code Online (Sandbox Code Playgroud)

我阅读了广播规则,但没有更明智.我可以使用for循环或类似方法进行解决,但应该有一个直接的方法.谢谢

python arrays numpy

16
推荐指数
1
解决办法
1万
查看次数

标签 统计

arrays ×1

numpy ×1

python ×1