is there a more efficient way to perform element-wise maximum with key?
import numpy as np
a = np.array([-2, 2, 4, 0])
b = np.array([-3,-5, 2, 0])
c = np.array([ 1, 1, 1, 1])
mxs = np.empty((4,))
for i in range(4):
mxs[i] = max([a[i], b[i], c[i]], key=abs)
>>> mxs
array([-3., -5., 4., 1.])
Unfortunately, numpy.maximum
does not offer a key
parameter, as it would be nice to be able to do something similar with:
np.maximum.reduce([a,b,c])
You can use:
arr = np.array([a,b,c])
arr[np.argmax(np.abs(arr), axis=0), np.arange(arr.shape[1])]