4

I have 2 GeoDataFrames 100 records each, and want to calculate distances between respective geometries (Points, of course).

I can't see how to make it other than write a cycle to iterate rows directly. (It seems that something changed since summer, when GeoPandas 0.4 was realeased.)

Here are the ways I used to do it:

Option 1: I assign another column. Now it sometimes turns all Points into nan.

main_df['geometry_other'] = other_df['geometry']
main_df['dist'] = main_df.apply(lambda r: r['geometry'].distance(r['geometry_other']), axis=1)
main_df.drop('geometry_other', axis=1, inplace=True)

Option 2: I join the 2 geodataframes and do the same. Same way, it turns 'geometry_other' into nans.

main_df = main_df.join(other_df, rsuffix='_other')
# then same as before

Option 3: Here's what I came up with now, after posting the question. I still don't like the repetitive .tolist() on both sides.

main_df['match_distance'] = [a.distance(b)
    for a, b in
       zip(main_df['geometry'].tolist(),
           other_df['geometry'].tolist())]

What are the options now to do this?

6

If the two GeoDataFrames are "aligned" (same length with same index), you can actually directly use the distance method: this accepts another GeoSeries or GeoDataFrame, and then the distance will be calculated elementwise between both series.

With:

import geopandas
from shapely.geometry import Point

main_df = geopandas.GeoDataFrame({'a' : [1, 2], 'geometry': [Point(0, 0), Point(1, 1)]})
other_df = geopandas.GeoDataFrame({'b' : [.1, .2], 'geometry': [Point(1, 0), Point(3, 1)]})

gives:

In [90]: main_df
Out[90]: 
   a     geometry
0  1  POINT (0 0)
1  2  POINT (1 1)

In [91]: other_df
Out[91]: 
     b     geometry
0  0.1  POINT (1 0)
1  0.2  POINT (3 1)

In [92]: main_df.distance(other_df)
Out[92]: 
0    1.0
1    2.0
dtype: float64

(and main_df.geometry.distance(other_df.geometry) does the same)

Note that the apply version you show (option 1) should also work, but is thus not needed / more verbose than the solution above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.