1>>> a = np.arange(10)
2>>> a
3array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
4>>> np.where(a < 5, a, 10*a)
5array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
6
1import numpy as np
2
3# Return elements chosen from x or y depending on condition.
4a = np.arange(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5single_where = np.where((a<5),-1,a) # [-1, -1, -1, -1, -1, 5, 6, 7, 8, 9]
6multiple_where = np.where((a<5),-1,np.where((a>5),0,a)) # [-1, -1, -1, -1, -1, 5, 0, 0, 0, 0]
1Parameters:
2condition : When True, yield x, otherwise yield y.
3x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape.
4
5Returns:
6out : [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere.