np = 4
arr = np.array([2, 3, np, 5])
print(arr)
# a) [2, 3, 4, 5]
# b) numpy.ndarray([2, 3, 4, 5])Review: NumPy Fundamentals
Module 3: NumPy
Review of Session 3.1: Fundamentals
Exercise
What is going to be the final value of x?
Solution
Remember that Python will only remember the last variable declaration with the same name. Doing the code above with np is similar to:
x = 10
x = 2
print(x)The code fails because np ceases to be NumPy!
import numpy as np
Exercise
How would you replace the for loop in the code below, for a 1D NumPy array?
arr = np.array([1, 2, 3, 4, 5])
result = 0
for i in arr:
result = result + i
print(result)arr = np.array([1, 2, 3, 4, 5])
# Option A
result = np.cumsum(arr)
# Option B
result = np.sum(arr)
# Option C
result = np.loop(arr)
Solution
When we do cumsum to a higher dimensional array, NumPy first flattens that array.
arr = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(np.cumsum(arr))
Exercise
How do you check the number of dimensions of a NumPy array?
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Option A
print(arr.shape)
# Option B
print(arr.ndim)
# Option C
print(arr.ndim())
# Option D
print(np.arr.ndim)
Exercise
I have a colored image represented by a 3D array img. I want to know its width and height. Which one of the following lines of code will give me that information?
img = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
# Option A
height, width = img.shape
# Option B
height, width, _ = img.shape
# Option C
height, width = img.shape(:2)
Exercise
An empty array is a NumPy array with no elements inside. What of the following lines will NOT initialize an empty array?
# Option A
x = np.array()
# Option B
x = np.array([])
# Option C
x = np.zeros(0).astype(int)
# Option D
# All of the above fail.