0
0
NumPydata~30 mins

Avoiding broadcasting mistakes in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Avoiding broadcasting mistakes
📖 Scenario: Imagine you are analyzing sales data for a small store. You have daily sales numbers for 5 products over a week. You want to apply a discount to each product's sales but must be careful to avoid mistakes caused by incorrect array shapes in calculations.
🎯 Goal: You will create a NumPy array for sales data, define a discount array, apply the discount correctly using broadcasting, and print the discounted sales.
📋 What You'll Learn
Create a NumPy array called sales with shape (7, 5) representing 7 days and 5 products.
Create a NumPy array called discount with shape (5,) representing discount factors for each product.
Apply the discount to the sales data correctly using broadcasting.
Print the resulting discounted sales array.
💡 Why This Matters
🌍 Real World
Retail stores often apply discounts to products and need to calculate updated sales or revenue correctly using arrays of data.
💼 Career
Data analysts and scientists must understand broadcasting to manipulate multi-dimensional data without errors in Python using NumPy.
Progress0 / 4 steps
1
Create the sales data array
Import NumPy as np and create a NumPy array called sales with these exact values and shape (7, 5):
[[100, 200, 300, 400, 500],
[110, 210, 310, 410, 510],
[120, 220, 320, 420, 520],
[130, 230, 330, 430, 530],
[140, 240, 340, 440, 540],
[150, 250, 350, 450, 550],
[160, 260, 360, 460, 560]]
NumPy
Need a hint?

Use np.array([...]) with the exact nested list of values.

2
Create the discount array
Create a NumPy array called discount with these exact values:
[0.9, 0.8, 0.85, 0.95, 0.9] representing discount factors for each product.
NumPy
Need a hint?

Use np.array([...]) with the exact discount values.

3
Apply the discount using broadcasting
Create a new NumPy array called discounted_sales by multiplying sales with discount using broadcasting. Use the * operator directly.
NumPy
Need a hint?

Use the * operator to multiply sales and discount arrays directly.

4
Print the discounted sales
Print the discounted_sales array to see the final discounted sales values.
NumPy
Need a hint?

Use print(discounted_sales) to display the array.