简体   繁体   English

如何找到 numpy 数组的第一个最小数量,然后在不对数组进行排序的情况下找到第二个最小数量?

[英]How can I find the first minimum number of numpy array, then the second minimum number without sorting the array?

Here is the code:这是代码:

import numpy as np
array = np.array([15, 55, 9, 99, 8, 21, 2, 90, 88])

this will output an array([ 15, 55, 9, 99, 8, 21, 2, 90, 88]) .这将 output 一个array([ 15, 55, 9, 99, 8, 21, 2, 90, 88])

How can I find the first minimum number without sorting then the second minimum number?如何在不排序的情况下找到第一个最小数字,然后是第二个最小数字?

I expect the output to be: first min = 9 second min = 8我希望 output 是:第一分钟 = 9第二分钟 = 8

You can find the absolute minimum like this:您可以像这样找到绝对最小值:

In [35]: import numpy as np

In [36]: arr = np.array([15, 55, 9, 99, 8, 21, 2, 90, 88])

In [37]: first = np.min(arr)

In [38]: second = np.min(arr[arr != first])

In [39]: first
Out[39]: 2

In [40]: second
Out[40]: 8

To obtain the indices of the local minima, you could use scipy.signal.argrelmin :要获得局部最小值的索引,您可以使用scipy.signal.argrelmin

In [52]: from scipy.signal import argrelmin

In [53]: idx = argrelmin(arr)[0]

In [54]: idx
Out[54]: array([2, 4, 6], dtype=int64)

In [55]: arr[idx]
Out[55]: array([9, 8, 2])

You could offset the list and zip them:您可以抵消列表和 zip 它们:

l0 = [15, 55, 9, 99, 8, 21, 2, 90, 88]
l1 = l0[1:]
l2 = [-1] + l0

[x for x,y,z in zip(l0,l1,l2) if (x < y) & (x < z)]
# Out[32]: [9, 8, 2]

or in one line:或在一行中:

l = [15, 55, 9, 99, 8, 21, 2, 90, 88]
[x for x,y,z in zip(l,l[1:],[-1]+l) if (x < y) & (x < z)]
# Out[32]: [9, 8, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM