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] 

3 Answers 3

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]) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, would there be a way to add the absolute value in the max(abs(min), max)?
Also, I want to keep the same dimension in the output array. For instance here output.shape should still be (16,16,8).
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.

Comments

1
output = np.where((abs(array_min[...,7]) > array_max[..., 7])[..., None], array_min, array_max) 

1 Comment

This leads to "operands could not be broadcast together with shapes (16,16) (16,16,8) (16,16,8) ". Am I missing something?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.