'Distance Between Two DFs With A Few Variables

I'd like some help with a kind of complex situation. I'll try to be very objective and thanks in advance:

I have two dataframes. 1) df has a list of a few thousand coordinates of services done on the field, 2) dfbase has a few coordinates, for physical bases where each person starts their services from.

I need to calculate the distance between each base in dfbase to the respective coordinate in df.

The thing is, they must be in the same area code (common column ROTA) which consists into breaking an ZCGUNLEIT to a substring, 3, 3.

dfbase

df

However, not every ROTA has a physical base. For example, ROTA 071 has no base, but 072 has. So if a ROTA doesn't have a base, the distance should be calculated for this coordinate to the next ROTA, in this case 072.

I'm using GEOPY to do that, but could not understand how to write. My last try was to merge both dataframes into df2 so that every coordinate in df has a either a 0.0 matching (for cases which that route doesn't have a coordinate) or a respective base with coordinates, as below:

enter image description here

This was my last try, which resulted in the error: single positional indexer is out-of-bounds:

dist=[0]
for i in range(1,len(df2)):
    if df2.ROTA.iloc[i]==df.ROTA.iloc[i]:
      dist.append(geopy.distance.geodesic((df2.LATITUDE.iloc[i],df2.LONGITUDE.iloc[i]),(df2.Latitude.iloc[i],df2.Longitude.iloc[i])).km)
    elif df2.ROTA.iloc[i] == df2.ROTA.iloc[i+1]:
      dist.append(geopy.distance.geodesic((df2.LATITUDE.iloc[i],df2.LONGITUDE.iloc[i]),(df2.Latitude.iloc[i],df2.Longitude.iloc[i])).km)
    else: dist.append(0)

df2['DIST']=dist


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source