Numpy
De Octet.ca
Cet article porte sur la librairie python numpy.
API[modifier]
where[modifier]
Exemple d'utilisation de numpy.where
>>> from numpy import * >>> a = array([3,5,7,9]) >>> b = array([10,20,30,40]) >>> c = array([2,4,6,8]) >>> where(a <= 6, b, c) array([10, 20, 6, 8]) >>> where(a <= 6, b, -1) array([10, 20, -1, -1]) >>> indices = where(a <= 6) # returns a tuple; the array contains indices. >>> indices (array([0, 1]),) >>> b[indices] array([10, 20]) >>> b[a <= 6] # an alternative syntax array([10, 20]) >>> d = array([[3,5,7,9],[2,4,6,8]]) >>> where(d <= 6) # tuple with first all the row indices, then all the column indices (array([0, 0, 1, 1, 1]), array([0, 1, 0, 1, 2]))
Be aware of the difference between x[list of bools] and x[list of integers]! #!python numbers=disable >>> from numpy import * >>> x = arange(5,0,-1) >>> print x [5 4 3 2 1] >>> criterion = (x <= 2) | (x >= 5) >>> criterion array([True, False, False, True, True], dtype=bool) >>> indices = where(criterion, 1, 0) >>> print indices [1 0 0 1 1] >>> x[indices] # integers! array([4, 5, 5, 4, 4]) >>> x[criterion] # bools! array([5, 2, 1]) >>> indices = where(criterion) >>> print indices (array([0, 3, 4]),) >>> x[indices] array([5, 2, 1])