二维数组python上的最小值 [英] Minimum value on a 2d array python

查看:453
本文介绍了二维数组python上的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下结构的数组,对此结构进行了简化:

I have an array of the following structure which is simplified for this question:

8 2 3 4 5 6
3 6 6 7 2 6
3 8 5 1 2 9
6 4 2 7 8 3

我希望在此2D数组中找到最小值,但是使用内置的min函数会返回值错误:

I wish to find the minimum value in this 2D array however using the inbuilt min function returns a value error:

ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我已经研究了使用np.argmin的替代方法:

I have looked into the alternative of using np.argmin:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html

但是,它仅沿单个轴求值,并沿单个行/列返回最小值的索引,而我希望对整个数组求值,而返回最小值而不是索引.

However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

如果可以返回数组中最低项目的索引值,则从可以轻松找到最低值开始,这也是优选的.

If it is possible to return the index values of the lowest item in the array then that would be preferable also as from that the lowest value can easily be found.

由于np.min下面的评论是我正在寻找的解决方案,我不知道它的存在,因此我的答案得以解决.

Thanks to the comments below np.min is the solution I was looking for and I was not aware of it existing so my answer is solved.

推荐答案

但是,它仅沿单个轴求值,并沿单个行/列返回最小值的索引,而我希望对整个数组求值,而返回最小值而不是索引.

However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

numpy.argmin默认情况下不沿单轴求值,默认值沿平化矩阵求值,它返回平化数组中的线性索引;来自链接的numpy文档:

numpy.argmin does not by default evaluate along a single axis, the default is to evaluate along the flattened matrix and it returns the linear index in the flattened array; from the numpy docs that you linked:

默认情况下,索引位于平整的数组中,否则沿指定的轴.

By default, the index is into the flattened array, otherwise along the specified axis.

无论哪种方式,请使用 numpy.amin numpy.min返回最小值 ,或者等效地对于数组arrname使用

Either way, use numpy.amin or numpy.min to return the minimum value, or equivalently for an array arrname use arrname.min(). As you mentioned, numpy.argmin returns the index of the minimum value (of course, you can then use this index to return the minimum value by indexing your array with it). You could also flatten into a single dimension array with arrname.flatten() and pass that into the built-in min function.

以下四种方法可以产生所需的结果.

The four following methods produce what you want.

import numpy as np

values = np.array([
    [8,2,3,4,5,6],
    [3,6,6,7,2,6],
    [3,8,5,1,2,9],
    [6,4,2,7,8,3]])

values.min()          # = 1
np.min(values)        # = 1
np.amin(values)       # = 1
min(values.flatten()) # = 1

这篇关于二维数组python上的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆