Python – How to Measure Distance Between Points Using Shapely and Fiona

fionapythonshapely

I am trying to determine a rough distance between points in my shapefile.

The shapefile I am working with has 28 million points in the structure x y z.
I am hoping to find the most common distance between each pair of points in metres.

I have come across this post How to measure distance using shapely which uses the code structure

import fiona
import shapely.geometry

# capital is a shapely geometry object

with fiona.open(path_to_data) as src:
    for feature in src:
        geom = shapely.geometry.shape(feature["geometry"])
        distance_between_pts = capital.distance(geom)
        print(distance_between_pts)

Whilst this example is comparing the distance between cities and capitals (2 different things), I'm wondering is there a way I can use fiona and shapely to give me the distance between points within 1 shapefile?

Yes I know 28 million calculations is a large magnitude. But if I could even limit the calculations to a much smaller number of points and just take a rough distance as my calculation

Best Answer

You can do it with itertools.combinations(). In your case:

import fiona
import shapely.geometry
import itertools

with fiona.open(path_to_data) as src:
    for feat_1, feat_2 in itertools.combinations(src, 2):
        geom_1 = shapely.geometry.shape(feat_1["geometry"])
        geom_2 = shapely.geometry.shape(feat_2["geometry"])
        distance_between_pts = geom_1.distance(geom_2)
        print(distance_between_pts)

What itertools.combinations(src, 2) does is that, given some iterator (in this case src), it returns all combinations of the features in the iterator that have length 2.