在数组中找到最小值

时间:2014-12-17 20:21:37

标签: arrays python-3.x numpy

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

我已经将它从max更改为min,因此有些人仍然说max,但我不认为只要" Y [:IDX] .argmin()"是min?

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)

1 个答案:

答案 0 :(得分:3)

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