How to use NumPy Broadcasting to divide 2D arrays by 1D arrays
Create a 2D array x of shape (5, 5) and a 1D array y of shape (5,). Write a NumPy program that divides each row of a by b using broadcasting.
Sample Solution:
Python Code:
import numpy as np
# Create a 2D array x of shape (5, 5)
x = np.array([[10, 20, 30, 40, 50],
[5, 15, 25, 35, 45],
[1, 2, 3, 4, 5],
[6, 12, 18, 24, 30],
[9, 18, 27, 36, 45]])
# Create a 1D array y of shape (5,)
y = np.array([1, 2, 3, 4, 5])
# Divide each row of x by the array y using broadcasting
result = x / y[:, np.newaxis]
print(result)
Output:
[[10. 20. 30. 40. 50. ] [ 2.5 7.5 12.5 17.5 22.5 ] [ 0.33333333 0.66666667 1. 1.33333333 1.66666667] [ 1.5 3. 4.5 6. 7.5 ] [ 1.8 3.6 5.4 7.2 9. ]]
Explanation:
- Import NumPy: Import the NumPy library to handle array operations.
- Create 2D array x: Define a 2D array x with shape (5, 5).
- Create 1D array y: Define a 1D array y with shape (5,).
- Broadcasting Division: Use broadcasting to divide each row of x by the corresponding element in y.
- Print Result: Print the resulting array.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics