给定多个相同大小的 numpy 数组,我想创建一个相同大小的数组,其中包含数组的极值。
我有一个可行的解决方案,但希望以一种更Pythonic的方式来完成此操作,如果可能的话,不使用for循环。
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]]
我一直在考虑
numpy.maximum.reduce
和numpy.minimum.reduce
的组合,但无法重现上述结果。
您可以使用以下内容:
w = np.dstack([a,b,c])
y = np.abs(w)
x = np.argmax(y, axis=-1)
z = np.take_along_axis(y, np.expand_dims(x, axis=-1), axis=-1)
np.reshape(z, (2,2))
array([[-3, 2],
[5, -5]])