I am looking any package or module to find index more fast than my coding.
If there is an numpy array, like
a = numpy.array([1,2,3,4,5,6])
So these are a[0]=1, a[1]=2, a[2]=3, a[3]=4, a[4]=5, a[5]=6. In this situation, I'd like to find two index (just before and just after) around 3.5 So, this solution are a[2] and a[3], right?
Well, I took this way
for i in range(len(a) - 1):
difference1 = 3.5 - a[i]
difference2 = 3.5 - a[i + 1]
if difference1 * difference2 < 0:
print(i)
So I can find a[2]. and i can know a[3] is a little bigger than 3.5 which of all the things i have. but this is just an example. I deal with more huge data, So there need a lot of time. Is there any tool (module or package) to find more faster in python?
Here's one solution using numpy. I'm assuming that your array is sorted from your example.
I mocked up this version, and over a 10M element array the method performed about 10x faster than the original. I've also not tried to merge together each numpy activity (you could do this in one long line if you want) for clarity.
Specific answer to your example:
a = numpy.array([1,2,3,4,5,6])
print numpy.where(numpy.sort(numpy.concatenate((a,[3.5])))==3.5)[0][0] - 1
Longer example for more explanation:
import time
import numpy
a = numpy.array([1,2,3,4,5,6])
f = 3.5
#Replacing with a larger range of values to search for timing test
a = numpy.arange(10000000)
f = 500000.5
print "starting new version"
start = time.time()
b = numpy.concatenate((a,[f]))
c = numpy.sort(b)
d = numpy.where(c==f)[0][0] - 1
print d
end = time.time()
print end-start
print "do it in one unreadable line"
start = time.time()
print numpy.where(numpy.sort(numpy.concatenate((a,[f])))==f)[0][0] - 1
end = time.time()
print end-start
print "starting original version"
start = time.time()
for i in range(len(a) - 1):
difference1 = f - a[i]
difference2 = f - a[i + 1]
if difference1 * difference2 < 0:
print i
end = time.time()
print end-start
EDIT: Put the longer example second so it doesn't look like my suggested solution is 30 lines long!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments