# Create exercise_array
exercise_array = np.array([1, 14, 22, 47, 58, 67])NumPy Arrays - Answer Key
Exercise 1
- Create a NumPy array holding the values
1,14,22,47,58and67and assign it toexercise_array
- Retrieve the second, third and fourth elements from
exercise_array
# Retrieve second, third and fourth elements from exercise_array
print(exercise_array[1:4])[14 22 47]
- Retrieve the values less than 25 from
exercise_array
# Subset array to the values less than 25
print(exercise_array[exercise_array < 25])[ 1 14 22]
- Reshape
exercise_arrayinto a matrix have three rows with two columns each and assign it toexercise_matrix.
# Reshape exercise_array to be a matrix of 3 rows and 2 columns
exercise_matrix = exercise_array.reshape(3, 2)
print(exercise_matrix)[[ 1 14]
[22 47]
[58 67]]
- Retrieve the value in the third row, second column of
exercise_matrix
# Retrieve the value in the third row, second column of exercise_matrix
print(exercise_matrix[2,1])67
Exercise 2
- Test out the following functions on the
reshaped_matrixarray that we created earlier and describe what the output is for each function:np.shape()np.ndim()np.size()
np.shape(): This function returns the dimensions of the array as a tuple. For example,np.shapeon a 2 x 5 2-dimensional array would return(2, 5).
# Retrieve the dimensions of matrix_arange
np.shape(reshaped_matrix)(2, 5)
np.ndim(): This function returns the number of dimensions of the array.
# Retrieve number of the dimensions of matrix_arange
np.ndim(reshaped_matrix)2
np.size(): This function returns the total number of elements in the array. For example,np.sizeon a 2 x 5 2-dimensional array would return10(2 rows x 5 columns = 10 elements).
# Retrieve number of elements within matrix_arange
np.size(reshaped_matrix)10
Reuse
CC-BY-4.0