3

I am given an array containing both positive and negative numbers.

import numpy as np
arr = np.array([-10.2, -5.3, -2.1, 0, 1.2, 3.4])

I would like to find the index corresponding to the maximum negative number and to a minimum positive number. In the above, my expected outcome is 2 and 4. Is there any numpy trick to achieve this? I have found a solution in this link, but I would like to know how this could be done through numpy functions: Finding index of largest negative and smallest positive element in array

kmario23
  • 57,311
  • 13
  • 161
  • 150
matttree
  • 125
  • 1
  • 1
  • 11

3 Answers3

18

Replace non negative values with -inf, then use argmax to find the largest negative:

np.where(arr < 0, arr, -np.inf).argmax()
# 2

Similarly replace non positive values with inf then use argmin to find the smallest positive:

np.where(arr > 0, arr, np.inf).argmin()
# 4
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 2
    Or replace with `nan` and use `nanargmax` and `nanargmin`. But that's not much different than using `inf`. – Warren Weckesser Apr 20 '19 at 04:07
  • @Psidom Is using Numpy functions as in your answer faster or doing it with lists as mentioned in the answer tagged in the question faster? – Lost Jun 15 '22 at 09:49
1

If your array is always sorted (as in the provided example), then:

# input
Out[66]: array([-10.2,  -5.3,  -2.1,   0. ,   1.2,   3.4])

# obtain a `signed` boolean mask 
In [75]: sign_mask = np.sign(arr)

# compute derivative and obtain index for max_negative element
In [76]: max_neg_idx = np.where(np.diff(sign_mask, append=1) == 1)[0][0]

# add +2 to that to get index for min_positive element
In [77]: min_pos_idx = max_neg_idx + 2
kmario23
  • 57,311
  • 13
  • 161
  • 150
0

I was facing a similar type of problem and this was my approach:

arr=np.array([-10.2, -5.3, -2.1, 0, 1.2, 3.4])

#Filtering for all the negative values and getting the min of them
print('Threshold for Min val',np.where(arr==[max(arr[arr<0])]))

#Filtering for all the positive values and getting the max of them
print('Threshold for Max val',np.where(val==[min(arr[arr>0])]))
Raghul Raj
  • 1,428
  • 9
  • 24