Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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.     ]]]
like image 297
Adam Lee Avatar asked Jan 02 '23 16:01

Adam Lee


1 Answers

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
like image 144
dawg Avatar answered Jan 12 '23 22:01

dawg