1

I have df1 and df2. Each dataframe contains an ID column. Each dataframe also contains a geometry column. I would like to calculate the distance between each dataframe's geometry column only for rows where ID's match in each dataframe.

I would imagine it looks something like this but can't figure it out:

for geom in df1.geometry:
    if df1['system_id'] == df2f['systemID']:    
        df1['distance'] = [geom.distance(df2.geometry[0].boundary) for geom in df1.geometry]

1 Answer 1

0

Merge the two dataframes into a temporary dataframe, calculate the distances and merge the result back to the original data frame:

#Merge the two dataframes where ids match into a new dataframe
distances = df1.merge(right=df2, how="inner",left_on="system_id", right_on="systemID")

#Calculate distances
distances["distance"] = distances.apply(lambda row: row["geometry_x"].distance(row["geometry_y"].boundary), axis=1)

#Merge distance column to the original dataframe. Distance will be NaN for rows with no id match
df1 = df1.merge(right=distances[["system_id","distance"]], how="left", on="system_id")
1
  • 1
    Thank you @Bera that worked perfectly. I guess I needed to think of this objective in several steps instead of one single loop.
    – user216077
    Commented Dec 5, 2022 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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