Avec numpy il existe la fonction where pour retrouver les indices des éléments d'une matrice vérifiant une condition donnée. Considérons la matrice M=[4,1,8,6,2,1], on veut retrouver l'indice de l'élément ou M=2, dans ce cas la fonction where donne 4 car l'élément est sur la quatrième colonne (Rappel: base 0 par défaut sous python)
>>> import numpy as np>>> M = np.array([4,1,8,6,2,1])>>> np.where(M == 2)(array([4]),)
Autre exemple pour une matrice (2,3):
>>> M = np.array([[4,1,8],[5,2,1]])>>> Marray([[4, 1, 8],[5, 2, 1]])>>> np.where(M == 1)(array([0, 1]), array([1, 2]))
Autre exemple avec deux conditions (M > 2) & (M < 8) (Attention à la syntaxe):
>>> M = np.array([[4,1,8],[5,2,1]])>>> np.where((M > 2) & (M < 8) )(array([0, 1]), array([0, 0]))
Références
- numpy.where | scipy doc
- Numpy where function multiple conditions | stackoverflow
- How to use numpy.where with logical operators | stackoverflow
- Is there a Numpy function to return the first index of something in an array? | stackoverflow
