Numpy exercices notebook
Exercice 1:¶
Create a 1-dimensional NumPy array with 5 integers from 0 to 4.
import numpy as np
a = np.array([0, 1, 2, 3, 4])
print(a)
Exercice 2:¶
Create a 2-dimensional NumPy array with shape (2, 3) containing only ones.
a = np.ones((2, 3))
print(a)
Exercice 3:¶
Create a 3-dimensional NumPy array with shape (2, 3, 4) containing only zeros.
a = np.zeros((2, 3, 4))
print(a)
Exercice 4:¶
Create a 2-dimensional NumPy array with shape (3, 4) containing random integers between 0 and 9.
a = np.random.randint(0, 10, size=(3, 4))
print(a)
Exercice 5:¶
Create a 2-dimensional NumPy array with shape (3, 4) and find its dimensions and size.
a = np.zeros((3, 4))
print("Dimensions:", a.ndim)
print("Shape:", a.shape)
print("Size:", a.size)
Exercice 6:¶
Create a 2-dimensional NumPy array with shape (3, 4) and calculate the sum of all its elements.
a = np.random.randint(0, 10, size=(3, 4))
print(a)
print("Sum:", np.sum(a))
Exercice 7:¶
Create a 2-dimensional NumPy array with shape (3, 4) and find the minimum and maximum value in each row.
a = np.random.randint(0, 10, size=(3, 4))
print(a)
print("Minimum values:", np.min(a, axis=1))
print("Maximum values:", np.max(a, axis=1))
Exercice 8:¶
Create a 2-dimensional NumPy array with shape (3, 4) and replace all the odd numbers with -1.
a = np.random.randint(0, 10, size=(3, 4))
print("Before:", a)
a[a % 2 == 1] = -1
print("After:", a)
Exercice 9:¶
Create a 2-dimensional NumPy array with shape (3, 4) and extract the elements in the second and third row and the second and third column.
a = np.random.randint(0, 10, size=(3, 4))
print(a)
b = a[1:3, 1:3]
print(b)
Exercice 10:¶
Create a 2-dimensional NumPy array with shape (3, 4) and multiply each element by 2.
a = np.random.randint(0, 10, size=(3, 4))
print("Before:", a)
a = a * 2
print("After:", a)