Broadcasting across columns
Recall that when broadcasting across columns, NumPy requires you to be explicit that it should broadcast a vertical array, and horizontal and vertical 1D arrays do not exist in NumPy. Instead, you must first create a 2D array to declare that you have vertical data. Then, NumPy creates a copy of this 2D vertical array for each column and applies the desired operation.
A Python list called monthly_growth_rate
with len()
of 12
is available. This list represents monthly year-over-year expected growth for the economy; your task is to use broadcasting to multiply this list by each column in the monthly_sales
array. The monthly_sales
array is loaded, along with numpy
as np
.
This exercise is part of the course
Introduction to NumPy
Exercise instructions
- Convert
monthly_growth_rate
, currently a Python list, into a one-dimensional NumPy array calledmonthly_growth_1D
. - Reshape
monthly_growth_1D
so that it is broadcastable column-wise acrossmonthly_sales
; call the new arraymonthly_growth_2D
. - Using broadcasting, multiply each column in
monthly_sales
bymonthly_growth_2D
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Convert monthly_growth_rate into a NumPy array
monthly_growth_1D = ____
# Reshape monthly_growth_1D
monthly_growth_2D = monthly_growth_1D.____
# Multiply each column in monthly_sales by monthly_growth_2D
print(____)