Warm tip: This article is reproduced from stackoverflow.com, please click
numpy python

Numpy: how do I get the smallest index for which a property is true

发布于 2020-03-29 21:02:56

I have a numpy array that is one dimensional. I would like to get the biggest and the smallest index for which a property is true.

For instance,

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

and I would like to know the smallest index for which the value of A is larger or equal to 4.

I can do

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)

Is there a better way of doing this?


As suggested in this answer,

np.argmax(A>=4)

returns 3, which is indeed the smallest index. But this doesn't give me the largest index.

Questioner
usernumber
Viewed
19
Josmoor98 2020-01-31 19:57

You can try something like. As per the comments, if A is.

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 returns all the index values meeting your condition. You can then access the smallest and largest index positions.

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