0

Given a 2D numpy array, e.g. np.array([[1,1,0], [1,2,0], [0,0,4]]), I want to return the sub-array with the minimal sum.

In this case, this would be the array np.array([1,1,0]).

How can I achieve this, ideally only using built-in numpy functions? It seems numpy does not allow specifying a key function, unlike vanilla python.

1
  • 1
    Sum with the axis argument so that you sum along the rows, then find the argmin of that, which will give you the row index into the original array with the minimum sum. Commented Apr 2, 2022 at 21:42

2 Answers 2

2

First we can use the build in function numpy.sum and get sums allong axis 1. How a numpy array is indexed can be found here.

    array = np.array([[1,1,0], [1,2,0], [0,0,4]])
    internal_sums = np.sum(array, axis=1)

Now we have all the sums stored in the variable 'internal_sums'. Next we use the numpy function 'numpy.argmin' to get the index of the minimal sum.

    minsum_index = np.argmin(internal_sums)

Now we simply get the array at the correct index

    minsum_array = array[minsum_index]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Despite being longer than min(array, key=sum), it is actually much faster using numpy, just as I hoped. Speed for 10,000 executions: Python: 1.03177 seconds Numpy: 0.05466 seconds
2

To add on to the excellent answer above, you can also use the ndarray methods, which lets you squeeze it all into one line!

array = np.array([[1,1,0], [1,2,0], [0,0,4]])
min_array = array[array.sum(1).argmin()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.