1

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.

usernumber
  • 1,958
  • 1
  • 21
  • 58
  • Do you need the biggest and smallest occurrences? – Josmoor98 Jan 31 '20 at 11:01
  • Sorry, I meant index not occurrence. So the answer linked doesn't answer your question? – Josmoor98 Jan 31 '20 at 11:12
  • From the link, I'm still missing how to get the largest index. – usernumber Jan 31 '20 at 11:25
  • 1
    To get the maximum value, you can use `np.argmax(A == A[A >= 4].max())`. This however, will only return the first index with this value. So it will ignore duplicate values of the max value. This returns `5`. Tried to answer, but the ability has been removed, since it's marked as a duplicate – Josmoor98 Jan 31 '20 at 11:32
  • @Josmoor98 If the last element of `A` is `4` rather than `1`, np.argmax(A == A[A >= 4].max()) returns `5` instead of `7`. This doesn't work – usernumber Jan 31 '20 at 11:36
  • 1
    I see what you mean now. You can use `np.where(A>=4)` to return all index values meeting your condition. Then just select the first and last occurrence to get the min/max values. So `np.where(A>=4)` returns `array([3, 5, 7])`, then you can just slice the first and last values, or use `.min()` and `.max()` – Josmoor98 Jan 31 '20 at 11:44

1 Answers1

2

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)
Josmoor98
  • 1,721
  • 10
  • 27