Issue
Given multiple numpy arrays of same size, I want to create an array of equal size, which contains the extreme values of the arrays.
I have a working solution, but want to do this in a more pythonic way without the for loops if possible.
MWE
import numpy as np
a = np.array([[-1, 2], [3, 4]])
b = np.array([[-3, 1], [5, -2]])
c = np.array([[2, -1], [1, -5]])
m, n = a.shape
out = np.zeros((m, n))
for ii in range(m):
for jj in range(n):
tmp = [a[ii, jj], b[ii, jj], c[ii, jj]]
out[ii, jj] = tmp[np.argmax(np.abs(tmp))]
print(out)
# [[-3, 2], [5, -5]]
I have been thinking about a combination of numpy.maximum.reduce
and numpy.minimum.reduce
, but were not able to reproduce the above result.
Solution
You can use the following:
w = np.dstack([a,b,c])
y = np.abs(w)
x = np.argmax(y, axis=-1)
z = np.take_along_axis(w, np.expand_dims(x, axis=-1), axis=-1)
np.reshape(z, (2,2))
array([[-3, 2],
[5, -5]])
Answered By - C.Nivs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.