0
0
NumPydata~30 mins

Broadcasting errors and debugging in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Broadcasting errors and debugging
📖 Scenario: Imagine you are working with sales data for a small store. You have daily sales numbers and want to apply a discount factor to each day's sales to see the adjusted sales. However, sometimes the shapes of your data arrays don't match, causing errors.
🎯 Goal: You will create two numpy arrays representing sales and discount factors. Then you will identify and fix a broadcasting error by adjusting the shape of the discount array. Finally, you will print the corrected adjusted sales.
📋 What You'll Learn
Create a numpy array called sales with values [100, 200, 300]
Create a numpy array called discounts with values [0.9, 0.8]
Create a new array adjusted_sales by multiplying sales and discounts with correct shapes to avoid broadcasting errors
Print the adjusted_sales array
💡 Why This Matters
🌍 Real World
In real data science, you often combine data arrays of different shapes. Understanding broadcasting helps you avoid errors and write efficient code.
💼 Career
Data scientists and analysts frequently manipulate arrays and matrices. Debugging broadcasting errors is a key skill to ensure correct calculations.
Progress0 / 4 steps
1
Create the sales and discounts arrays
Import numpy as np. Create a numpy array called sales with values [100, 200, 300]. Create another numpy array called discounts with values [0.9, 0.8].
NumPy
Need a hint?

Use np.array() to create arrays. Remember to import numpy first.

2
Add a shape adjustment for discounts
Create a new variable called discounts_reshaped by reshaping discounts to have shape (2, 1) using reshape.
NumPy
Need a hint?

Use discounts.reshape((2, 1)) to change the shape.

3
Multiply sales and reshaped discounts to get adjusted sales
Create a new variable called adjusted_sales by multiplying discounts_reshaped and sales. This will use broadcasting correctly.
NumPy
Need a hint?

Use the * operator to multiply arrays. Broadcasting works when shapes align properly.

4
Print the adjusted sales array
Print the adjusted_sales array to see the result.
NumPy
Need a hint?

Use print(adjusted_sales) to display the array.