2

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]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
Roms
  • 23
  • 4

3 Answers3

2

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])
Ehsan
  • 12,072
  • 2
  • 20
  • 33
  • Thanks, would there be a way to add the absolute value in the max(abs(min), max)? – Roms Jun 11 '20 at 15:56
  • Also, I want to keep the same dimension in the output array. For instance here output.shape should still be (16,16,8). – Roms Jun 11 '20 at 16:30
1
output = np.where((abs(array_min[...,7]) > array_max[..., 7])[..., None], array_min, array_max)
tstanisl
  • 13,520
  • 2
  • 25
  • 40
  • 1
    This leads to "operands could not be broadcast together with shapes (16,16) (16,16,8) (16,16,8) ". Am I missing something? – Roms Jun 11 '20 at 16:32
1
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.

Grigory Feldman
  • 405
  • 3
  • 7