Extracting minimum values per row using numpy
Asked Answered
B

1

9

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.

Bally answered 27/3, 2015 at 13:32 Comment(0)
S
15

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.

Scansorial answered 27/3, 2015 at 13:34 Comment(2)
while doing as you say I am getting an error " 'list' object has no attribute 'min' " that is min is not a part of a matrix should i need to run any operation for getting min?Icterus
\\\n import numpy \\\n numpy.miin(numbers,axis=1) workedIcterus

© 2022 - 2024 — McMap. All rights reserved.