Bases des tableaux NumPy
NumPy signifie Python numérique. Il s'agit d'une bibliothèque Python utilisée pour travailler avec un tableau. En Python, nous utilisons la liste pour le tableau mais son traitement est lent. Le tableau NumPy est un puissant objet tableau à N dimensions et est utilisé dans les capacités d'algèbre linéaire, de transformation de Fourier et de nombres aléatoires. Il fournit un objet tableau beaucoup plus rapide que les listes Python traditionnelles.
Types de tableau :
- Tableau unidimensionnel
- Tableau multidimensionnel
Tableau unidimensionnel :
Un tableau unidimensionnel est un type de tableau linéaire.
Tableau unidimensionnel
Exemple:
Python3 # importing numpy module import numpy as np # creating list list = [1, 2, 3, 4] # creating numpy array sample_array = np.array(list) print('List in python : ', list) print('Numpy Array in python :', sample_array)
Sortir:
List in python : [1, 2, 3, 4] Numpy Array in python : [1 2 3 4]
Vérifiez le type de données pour la liste et le tableau :
Python3 print(type(list_1)) print(type(sample_array))
Sortir:
Tableau multidimensionnel :
Les données des tableaux multidimensionnels sont stockées sous forme de tableau.
Tableau bidimensionnel
Exemple:
Python3 # importing numpy module import numpy as np # creating list list_1 = [1, 2, 3, 4] list_2 = [5, 6, 7, 8] list_3 = [9, 10, 11, 12] # creating numpy array sample_array = np.array([list_1, list_2, list_3]) print('Numpy multi dimensional array in python
', sample_array) Sortir:
Numpy multi dimensional array in python [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
Note: utiliser [ ] opérateurs à l'intérieur de numpy.array() pour le multidimensionnel
Anatomie d'un tableau :
1. Axe : L'axe d'un tableau décrit l'ordre d'indexation dans le tableau.
Axe 0 = unidimensionnel
Axe 1 = Bidimensionnel
Axe 2 = Trois dimensions
2. Forme : Le nombre d'éléments avec chaque axe. Il s'agit d'un tuple.
Exemple:
Python3 # importing numpy module import numpy as np # creating list list_1 = [1, 2, 3, 4] list_2 = [5, 6, 7, 8] list_3 = [9, 10, 11, 12] # creating numpy array sample_array = np.array([list_1, list_2, list_3]) print('Numpy array :') print(sample_array) # print shape of the array print('Shape of the array :', sample_array.shape) Sortir:
Numpy array : [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] Shape of the array : (3, 4)
Exemple:
Python3 import numpy as np sample_array = np.array([[0, 4, 2], [3, 4, 5], [23, 4, 5], [2, 34, 5], [5, 6, 7]]) print('shape of the array :', sample_array.shape) Sortir:
shape of the array : (5, 3)
3. Rang : Le rang d'un tableau est simplement le nombre d'axes (ou de dimensions) dont il dispose.
Le tableau unidimensionnel a le rang 1.
Rang 1
Le tableau bidimensionnel a le rang 2.
Rang 2
4. Objets de type de données (dtype) : Les objets de type de données (dtype) sont une instance de numpy.dtype classe. Il décrit comment les octets du bloc de mémoire de taille fixe correspondant à un élément du tableau doivent être interprétés.
Exemple:
Python3 # Import module import numpy as np # Creating the array sample_array_1 = np.array([[0, 4, 2]]) sample_array_2 = np.array([0.2, 0.4, 2.4]) # display data type print('Data type of the array 1 :', sample_array_1.dtype) print('Data type of array 2 :', sample_array_2.dtype) Sortir:
Data type of the array 1 : int32 Data type of array 2 : float64
Une manière différente de créer un Numpy Array :
1. numpy.array() : L'objet tableau Numpy dans Numpy s'appelle ndarray. Nous pouvons créer ndarray en utilisant numpy.array() fonction.
Syntaxe: numpy.array (paramètre)
Exemple:
Python3 # import module import numpy as np #creating a array arr = np.array([3,4,5,5]) print('Array :',arr) Sortir:
Array : [3 4 5 5]
2. numpy.fromiter() : La fonction fromiter() crée un nouveau tableau unidimensionnel à partir d'un objet itérable.
Syntaxe: numpy.fromiter(itérable, dtype, count=-1)
Exemple 1:
Python3 #Import numpy module import numpy as np # iterable iterable = (a*a for a in range(8)) arr = np.fromiter(iterable, float) print('fromiter() array :',arr) Sortir:
tableau fromiter() : [ 0. 1. 4. 9. 16. 25. 36. 49.]
Exemple 2 :
Python3 import numpy as np var = 'Geekforgeeks' arr = np.fromiter(var, dtype = 'U2') print('fromiter() array :', arr) Sortir:
tableau fromiter() : ['G' 'e' 'e' 'k' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']
3. numpy.arange() : Il s'agit d'une fonction NumPy intégrée qui renvoie des valeurs régulièrement espacées dans un intervalle donné.
Syntaxe: numpy.arange([start, ]stop, [step, ]dtype=Aucun)
Exemple:
Python3 import numpy as np np.arange(1, 20 , 2, dtype = np.float32)
Sortir:
array([ 1., 3., 5., 7., 9., 11., 13., 15., 17., 19.], dtype=float32)
4. numpy.linspace() : Cette fonction renvoie des nombres régulièrement espacés sur une valeur spécifiée entre deux limites.
Syntaxe: numpy.linspace (start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
Exemple 1:
Python3 import numpy as np np.linspace(3.5, 10, 3)
Sortir:
array([ 3.5 , 6.75, 10. ])
Exemple 2 :
Python3 import numpy as np np.linspace(3.5, 10, 3, dtype = np.int32)
Sortir:
array([ 3, 6, 10])
5. numpy.empty() : Cette fonction crée un nouveau tableau de forme et de type donnés, sans initialiser de valeur.
Syntaxe: numpy.empty(shape, dtype=float, order=’C’)
Exemple:
Python3 import numpy as np np.empty([4, 3], dtype = np.int32, order = 'f')
Sortir:
array([[ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11], [ 4, 8, 12]])
6. numpy.ones() : Cette fonction est utilisée pour obtenir un nouveau tableau de forme et de type donnés, rempli de uns (1).
Syntaxe: numpy.ones (forme, dtype = Aucun, commande = 'C')
Exemple:
Python3 import numpy as np np.ones([4, 3], dtype = np.int32, order = 'f')
Sortir:
array([[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]])
7. numpy.zeros() : Cette fonction est utilisée pour obtenir un nouveau tableau de forme et de type donnés, rempli de zéros (0).
Syntaxe: numpy.ones (forme, dtype = Aucun)
Exemple:
Python3 import numpy as np np.zeros([4, 3], dtype = np.int32, order = 'f')
Sortir:
array([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])