I have the following array which consists of 10 values:
values = [5,4,15,2,7,1,0,25,9,6]
And I want to find the maximum value as index and subtract the next index from it, so the output should be the range between the two indices, I tried to do the below code:
start= 0
step=2
length=10
while start <= length:
max_val = np.max(values)
idx = np.where(values == max_val)
print('max', max_val)
print('max index', np.where(values == max_val))
idx_all= values[i]
print(max_val)
range1= values[idx[0]] - values[idx[0] 1];
print('range', range1)
start=start step
The maximum value and its index are correct, However, I get the following output error at finding the difference between the two indices:
max 25
max index (array([7], dtype=int64),)
25
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-49-de731383e093> in <module>
15
16 print(max_val)
---> 17 range1= values[idx[0]] - values[idx[0] 1];
18 print('range', range1)
19
TypeError: only integer scalar arrays can be converted to a scalar index
I was wondering how can I edit this to make the output know the next index and subtract it? Thank you.
CodePudding user response:
I think that this code should accomplish what you're looking for:
values = [5,4,15,2,7,1,0,25,9,6]
max_val = np.max(values)
idx = list(np.where(values == max_val)[0])[0]
max_val = values[idx]
value = max_val - values[idx 1]
print(value)
This will output 16 for this example.
CodePudding user response:
This outputs 16, which is true because 9 is next to 25
values = [5,4,15,2,7,1,0,25,9,6]
# get the maximum value first
mm = max(values)
index = 0
next_index = 0
# iterate through the array while checking for the max index
for i in range(0, len(values)):
if(values[i]==mm):# this is the index of the maximum element
index = i
next_index = i 1 # break out of the loop
break
# get the element at next index
el = values[next_index]
# get the difference with the maximum
diff = mm - el
print(diff)