w3resource

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


20. Multiply Each Column of 2D Array by 1D Array

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.

For more Practice: Solve these Related Problems:

  • Create a function that multiplies each column of a 2D array by a corresponding element from a 1D array using broadcasting.
  • Implement a solution that scales each row of a 2D array by a 1D array and then transposes the result for verification.
  • Test the multiplication on arrays where the 1D multiplier contains both positive and negative numbers.
  • Compare the result of column-wise multiplication using broadcasting with that achieved by manually iterating through columns.

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.



Follow us on Facebook and Twitter for latest update.