如何解决:ValueError: 操作数无法与形状 (4,) (4,6) 一起广播

7 python arrays numpy array-broadcasting

我必须通过广播对 2 个数组求和。这是第一个:

a = [0 1 2 3]
Run Code Online (Sandbox Code Playgroud)

这是第二个:

A = [[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止尝试过的代码:

a = [0 1 2 3]
Run Code Online (Sandbox Code Playgroud)

但是当我运行时,它会抛出以下错误:ValueError: operands could not be broadcast together with shapes (4,) (4,6)

怎么解决呢?

Sus*_*wal 11

执行数学运算时,数组需要具有兼容的形状和相同的维数。也就是说,您不能将两个形状为 (4,) 和 (4, 6) 的数组相加,但可以将形状为 (4, 1) 和 (4, 6) 的数组相加。

您可以添加额外的维度,如下所示:

a = np.array(a)
a = np.expand_dims(a, axis=-1) # Add an extra dimension in the last axis.
A = np.array(A)
G = a + A
Run Code Online (Sandbox Code Playgroud)

这样做并广播后,a实际上将成为

[[0 0 0 0 0 0]
 [1 1 1 1 1 1]
 [2 2 2 2 2 2]
 [3 3 3 3 3 3]]
Run Code Online (Sandbox Code Playgroud)

出于加法的目的( 的实际值a不会改变,a仍然是;上面是要添加的[[0] [1] [2] [3]]数组)。A