Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting minimum values per row using numpy

I have a question and I could not find the answer on the internet nor on this website. I am sure it is very easy though. Let's say I have a set of 20 numbers and I have them in a 5x4 matrix:

numbers = np.arange(20).reshape(5,4) 

This yields the following matrix:

[ 0,  1,  2,  3]
[ 4,  5,  6,  7]
[ 8,  9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]

Now I would like to have the minimum value of each row, in this case amounting to 0,4,8,12,16. However, I would like to add that for my problem the minimum value is NOT always in the first column, it can be at a random place in the matrix (i.e. first, second, third or fourth column for each row). If someone could shed some light on this it would be greatly appreciated.

like image 260
user3891296 Avatar asked Mar 27 '15 13:03

user3891296


1 Answers

You just need to specify the axis across which you want to take the minimum. To find the minimum value in each row, you need to specify axis 1:

>>> numbers.min(axis=1)
array([ 0,  4,  8, 12, 16])

For a 2D array, numbers.min() finds the single minimum value in the array, numbers.min(axis=0) returns the minimum value for each column and numbers.min(axis=1) returns the minimum value for each row.

like image 111
Alex Riley Avatar answered Oct 15 '22 16:10

Alex Riley