7

How can I quickly find the min or max sum of the elements of a row in an array?

For example:

1, 2
3, 4
5, 6
7, 8

The minimum sum would be row 0 (1 + 2), and the maximum sum would be row 3 (7 + 8)

  print mat.shape
  (8, 1, 2)  
  print mat
 [[[-995.40045 -409.15112]]

 [[-989.1511  3365.3267 ]]

 [[-989.1511  3365.3267 ]]

 [[1674.5447  3035.3523 ]]

 [[   0.         0.     ]]

 [[   0.      3199.     ]]

 [[   0.      3199.     ]]

 [[2367.      3199.     ]]]
dawg
  • 98,345
  • 23
  • 131
  • 206
Adam Lee
  • 2,983
  • 7
  • 35
  • 47

4 Answers4

7

In native Python, min and max have key functions:

>>> LoT=[(1, 2), (3, 4), (5, 6), (7, 8)]
>>> min(LoT, key=sum)
(1, 2)
>>> max(LoT, key=sum)
(7, 8)

If you want the index of the first min or max in Python, you would do something like:

>>> min(((i, t) for i, t in enumerate(LoT)), key=lambda (i,x): sum(x))
(0, (1, 2))

And then peel that tuple apart to get what you want. You also could use that in numpy, but at unknown (to me) performance cost.


In numpy, you can do:

>>> a=np.array(LoT)
>>> a[a.sum(axis=1).argmin()]
array([1, 2])
>>> a[a.sum(axis=1).argmax()]
array([7, 8])

To get the index only:

>>> a.sum(axis=1).argmax()
3
dawg
  • 98,345
  • 23
  • 131
  • 206
  • The Numpy way is generally more performant. Explanation: https://stackoverflow.com/a/8385658/5398884 – Tim Jul 02 '22 at 22:04
1

You can do this using np.argmin and np.sum:

array_minimum_index = np.argmin([np.sum(x, axis=1) for x in mat])
array_maximum_index = np.argmax([np.sum(x, axis=1) for x in mat])

For your array, this results in array_minimum_index = 0 and array_maximum_index = 7, as your sums at those indices are -1404.55157 and 5566.0

To simply print out the values of the min and max sum, you can do this:

array_sum_min = min([np.sum(x,axis=1) for x in mat])
array_sum_max = max([np.sum(x,axis=1) for x in mat])
sacuL
  • 49,704
  • 8
  • 81
  • 106
1
x = np.sum(x,axis=1)
min_x = x.min()
max_x = x.max()

presuming x is 4,2 array use np.sum to sum across the rows, then .min() returns the min value of your array and .max() returns the max value

Burton2000
  • 1,972
  • 13
  • 23
1

You can use min and max and use sum as their key.

lst = [(1, 2), (3, 4), (5, 6), (7, 8)]

min(lst, key=sum) # (1, 2)
max(lst, key=sum) # (7, 8)

If you want the sum directly and you do not care about the tuple itself, then map can be of help.

min(map(sum, lst)) # 3
max(map(sum, lst)) # 15
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73