w3resource

How to multiply columns of a 2D array by a 1D array using NumPy?

NumPy: Broadcasting Exercise-20 with Solution

Write a NumPy program that Multiplies each column of a 2D array x of shape (7, 3) by a 1D array y of shape (7,) using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array x of shape (7, 3)
x = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9],
              [10, 11, 12],
              [13, 14, 15],
              [16, 17, 18],
              [19, 20, 21]])

# Create a 1D array y of shape (7,)
y = np.array([1, 2, 3, 4, 5, 6, 7])

# Multiply each column of x by the array y using broadcasting
result = x * y[:, np.newaxis]

print(result)

Output:

[[  1   2   3]
 [  8  10  12]
 [ 21  24  27]
 [ 40  44  48]
 [ 65  70  75]
 [ 96 102 108]
 [133 140 147]]

Explanation:

  • Import NumPy: Import the NumPy library to handle array operations.
  • Create 2D array x: Define a 2D array x with shape (7, 3).
  • Create 1D array y: Define a 1D array y with shape (7,).
  • Broadcasting Multiplication: Multiply each column of x by the corresponding element in y using broadcasting.
  • Print Result: Print the resulting array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to use NumPy Broadcasting to add 3D and 2D arrays?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/multiply-columns-of-a-2d-array-by-a-1d-array-using-numpy.php