NumPy Exercises
Problem 1: Create a 1D NumPy array containing the numbers from 1 to 10. Then, calculate the square of each number in that array without using a loop.
numpy-exercises.py
import numpy as np
# 1. Create the array
numbers = np.arange(1, 11)
# 2. Square each number
squared_numbers = numbers ** 2
print("Original Array:", numbers)
print("Squared Array:", squared_numbers)
Problem 2: Create a 1D NumPy array containing the numbers from 15 to 25. Extract and print only the even numbers from this array.
numpy-exercises.py
import numpy as np
# 1. Create the array
data = np.arange(15, 26)
# 2. Create a boolean mask for even numbers
is_even = (data % 2 == 0)
# 3. Filter the array using the mask
even_numbers = data[is_even]
# Alternatively, in one line:
# even_numbers = data[data % 2 == 0]
print("Original Data:", data)
print("Even Numbers:", even_numbers)
Problem 3: Create a 1d NumPy array containing the numbers from 0 to 8. Reshape this array into a 3x3 two-dimensional matrix. Then, extract the value in the center of the matrix.
numpy-exercises.py
import numpy as np
# 1. Create the 1D array and reshape it
flat_array = np.arange(9)
matrix = flat_array.reshape(3, 3)
# 2. Extract the center value (Row index 1, Column index 1)
center_value = matrix[1, 1]
print("3x3 Matrix:
", matrix)
print("
Center Value:", center_value)