📖 Scenario: Imagine you are working with sales data for a small store. You have daily sales numbers for different products, and you want to apply a discount rate to all products easily using NumPy arrays.
🎯 Goal: You will learn how to use NumPy broadcasting rules to apply a discount rate to a 2D array of sales data without writing loops.
📋 What You'll Learn
Create a NumPy 2D array with exact sales data
Create a NumPy 1D array with exact discount rates
Use broadcasting to apply discounts to sales data
Print the discounted sales array
💡 Why This Matters
🌍 Real World
Applying discounts or adjustments to sales data is common in retail and business analytics. Broadcasting helps apply these changes efficiently without writing loops.
💼 Career
Data scientists and analysts often use broadcasting in NumPy to perform fast and readable calculations on large datasets.
Progress0 / 4 steps
1
Create the sales data array
Import NumPy as np and create a 2D NumPy array called sales with these exact values: [[100, 200, 300], [400, 500, 600]].
NumPy
Hint
Use np.array() to create the array with the exact nested list.
2
Create the discount rates array
Create a 1D NumPy array called discounts with these exact values: [0.9, 0.8, 0.7] representing discount rates for each product.
NumPy
Hint
Create a 1D array with the discount rates matching the number of columns in sales.
3
Apply broadcasting to calculate discounted sales
Create a new NumPy array called discounted_sales by multiplying sales with discounts using broadcasting.
NumPy
Hint
Simply multiply the 2D sales array by the 1D discounts array to apply broadcasting.
4
Print the discounted sales array
Print the discounted_sales array to see the result of applying the discounts.
NumPy
Hint
Use print(discounted_sales) to display the array.
Practice
(1/5)
1. What is the main purpose of broadcasting in NumPy?
easy
A. To create copies of arrays for backup
B. To perform operations on arrays of different shapes by stretching dimensions
C. To sort arrays automatically before calculations
D. To convert arrays into lists for easier processing
Solution
Step 1: Understand broadcasting concept
Broadcasting allows NumPy to perform element-wise operations on arrays with different shapes by stretching dimensions of size 1.
Step 2: Compare options with concept
Only To perform operations on arrays of different shapes by stretching dimensions correctly describes this purpose. Other options describe unrelated actions.
Final Answer:
To perform operations on arrays of different shapes by stretching dimensions -> Option B
Quick Check:
Broadcasting = Stretching dimensions for operations [OK]
Hint: Broadcasting stretches size 1 dims to match shapes [OK]
Common Mistakes:
Thinking broadcasting copies arrays
Confusing broadcasting with sorting
Believing broadcasting converts arrays to lists
2. Which of the following is a valid broadcasting rule in NumPy?
easy
A. Arrays must have the same number of dimensions
B. All dimensions must be equal
C. Dimensions must be exactly equal or one of them must be 1
D. Only 1D arrays can be broadcasted
Solution
Step 1: Recall broadcasting rules
Broadcasting compares shapes from right to left; dimensions must be equal or one must be 1 to stretch.
Step 2: Evaluate options
Dimensions must be exactly equal or one of them must be 1 matches the rule exactly. Options A, B, and D are incorrect because broadcasting allows different dimensions and works beyond 1D arrays.
Final Answer:
Dimensions must be exactly equal or one of them must be 1 -> Option C
Quick Check:
Broadcasting rule = equal or 1 dimension [OK]
Hint: Check if dims are equal or one is 1 [OK]
Common Mistakes:
Assuming all dims must match exactly
Believing arrays must have same number of dims
Thinking broadcasting only works on 1D arrays
3. What is the shape of the result when adding arrays a = np.ones((3,1)) and b = np.ones((1,4)) using broadcasting?
medium
A. (3, 1)
B. (4, 3)
C. (1, 4)
D. (3, 4)
Solution
Step 1: Analyze shapes of a and b
a has shape (3,1), b has shape (1,4). Broadcasting compares from right: 1 vs 4 and 3 vs 1.
Step 2: Apply broadcasting rules
Dimensions 1 and 4 broadcast to 4; 3 and 1 broadcast to 3. Result shape is (3,4).
Final Answer:
(3, 4) -> Option D
Quick Check:
Broadcast (3,1) + (1,4) = (3,4) [OK]
Hint: Match dims right to left, stretch 1 to other size [OK]
Common Mistakes:
Confusing order of dimensions
Forgetting to broadcast size 1 dimension
Swapping dimensions in result shape
4. Consider the code:
import numpy as np
x = np.ones((2,3))
y = np.ones((3,2))
z = x + y
What error will occur and why?
medium
A. ValueError because shapes (2,3) and (3,2) are incompatible for broadcasting
B. TypeError because arrays have different data types
C. No error, result shape is (2,3)
D. SyntaxError due to invalid addition
Solution
Step 1: Check shapes of x and y
x shape is (2,3), y shape is (3,2). Compare dims right to left: 3 vs 2 and 2 vs 3.
Step 2: Apply broadcasting rules
Neither dimension matches or is 1, so broadcasting fails and raises ValueError.
Final Answer:
ValueError because shapes (2,3) and (3,2) are incompatible for broadcasting -> Option A
Quick Check:
Broadcasting fails if dims differ and neither is 1 [OK]
Hint: Broadcast dims must be equal or 1; else error [OK]
Common Mistakes:
Assuming addition works despite shape mismatch
Confusing error type as TypeError or SyntaxError
Ignoring dimension order in shapes
5. You have a 3D array A with shape (4,1,5) and a 2D array B with shape (1,3). You want to add them using broadcasting. What will be the shape of the result?
hard
A. Broadcasting will fail with ValueError
B. (4, 1, 3)
C. (1, 3, 5)
D. (4, 3, 5)
Solution
Step 1: Align shapes by adding missing dimension
A shape is (4,1,5), B shape is (1,3). Treat B as (1,1,3) to match 3D shape.
Step 2: Compare dimensions right to left
For each dim: 5 vs 3 (A's last dim 5, B's last dim 3) - mismatch. This means broadcasting fails.
Step 3: Re-examine dimension matching
Actually, B's shape is (1,3), so when adding to A (4,1,5), B is broadcast to (1,1,3). Compare dims: 5 vs 3 (A's last dim 5, B's last dim 3) - mismatch. NumPy aligns shapes from right: A (4,1,5), B (1,1,3). Last dims 5 and 3 mismatch, so broadcasting fails.
Final Answer:
Broadcasting will fail with ValueError -> Option A
Quick Check:
Mismatch in last dims 5 and 3 causes failure [OK]
Hint: Align dims right to left; mismatch without 1 causes error [OK]
Common Mistakes:
Assuming missing dims auto-align without prepending
Ignoring last dimension mismatch
Thinking broadcasting always works if dims differ
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.