Thursday, July 4, 2024
HomeLanguagesPythonPython | Multiply 2d numpy array corresponding to 1d array

Python | Multiply 2d numpy array corresponding to 1d array

Given a two numpy arrays, the task is to multiply 2d numpy array with 1d numpy array each row corresponding to one element in numpy. Let’s discuss a few methods for a given task.

Method #1: Using 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)


Output:

initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[ 0  0  0]
 [ 4  8 10]
 [ 3  6  9]]

 
Method #2: Using axis as none




# 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]]

 
Method #3: Using transpose()




# 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]]

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments