Cómo arreglar operands could not be broadcast together with shapes error en Python

Haider Ali 14 abril 2022
Cómo arreglar operands could not be broadcast together with shapes error en Python

En Python, las matrices numpy con diferentes formas no se pueden transmitir juntas. Significa que no puede agregar dos matrices 2D con diferentes filas y columnas.

Pero hay una manera a través de la cual puedes hacer eso. Echar un vistazo.

Se corrigió el error operands could not be broadcast together with shapes en Python

No puede sumar o multiplicar dos matrices 2D con diferentes formas. Echa un vistazo al siguiente código.

import numpy as np

# Addition Example

# 2d array with shape 2 rows and 3 columns
array_1 = np.array([[1, 1, 1], [1, 1, 1]])
# 2d array with shape 3 rows and 2 columns
array_2 = np.array([[1, 1], [1, 1], [1, 1]])
# Addition applying on the arrays
array_Addition = array_1 + array_2

Como puede ver, hay dos matrices 2D con diferentes formas.

El primer arreglo tiene dos filas y tres columnas, y el segundo arreglo tiene tres filas y dos columnas. Agregarlos dará este error operands could not be broadcast together with shapes.

Funciona igual que sumar dos matrices en matemáticas.

El primer elemento de la primera matriz se agrega con el primer elemento de la segunda matriz, y el segundo elemento se agregará con la segunda. Entonces, si las formas no coinciden, dará un error.

Por lo tanto, necesitamos usar las funcionalidades de remodelación para tener las mismas formas para las dos matrices 2D. En el siguiente código, estamos remodelando la segunda matriz de acuerdo con las formas de la primera.

Una vez que las formas sean iguales, puede agregar las dos matrices.

import numpy as np

# Addition Example

# 2d array with shape 2 rows and 3 columns
array_1 = np.array([[1, 1, 1], [1, 1, 1]])
# 2d array with shape 3 rows and 2 columns
array_2 = np.array([[1, 1], [1, 1], [1, 1]])

# changing the shape of array_2 according to the Array_1 or Array_1 according to Array_2
array_2 = array_2.reshape((2, 3))

# again Addition applying on the arrays
array_Addition = array_1 + array_2

print(array_Addition)

Producción :

[[2 2 2]
 [2 2 2]]
Autor: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

Artículo relacionado - Python Error

Artículo relacionado - Python NumPy