Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to get index of minimum value in long vector, python

I have a long list of longitude values (len(Lon) = 420481), and another one of latitude values. I want to find the corresponding latitude to the minimum of the longitude.

I tried:

SE_Lat = [Lat[x] for x,y in enumerate(Lon) if y == min(Lon)]

but this takes ages to finish.

Does anyone know a more efficient way?

Maybe you also have a suggestions for this: I now try to find the closest corresponding latitude to a new longitude, which is not in the original longitude vector. I tried this:

minDiff = [min(abs(x - lon_new) for x in lons)] # not very quick, but works
[(lat,lon) for lat,lon in izip(lats,lons) if abs(lon-lon_new)==minDiff]

The last line throws an error, because there are multiple matches. I don't know at the moment how to find only one value, lets say the first. Any help is greatly appreciated!

like image 878
Ronja Avatar asked May 18 '11 12:05

Ronja


2 Answers

May I recommend numpy?

import numpy
nplats = numpy.array(lats)
nplons = numpy.array(lons)

# this part is 20x faster than using the built-in python functions
index = numpy.argmin(nplats)

print nplats[index], nplons[index]

this is way faster than the min(izip()) solution (~20x using my setup when using 420481 randomly created records), although of course you'd need to store your data values in numpy to take advantage of this speed-up.

like image 160
Noah Avatar answered Oct 09 '22 17:10

Noah


min(itertools.izip(Lat, Lon), key=operator.itemgetter(1))[0]
like image 30
Ignacio Vazquez-Abrams Avatar answered Oct 09 '22 18:10

Ignacio Vazquez-Abrams