← retour aux snippets

numpy: where (sélection)

Choisir entre deux tableaux selon condition.

objectif

Choisir entre deux tableaux selon condition.

code minimal

import numpy as np
x = np.array([1,2,3,4])
print(np.where(x%2==0, x, 0).tolist())

utilisation

import numpy as np
x = np.array([1,2,3,4])
print(np.where(x>2, 1, -1).tolist())

variante(s) utile(s)

import numpy as np
x = np.array([1,2,3])
print(np.where(x>1)[0].tolist())

notes

  • where(cond, A, B) vectorisé; indices si B omis.