Supposons que l'on veuille supprimer les éléments négatifs d'une matrice à une dimension A, on peut alors utiliser un simple filtre A[A > 0], exemple:
>>> A = np.array(([-1,2,4,7,-3,9,3]))>>> A[A > 0]array([2, 4, 7, 9, 3])
Attention, pour une matrice à deux dimensions ou plus, le filtre A[A > 0] retourne une matrice à une dimension, illustration:
>>> A = np.array(([1,2,-3],[4,-5,6],[-7,8,-9]))>>> Aarray([[ 1, 2, -3],[ 4, -5, 6],[-7, 8, -9]])>>> A[A > 0]array([1, 2, 4, 6, 8])
On peut aussi utiliser numpy.where pour obtenir les indices des éléments positifs (>0) de la matrice A:
>>> A = np.array(([1,2,-3],[4,-5,6],[-7,8,-9]))>>> Aarray([[ 1, 2, -3],[ 4, -5, 6],[-7, 8, -9]])>>> np.where( A > 0)(array([0, 0, 1, 1, 2]), array([0, 1, 0, 2, 1]))
ou encore créer un "mask":
>>> import numpy.ma as ma>>> B = ma.masked_array(A, mask = ( A > 0) )>>> Bmasked_array(data =[[-- -- -3][-- -5 --][-7 -- -9]],mask =[[ True True False][ True False True][False True False]],fill_value = 999999)>>>
Références
| Liens | Site |
|---|---|
| Deleting certain elements from numpy array using conditional checks | stackoverflow |
| Numpy where function multiple conditions | stackoverflow |
| numpy.where | scipy doc |
| numpy.ma.masked_where | scipy doc |
| Numpy array, how to select indices satisfying multiple conditions? | stackoverflow |
| how to apply a mask from one array to another array? | stackoverflow |
