Rein K. - 3 years ago 71
Python Question

# Getting the indices of n highest items before a tage value

I have a list of temperatures, and I need to find n values before and after the desired temperature, preferably in separate lists.The values in my list are not necessarily unique, but I need the index of the original list. I need these indices to find other parameters in other lists.

Example:

``````TestArray = np.array([12,42,19,32,41,14,17,23,12,18,32,19])
Value = 20
n = 2
TestArray = np.append(TestArray, Value)
Sort = np.argsort(TestArray)
Index = np.where(Sort == (len(TestArray)-1))[0][0]
Lower = Sort[Index-n:Index]
Upper = Sort[Index+1:Index+n+1]
print(Upper, TestArray[Upper])
print(Lower, TestArray[Lower])
``````

My code gives the wanted output, but it looks really messy and I was wondering if there was a better way.

Explanation:
I append the wanted value to the end, so I know its index. Then I use argsort find the indices from low to high, and then use np.where to locate where my wanted value is. Then use indexing to find upper and lower values.

You can filter the array and then use `np.partition`:

``````mask = TestArray < Value

Lower
#array([19, 19])

Upper
#array([23, 32])
``````

To get the indices back:

``````TestArray = np.array([12,42,19,32,41,14,17,23,12,18,32,19])    ​
​