【问题标题】:Finding minimum in an array在数组中找到最小值
【发布时间】:2014-12-17 20:21:37
【问题描述】:

我想在 idx 2-7 之间找到最小的“y”数,但有些事情我做得不对。 目前它打印 x = 0.02 和 y = 101,我希望它打印出 x = 0.05 和 y = 104。 即使我将“idx = 3”更改为更高的数字,也没有任何变化。

我已经把它从最大值改成了最小值,因此有些人仍然说是最大值,但我认为只要“y[:idx].argmin()”是最小值,这并不重要?

import numpy as np
# idx:           0     1     2     3     4     5     6     7
x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
y = np.array([ 110,  101,  110,  106,  102,  104,  112,  115]) # load


idx = 3
cutoff = 0.08
while x[idx] < cutoff:
    idx = idx + 1

max_idx = y[:idx].argmin()
max_x = x[max_idx]
max_y = y[max_idx]
print (max_x)
print (max_y)

【问题讨论】:

    标签: arrays python-3.x numpy


    【解决方案1】:

    y[:idx] 是第一个 idx 值。你想要y[2:]

    另外,min_idx = y[2:].argmin() 为您提供相对于y[2:] 的最小索引。 所以关于y 的最小索引是2+min_idx


    import numpy as np
    # idx:           0     1     2     3     4     5     6     7
    x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
    y = np.array([ 110,  101,  110,  106,  102,  104,  112,  115]) # load
    
    min_idx = y[2:].argmin()
    min_x = x[2+min_idx]
    min_y = y[2+min_idx]
    print (min_x)
    # 0.05
    
    print (min_y)
    # 102
    

    如果您希望将注意力限制在 x >= 0.03 和 x x 和 y 限制为这些值:

    import numpy as np
    # idx:           0     1     2     3     4     5     6     7
    x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
    y = np.array([ 110,  101,  110,  106,  102,  104,  112,  115]) # load
    
    lower, upper = 0.03, 0.07
    mask = (x >= lower) & (x < 0.07)
    # array([False, False,  True,  True,  True,  True, False, False], dtype=bool)
    
    # select those values of x and y
    masked_y = y[mask]
    masked_x = x[mask]
    
    # find the min index with respect to masked_y
    min_idx = masked_y.argmin()
    
    # find the values of x and y restricted to the mask, having the min y value
    min_x = masked_x[min_idx]
    min_y = masked_y[min_idx]
    
    print (min_x)
    # 0.05
    
    print (min_y)
    # 102
    

    【讨论】:

    • 嘿,但是有没有办法根据 x 值设置“限制”,包括下限和上限。喜欢从 0.03 到 0.07 吗?
    猜你喜欢
    • 2013-03-30
    • 2018-07-04
    • 2011-03-30
    • 1970-01-01
    • 2013-04-08
    • 2021-02-10
    • 2021-03-15
    • 2018-03-14
    相关资源
    最近更新 更多