Dadas dos arrays numpy, la tarea es multiplicar la array numpy 2d con la array numpy 1d cada fila correspondiente a un elemento en numpy. Analicemos algunos métodos para una tarea determinada.
Método #1: Usando np.newaxis()
# Python code to demonstrate # multiplication of 2d array # with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) ini_array2 = np.array([0, 2, 3]) # printing initial arrays print("initial array", str(ini_array1)) # Multiplying arrays result = ini_array1 * ini_array2[:, np.newaxis] # printing result print("New resulting array: ", result)
Producción:
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]]
Método #2: Usar el eje como ninguno
# Python code to demonstrate # multiplication of 2d array # with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) ini_array2 = np.array([0, 2, 3]) # printing initial arrays print("initial array", str(ini_array1)) # Multiplying arrays result = ini_array1 * ini_array2[:, None] # printing result print("New resulting array: ", result)
Producción:
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]]
Método #3: Usar transponer()
# python code to demonstrate # multiplication of 2d array # with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) ini_array2 = np.array([0, 2, 3]) # printing initial arrays print("initial array", str(ini_array1)) # Multiplying arrays result = (ini_array1.T * ini_array2).T # printing result print("New resulting array: ", result)
Producción:
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]]
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA