1

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?

2
  • Are x and y the same shape? Commented Oct 13, 2015 at 15:29
  • I can make them so but I'd be interested in a general answer if there's one Commented Oct 13, 2015 at 15:31

2 Answers 2

3

You are just looking for "pointwise maximum of 2 arrays", which can be obtained with numpy.maximum()

x = np.array([0, 1, 2])
y = np.array([1, 2, 0])
np.maximum(x, y)

outputs array([1, 2, 2])

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.