0
0
NumPydata~15 mins

np.broadcast_to() for explicit broadcasting in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Using np.broadcast_to() for Explicit Broadcasting
📖 Scenario: Imagine you are working with sales data for a small store. You have the sales numbers for one product over a week, but you want to compare it with a target sales array that has the same shape as the weekly data for easy calculations.
🎯 Goal: You will create a numpy array for weekly sales, then use np.broadcast_to() to expand a single target sales value to match the weekly sales shape. Finally, you will print the broadcasted target sales array.
📋 What You'll Learn
Create a numpy array called weekly_sales with the exact values: [10, 15, 20, 25, 30, 35, 40]
Create a variable called target_sales with the exact value 20
Use np.broadcast_to() to create a new array called broadcasted_target that has the same shape as weekly_sales but with all values equal to target_sales
Print the broadcasted_target array
💡 Why This Matters
🌍 Real World
Broadcasting helps when you want to compare or combine data of different shapes without manually repeating values. For example, comparing daily sales to a fixed target.
💼 Career
Data scientists often use broadcasting to efficiently perform operations on arrays of different shapes, saving time and memory.
Progress0 / 4 steps
1
Create the weekly sales data array
Create a numpy array called weekly_sales with these exact values: [10, 15, 20, 25, 30, 35, 40]
NumPy
Need a hint?

Use np.array() to create the array with the exact list of numbers.

2
Set the target sales value
Create a variable called target_sales and set it to the integer value 20
NumPy
Need a hint?

Just assign the number 20 to the variable target_sales.

3
Broadcast the target sales value to match weekly sales shape
Use np.broadcast_to() to create a new array called broadcasted_target that has the same shape as weekly_sales but with all values equal to target_sales
NumPy
Need a hint?

Use np.broadcast_to(target_sales, weekly_sales.shape) to expand the single value to the shape of weekly_sales.

4
Print the broadcasted target sales array
Print the broadcasted_target array to see the result
NumPy
Need a hint?

Use print(broadcasted_target) to display the array.