Find the maximum value of each element in a 3D array and save them as a new array in python

Viewed 121

I have a numpy array that is roughly (x,y,z) = (100, 150, 25) and I want to find the maximum value of each x,y array element (ie, compare the [1][1] from all subarrays and find the maximum). I then want to save these values to a separate 2d array of shape (x, y) = (100, 150). I have included the below code as an example. Thanks!

import numpy as np

a = np.array([[[6, 7], [3, 4], [2, 7]], [[1, 2], [5, 8], [3, 5]]])
print(a)

#some function that finds the maximum of each element and saves it to a new 2d array
desired_output = np.array([[6,7], [5, 8], [3, 7]])
print(desired_output)
1 Answers

The solution to your problem (probably):

a.max(axis=0)

Since I'm unsure of how exactly your array is formatted, you might be looking for axis=1 or axis=2. But according to the example you provided, axis=0 should be correct.

Some notes: So, the technical shape of your array is probably (25, 100, 150). Using a different example (where all the dimensions have different numbers so we don't get confused):

arr = [[[x, x, x],
        [x, x, x],
        [x, x, x],
        [x, x, x]],

       [[x, x, x],
        [x, x, x],
        [x, x, x],
        [x, x, x]]]

arr is a 3d matrix, with dimensions 2x4x3

Why this works: Numpy's operations, when you specify an axis, collapse that axis and create a new shape. Below are some examples.

Collapsing along axis 0, we get a 1x4x3 --> 4x3 shape:

[[x, x, x],
 [x, x, x],
 [x, x, x],
 [x, x, x]]

Collapsing along axis 1, we get a 2x1x3 --> 2x3 shape:

[[x, x, x],
 [x, x, x]]

Collapsing along axis 2, we get a 2x4x1 --> 2x4 shape:

[[x, x, x, x],
 [x, x, x, x]]
Related