温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Numpy: how do I get the smallest index for which a property is true
numpy python

python - numpy:如何获取属性为真的最小索引

发布于 2020-03-29 21:59:28

我有一个一维的numpy数组。我想获得一个属性正确的最大和最小索引。

例如,

A = np.array([0, 3, 2, 4, 3, 6, 1, 0])

并且我想知道的值A大于或等于的最小索引4

我可以

i = 0
while A[i] < 4:
    i += 1
print("smallest index", i)

i = -1
while A[i] <4:
    i -= 1
print("largest index", len(A)+i)

有更好的方法吗?


如此答案中所建议

np.argmax(A>=4)

返回3,这确实是最小的索引。但这并没有给我最大的索引。

查看更多

提问者
usernumber
被浏览
19
Josmoor98 2020-01-31 19:57

您可以尝试类似。根据评论,如果A是。

A = np.array([0, 3, 2, 4, 3, 6, 1, 4])

idx_values = np.where(A >= 4)[0]
min_idx, max_idx = idx_values[[0, -1]]

print(idx_values)
# array([3, 5, 7], dtype=int64)

idx_values返回满足您条件的所有索引值。然后,您可以访问最小和最大的索引位置。

print(min_idx, max_idx)
# (3, 7)