Say I have two arrays, x and y, and want an array whose element i is x[i] if x[i] > y[i]; otherwise, it is y[i].
Is there some pre-written method in numpy to do this?
Say I have two arrays, x and y, and want an array whose element i is x[i] if x[i] > y[i]; otherwise, it is y[i].
Is there some pre-written method in numpy to do this?
A general way to do this is to construct a truth table and then use that to select indices from x or y
eg.
a = np.random.rand(10)
b = np.random.rand(10)
truth_table = a > b
# where truth_table[i] is True, select a[i] else b[i]
new_arr = np.where(truth_table, a, b)
# in one step
new_arr = np.where(a > b, a, b)
assert ((a >= b) == (new_arr == a)).all()
assert ((a <= b) == (new_arr == b)).all()
numpy.where is more powerful than this, in that it can broadcast one or both of input arrays to the same shape as truth table. eg.
# where a[i] is greater than b[i], select a[i], else 0
new_arr = np.where(a > b, a, 0)