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()

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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()

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.