3.4.2. Lab#
Use this assignment to practice the chapter’s concepts and coding skills in runnable Python code.
Sign in from the account menu before you start working on the assignment.
Write and run your code directly in the coding cells.
Multiple submissions are allowed. The highest score is kept.
### Question 1: Array Shape and Totals
# The weekly sales table has one row per department and one column per week.
# 1. Convert sales to a NumPy array named sales_array with np.array().
# 2. Print its shape and its number of values (.shape and .size).
# 3. Total each department across the four weeks with .sum(axis=1).
# Print exactly:
# Shape: (3, 4)
# Values: 12
# Department totals: [82 68 98]
import numpy as np
sales = [[18, 21, 19, 24], [15, 17, 16, 20], [22, 25, 23, 28]]
### Your code starts here.
### Your code ends here.
### Question 2: Vectorized Price Change
# Add the same price increase to every base price without a loop.
# 1. Convert base_prices to a NumPy array.
# 2. Add increase to the whole array and store the result in adjusted_prices.
# 3. Print the adjusted prices and their average with .mean().
# Print exactly:
# Adjusted prices: [13 17 21 25]
# Average adjusted price: 19.0
import numpy as np
base_prices = [10, 14, 18, 22]
increase = 3
### Your code starts here.
### Your code ends here.
### Question 3: Boolean Mask Selection
# Find the stores that met the sales target.
# 1. Convert sales to a NumPy array.
# 2. Build a Boolean mask that is True where sales are at or above target.
# 3. Count the True values with .sum() and select those sales with the mask.
# Print exactly:
# Stores at target: 3
# Selected sales: [120 135 150]
import numpy as np
sales = [95, 120, 88, 135, 150]
target = 100
### Your code starts here.
### Your code ends here.
### Question 4: Universal Functions
# Forecast errors are actual demand minus forecast demand.
# 1. Convert errors to a NumPy array.
# 2. Square every error with np.square() and total them with np.sum().
# 3. Compute the mean absolute error with np.abs() and .mean().
# Print exactly:
# Squared errors: [1 4 4 9]
# Total squared error: 18
# Mean absolute error: 2.0
import numpy as np
errors = [1, -2, 2, -3]
### Your code starts here.
### Your code ends here.
### Question 5: Reproducible Random Sample
# Simulate five days of orders with the seeded generator below.
# 1. Draw five whole numbers from 30 up to (not including) 60 with
# rng.integers(30, 60, size=5) and store them in sample.
# 2. Print the sample and its mean.
# Print exactly:
# Sample: [32 53 49 43 42]
# Sample mean: 43.8
import numpy as np
rng = np.random.default_rng(42)
### Your code starts here.
### Your code ends here.
Question 1
Question 2
Question 3
Question 4
Question 5