0
0
NumPydata~5 mins

np.broadcast_to() for explicit broadcasting in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does np.broadcast_to() do in NumPy?

np.broadcast_to() takes a smaller array and "stretches" it to a larger shape without copying data. It allows you to explicitly broadcast an array to a new shape.

Click to reveal answer
beginner
Why is broadcasting useful in data science?

Broadcasting lets you perform operations on arrays of different shapes easily, like adding a single value to every element in a matrix, without writing loops.

Click to reveal answer
intermediate
What happens if you try to broadcast to an incompatible shape with np.broadcast_to()?

NumPy will raise a ValueError because the shapes cannot be matched according to broadcasting rules.

Click to reveal answer
beginner
Example: What is the output shape of np.broadcast_to(np.array([1, 2, 3]), (3, 3))?

The output shape is (3, 3). The 1D array [1, 2, 3] is broadcasted to 3 rows, repeating the original array in each row.

Click to reveal answer
intermediate
Does np.broadcast_to() copy data or create a view?

It creates a view with broadcasted shape, so no new data is copied. This is memory efficient.

Click to reveal answer
What is the main purpose of np.broadcast_to()?
ATo sort an array
BTo reshape an array by changing its data
CTo copy an array multiple times
DTo explicitly broadcast an array to a new shape
If you have arr = np.array([5]), what will np.broadcast_to(arr, (2,3)) produce?
AAn error because shapes don't match
B(2,3) array filled with 5
C(1,) array with 5
D(3,2) array filled with 5
What error occurs if broadcasting shapes are incompatible?
AValueError
BTypeError
CIndexError
DKeyError
Does np.broadcast_to() create a copy of the data?
AYes, it copies data
BOnly for 2D arrays
CNo, it creates a view
DOnly if the array is large
Which of these shapes can np.broadcast_to() broadcast arr.shape = (3,) to?
A(3, 3)
B(4, 4)
C(3, 4)
D(2, 2)
Explain how np.broadcast_to() helps when working with arrays of different shapes.
Think about how you can stretch a small array to match a bigger one without loops.
You got /4 concepts.
    Describe a real-life example where you might use np.broadcast_to() in data analysis.
    Imagine adding a tax rate to every price in a table.
    You got /4 concepts.