NumPy | Multiply 2D Array to 1D Array
Given two NumPy arrays, the task is to multiply a 2D array with a 1D array, each row corresponding to one element in NumPy.
You can follow these methods to multiply a 1D array into a 2D array in NumPy:
- Using np.newaxis()
- Using axis as none
- Using transpose()
Let's understand them better with Python program examples:
Using np.newaxis()
The np.newaxis() method of the NumPy library allows us to increase the dimension of an array by 1 dimension. We use this method to perform element-wise multiplication by reshaping the 1D array to have a second-dimension
Example:
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)
Output
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]]
Using axis as none
We use None, to add a new axis to the 1D NumPy array. This reshapes the 1D array to a 2D array and allows us to multiply it with a 2D array.
Example:
# 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)
Output
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]]
Using transpose
Using NumPy T attribute, we transpose the 2D array to multiply it with a 1D array and then transpose the resulting array to its original form.
Example:
# 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)
Output
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]]