# Optimize computation distance of million points to lines in Python

I have found questions here of how to compute the distance of a point to a line (manually, with distance method of some libraries...) but my problem is that I need to compute the distance of 4M points to 9K lines, and keep points that are closer than a specific distance. I'm doing it with Python 3.5

``````    for i in range(len(multip)): #Shapely Multipoint object
while j < len(network): # .shp file opened GeoDataFrame object from geopandas
dist = network[j].distance(multip[i])
print('dist', dist)
if (dist <= critdist):
count += 1
xxx = (multip[i].x)
yyy = (multip[i].y)
distlist = np.append(distlist, dist)
critcoordx = np.append(critcoordx, xxx)
critcoordy = np.append(critcoordx, yyy)
j = 0
break
j += 1
j = 0
``````

I couldn't come up with a solution to vectorize this process.

I also tried things like:

``````network.distance(multip)
``````

But it does not compute individual distances.

• Do you need the exact distances or just the criterium "closer than X"? If so you could create a buffer around the lines and just keep the points intersecting with that buffer. – Kersten Jan 15 '18 at 9:29
• Just closer than. I tried the "GIS aproach" with QGIS at the beginning, but I was facing problems of "Invalid geometry" which I couldn't fix even with validity checker and v.clean. But maybe you know another approach to do the buffering and intersection. – ImanolUr Jan 15 '18 at 12:44
• Maybe you still need a solution I suggest you to use the spatial indexes of rtree. They could speed up a lot your script – Oscar Campo Apr 24 '18 at 13:35