numpy.maximum() on two 3-D arrays

Viewed 195

I'm looking for the numpy-way to compare two 3-D arrays and return a new 3-D array containing the element-wise maxima based on a given index of the array. Here my value is in [y][x][7] for instance:

output = numpy.zeros((16, 16, 8))
# we want to compare the values in [y,x,7] and only keep the element with max value
for x in range(array_min.shape[1]):
  for y in range(array_min.shape[0]):                
    if abs(array_min[y][x][7]) > array_max[y][x][7]:
      output[y][x] = array_min[y][x]
    else:
      output[y][x] = array_max[y][x]
3 Answers

If I understand you correctly, you only want a specific index on 3rd dimension to be compared. In that case, numpy has a builtin function for this that you can replace your loop with:

output[:,:,7] = np.maximum(array_min[:,:,7], array_max[:,:,7])
output = np.where((abs(array_min[...,7]) > array_max[..., 7])[..., None], array_min, array_max)
array_min = np.random.rand(16,16,8)
array_max = np.random.rand(16,16,8)
out = np.stack([array_min, array_max], axis=0).max(axis=0)

Works for more than 2 arrays.

Related