Skip to content
Related Articles

Related Articles

Python | Multiply 2d numpy array corresponding to 1d array
  • Last Updated : 15 Mar, 2019
GeeksforGeeks - Summer Carnival Banner

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :