Rein K. 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.


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.

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.

Answer Source

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

mask = TestArray < Value
Lower, Upper = -np.partition(-TestArray[mask], 2)[:2], np.partition(TestArray[~mask], 2)[:2]

#array([19, 19])

#array([23, 32])

To get the indices back:

TestArray = np.array([12,42,19,32,41,14,17,23,12,18,32,19])    ​
mask = TestArray < Value
arrInd = np.column_stack((np.arange(len(TestArray)), TestArray))
Lower, Upper = arrInd[mask,:], arrInd[~mask,:]
LowerInd, UpperInd = np.argpartition(-Lower[:, 1], 2)[:2], np.argpartition(Upper[:,1], 2)[:2]
​#[[ 2 19]
# [11 19]]

#[[ 7 23]
# [ 3 32]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download