Extracting minimum values per row using numpy

耗尽温柔 提交于 2019-12-12 12:46:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29301904/extracting-minimum-values-per-row-using-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!