w3resource

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


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: