在numpy数组中查找最小值以及该数组其余行的对应值 [英] Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row

查看:100
本文介绍了在numpy数组中查找最小值以及该数组其余行的对应值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下NumPy数组:

Consider the following NumPy array:

a = np.array([[1,4], [2,1],(3,10),(4,8)])

这将提供一个类似于以下内容的数组:

This gives an array that looks like the following:

array([[ 1,  4],
       [ 2,  1],
       [ 3, 10],
       [ 4,  8]])

我想做的是找到第二列的最小值(在这种情况下为1),然后报告该对的另一值(在这种情况下为2).我试过使用argmin之类的东西,但是第一列中的数字为1.

What I'm trying to do is find the minimum value of the second column (which in this case is 1), and then report the other value of that pair (in this case 2). I've tried using something like argmin, but that gets tripped up by the 1 in the first column.

有没有一种方法可以轻松地做到这一点?我也考虑过对数组进行排序,但是似乎无法使数组保持配对.数据是由如下所示的循环生成的,因此,如果有一种更简单的方法来实现不是 numpy数组,我也将其作为答案:

Is there a way to do this easily? I've also considered sorting the array, but I can't seem to get that to work in a way that keeps the pairs together. The data is being generated by a loop like the following, so if there's a easier way to do this that isn't a numpy array, I'd take that as an answer too:

results = np.zeros((100,2))

# Loop over search range, change kappa each time
for i in range(100):
    results[i,0] = function1(x)
    results[i,1] = function2(y)

推荐答案

如何

a[np.argmin(a[:, 1]), 0]

崩溃

a.抓住第二列

>>> a[:, 1]
array([ 4,  1, 10,  8])

b.获取第二列中最小元素的索引

b. Get the index of the minimum element in the second column

>>> np.argmin(a[:, 1])
1

c.索引a并获得相应的行

c. Index a with that to get the corresponding row

>>> a[np.argmin(a[:, 1])]
array([2, 1])

d.并选择第一个元素

d. And take the first element

>>> a[np.argmin(a[:, 1]), 0]
2

这篇关于在numpy数组中查找最小值以及该数组其余行的对应值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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