2

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])

Low Yield Bond
  • 327
  • 5
  • 10

2 Answers2

3

You can use:

arr = np.array([a,b,c])
arr[np.argmax(np.abs(arr), axis=0), np.arange(arr.shape[1])]
llllllllll
  • 16,169
  • 4
  • 31
  • 54
0

Instead of giving key function as absolute make as integer function.


Code

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=int)

print(mxs)
DRV
  • 676
  • 1
  • 8
  • 22