在long vector,python中获得最小值索引的有效方法 [英] Efficient way to get index of minimum value in long vector, python
问题描述
我有一长串的经度值(len(Lon)= 420481)和另一个纬度值。我想找到经度最小值的相应纬度。
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.
我试过:
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!
推荐答案
我可以推荐numpy吗?
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]
这比min(izip())解决方案快(使用420481随机创建的记录时使用我的设置约20倍),当然你会需要将您的数据值存储在numpy中以利用此加速。
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.
这篇关于在long vector,python中获得最小值索引的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!