NumPy Arrays – Practice Questions
Topic 1: Creation of NumPy Arrays
1. You have a NumPy array of integers.
arr = np.array([10, 5, 3, 9, 2, 8, 7, 6, 4, 1])
Write a Python program to find the maximum value and minimum value in the array.
Bonus: find the index of min and max values.
2. You are given a 1D NumPy array containing integers. Implement a function that
replaces all odd numbers in the array with the value -1. Can use Boolean Indexing or
loops
Example:
Input Array: [2, 7, 1, 8, 4, 3, 6]
Modified Array: [2, -1, -1, 8, 4, -1, 6]
3. You have two containers: a Python list and a NumPy array, both containing the
same set of integers. Your task is to demonstrate and compare the efficiency of
element-wise operations between the two containers.
Example:
1. Create a Python list python_list containing integers from 1 to 10.
2. Create a NumPy array numpy_array containing the same integers from 1 to
10.
3. Use a loop to square each element of python_list individually.
4. Use NumPy to square each element of numpy_array directly using vectorized
operations (Element-wise).
5. Measure and compare the execution time of the operations on both
containers.
6. Display the squared values of both the Python list and the NumPy array.
# Measure execution time for Python list and NumPy array separately
start_time = time.time()
# Perform element-wise square using a loop
end_time = time.time()
execution_time = end_time - start_time
Topic 2: Indexing, Slicing, and Basic Operations
4. How do you access the element at the 2nd row and 3rd column of a given NumPy
array?
my_array = np.array([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]])
5. Write code to calculate the sum of all elements in the above given NumPy array.
6. Given two NumPy arrays, a and b, how can you concatenate them vertically?
a = np.array([[1, 2], b = np.array([[5, 6]])
[3, 4]])
7. Calculate the dot product of two NumPy arrays, x and y.
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
Topic 3: Array Iterating and Vectorized Operations
8. Write a NumPy code to find the mean value of each row in a 2D array matrix.
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
9. Given a NumPy array of grades containing exam scores, write code to count the
number of scores above 90.
grades = np.array([85, 92, 88, 94, 78, 95, 99, 67, 89, 91])
10. Create a NumPy array of 20 random integers between 1 and 100. Calculate the
median value.