Numpy, getting a min or max element of three elements

I have a three dimensional array:

 y = np.random.randint(1,5 ,(50,50,3))

I want to calculate max and min along the third axis (3 elements) and then divide by the remaining number / element.

So something like this:

x = (np.max(y, axis =2) - 2*np.min(y, axis =2))/the third number

I do not know how to get the third number. To beware, the third number has the ability to be equal to the minimum or maximum value:

eg. (5,5,1)

+4
source share
3 answers

Usually sorting overflows when you only need max and min, in which case I think this is the easiest. It directly puts the numbers we want in places that are easy to access, without any complicated arithmetic.

y = np.random.randint(1, 5, (50, 50,3))
y2 = y.copy()
y2.sort(axis=2)
sout = (y2[...,2] - 2 * y2[...,0]) / y2[...,1]

which gives me

In [68]: (sout == divakar_out).all()
Out[68]: True

which is usually a good sign .; -)

+5
source

np.median

(y.max(2) - 2 * y.min(2)) / np.median(y, 2)
+5

№ 1

The focus on finding the third is to subtract from 3those maximum and minimum indices. The borderline case would be when the indices max and min coincide, i.e. All three elements along the last axis are the same, for which the index of the third element will also be the same.

So we will have one solution:

max_idx = y.argmax(2)
min_idx = y.argmin(2)

rem_idx = np.where(max_idx == min_idx, max_idx, 3 - max_idx - min_idx)
out = (y[all_idx(max_idx, 2)] -2*y[all_idx(min_idx, 2)])/y[all_idx(rem_idx, 2)]

Helper function for indexing in ywith indexes -

# https://stackoverflow.com/a/46103129/ @Divakar
def all_idx(idx, axis):
    grid = np.ogrid[tuple(map(slice, idx.shape))]
    grid.insert(axis, idx)
    return tuple(grid)

Approach # 2

We could get the summation along the axis and subtract the min and max values ​​to get the third element and just connect this to the formula -

maxv = np.max(y, axis =2)
minv = np.min(y, axis =2)
x = (maxv - 2*minv)/(y.sum(2) - maxv - minv)
+4
source

Source: https://habr.com/ru/post/1689096/


All Articles