Adam Lee
Adam Lee

Reputation: 3003

Finding the min or max sum of a row in an array

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

Upvotes: 7

Views: 7849

Answers (4)

Olivier Melançon
Olivier Melançon

Reputation: 22294

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

Upvotes: 1

dawg
dawg

Reputation: 103764

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

Upvotes: 7

sacuL
sacuL

Reputation: 51335

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

Upvotes: 1

Burton2000
Burton2000

Reputation: 2072

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

Upvotes: 1

Related Questions