Search code examples
pythonpandastimedeltagreat-circle

How to convert great_circle distance to timedelta in Python?


I have used great_circle function to find the distance between two coordinates.For example, if i have the following data:

lat1= ['-77.85']
lon1= ['80.23']
lat2= [-22.4532']
lon2= ['62.45']

And to find the distance i use the following code:

import pandas as pd
from geopy.distance import great_circle
from datetime import datetime,timedelta as dt
distance = df.apply(lambda x: great_circle((x['lat1'], x['lon1']),(x['lat2'], x['lon2'])), axis = 1)  # gives distance in km

And to find the time from the distance, as we know Time = Distance/Speed. I assume speed to be 80km/hr and I use:

time= distance/80  

The obtained 'time' has the unit 'km' . I want to convert this function to time.

df['time'] = pd.to_timedelta(time,unit='h')   

I obtain the following error:

Error : ValueError: Invalid type for timedelta scalar: class 'geopy.distance.great_circle'

Could you tell me how to obtain 'time' as time function and not as distance 'km'?


Solution

  • Consider using .km attribute.

    Demo:

    In [33]: df
    Out[33]:
        lat1   lon1     lat2   lon2
    0 -77.85  80.23 -22.4532  62.45
    
    In [34]: distance = x.apply(lambda x: great_circle((x['lat1'], x['lon1']),
                                                       (x['lat2'], x['lon2'])).km,
                                                       axis = 1)
    #  ---->                                                                  ^^^
    
    In [35]: distance
    Out[35]:
    0    6233.235674
    dtype: float64
    
    In [36]: df['time'] = pd.to_timedelta(distance/80,unit='h')
    
    In [37]: df
    Out[37]:
        lat1   lon1     lat2   lon2                   time
    0 -77.85  80.23 -22.4532  62.45 3 days 05:54:55.605600