Home > Blockchain >  using Numpy argmax to count vs for loop
using Numpy argmax to count vs for loop

Time:11-27

I currently use something like the similar bit of code to determine comparison

list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10
counter = 1

for number in list_of_numbers:
    if (high >= number) \
    and (counter < lookback):
        counter  = 1
    else:
        break

this will give you the output 7 and functions as you expect it to. however is very taxing on large data arrays. So I looked for a solution and came up with np.argmax() but there seems to be an issue. For example the following:

list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
np_list = np.array(list_of_numbers)
high = 29980.0

print(np.argmax(np_list > high)   1)

this will output 1, just like armax is suppose to .. but I want it to output 7. Is there another method to do this that will give me similar output to the if statement ?

CodePudding user response:

You have you less than sign backwards, no? The following should word the same as your for-loop:

print(np.min([np.sum(np_list < high) 1, lookback]))

CodePudding user response:

You can get a boolean array for where high >= number using NumPy:

list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10

boolean_arr = np.less_equal(np.array(list_of_numbers), high)

Then finding where is the first False argument in that to satisfy break condition in your code. Furthermore, to consider countering, you can use np.cumsum on the boolean array and find the first argument that satisfying specified lookback magnitude. So, the result will be the smaller value between break_arr and lookback_lim:

break_arr = np.where(boolean_arr == False)[0][0]   1
lookback_lim = np.where(np.cumsum(boolean_arr) == lookback)[0][0]   1
result = min(break_arr, lookback_lim)

If your list_of_numbers have not any bigger value than your specified high limit for break_arr or the specified lookback exceeds values in np.cumsum(boolean_arr) for lookback_lim, the aforementioned code will get stuck with an error like the following, relating to np.where:

IndexError: index 0 is out of bounds for axis 0 with size 0

Which can be handled by try-except or if statements e.g.:

try:
    break_arr = np.where(boolean_arr == False)[0][0]   1
except:
    break_arr = len(boolean_arr)   1

try:
    lookback_lim = np.where(np.cumsum(boolean_arr) == lookback)[0][0]   1
except:
    lookback_lim = len(boolean_arr)   1
  • Related