查找numpy数组中的最小值以及该数组其余行中的相应值

时间:2022-08-22 13:03:55

Consider the following NumPy array:

考虑下面的NumPy数组:

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]])

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.

我想做的就是找到第二列的最小值(在本例中是1),然后报告的其他值(在本例中2)。我试着使用argmin之类,但被绊倒的1在第一列中。

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:

有什么方法可以轻松做到这一点吗?我也考虑过对数组进行排序,但我似乎无法让它们协同工作。数据是由如下循环生成的,所以如果有一种更简单的方法,不是numpy数组,我也会把它作为一个答案:

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)

2 个解决方案

#1


20  

How about

如何

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

Break-down

崩溃

a. Grab the second column

a.抓住第二列

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

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

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

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

c. Index a with that to get the corresponding row

用它索引a,得到相应的行

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

d. And take the first element

d,取第一个元素

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

#2


5  

Using np.argmin is probably the best way to tackle this. To do it in pure python, you could use:

使用np。argmin可能是解决这个问题的最好方法。要在纯python中进行,您可以使用:

min(tuple(r[::-1]) for r in a)[::-1]

a中r的最小(元组(r[::-1]) [: -1]

#1


20  

How about

如何

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

Break-down

崩溃

a. Grab the second column

a.抓住第二列

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

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

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

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

c. Index a with that to get the corresponding row

用它索引a,得到相应的行

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

d. And take the first element

d,取第一个元素

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

#2


5  

Using np.argmin is probably the best way to tackle this. To do it in pure python, you could use:

使用np。argmin可能是解决这个问题的最好方法。要在纯python中进行,您可以使用:

min(tuple(r[::-1]) for r in a)[::-1]

a中r的最小(元组(r[::-1]) [: -1]