Basic NumPy Arrays and Operations

This is a formative test. It is an occasion to practice the course material. It does not contribute to your final grade.

Using the topics covered within the workshops (or otherwise), complete the questions below.

Make sure to use any described variable names exactly and do not change the name of this file. This ensures the nbgrader tool can grade your work correctly.


Question 1

1A) Create a NumPy array called numbers containing the values [1, 3, 5, 7, 9].

NoteHint

Use np.array([1, 3, 5, 7, 9]) to create a NumPy array from a list.

TipFully worked solution
numbers = np.array([1, 3, 5, 7, 9])

1B) Create a NumPy array called zeros_array containing 8 zeros using a NumPy function.

NoteHint

Use np.zeros(8) to create an array with 8 zeros.

TipFully worked solution
zeros_array = np.zeros(8)

Question 2

2A) Access the third element (value 30) from the data array and assign it to a variable called third_element.

NoteHint

The third element has index 2.

TipFully worked solution
third_element = data[2]

2B) Create a slice of the data array containing the last three elements and assign it to last_three.

NoteHint

Use negative indexing: data[-3:] to get the last three elements.

TipFully worked solution
last_three = data[-3:]
# Alternative solution:
# last_three = data[2:]

Question 3

3A) Multiply all elements in the values array by 3 and assign the result to tripled.

NoteHint

NumPy allows element-wise operations: values * 3.

TipFully worked solution
tripled = values * 3

3B) Add the arrays values and tripled together element-wise and assign to sum_array.

NoteHint

Use values + tripled for element-wise addition.

TipFully worked solution
sum_array = values + tripled

Question 4

4A) Create a NumPy array called range_array containing integers from 0 to 9 using np.arange().

NoteHint

Use np.arange(10) to create integers from 0 to 9.

TipFully worked solution
range_array = np.arange(10)

4B) Calculate the mean (average) of the range_array and assign it to a variable called mean_value.

NoteHint

Use np.mean(range_array) or range_array.mean().

TipFully worked solution
mean_value = np.mean(range_array)
# or
mean_value = range_array.mean()

Question 5

5A) Find all elements in the measurements array that are greater than 2.5 and assign them to filtered_data.

NoteHint

Use Boolean indexing: measurements[measurements > 2.5].

TipFully worked solution
filtered_data = measurements[measurements > 2.5]

5B) Count how many elements in the measurements array are greater than the mean of the array. Assign this count to count_above_mean.

NoteHint

First calculate the mean, then use np.sum(measurements > mean_value) to count True values.

TipFully worked solution
mean_val = np.mean(measurements)
count_above_mean = np.sum(measurements > mean_val)
# or in one line:
count_above_mean = np.sum(measurements > np.mean(measurements))