0
votes

I am trying to calculate the Latitude and Longitude for a number (series) of flights in which I tried to use this code

import pandas as pd
from math import radians, cos, sin, asin, sqrt
# convert decimal degrees to radians 
lon1 = df1['from_lon'].map(radians)
lat1 = df1['from_lat'].map(radians)
lon2 = df1['dest_lon'].map(radians)
lat2 = df1['dest_lat'].map(radians)
# haversine formula 
dlon = lon2 - lon1 
dlat = lat2 - lat1 
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
results = 3959.0 * c

but I keep getting this error

TypeError: cannot convert the series to <class 'float'>

I have seen many people asking about this error on stackoverflow and tried the answers provided to them. What I have tried is to use the equation in this way

a = dlat.divide(2).apply(sin).pow(2) + cos(lat1) * lat2.apply(cos).multiply(dlon.divide(2).apply(sin).pow(2))

I also tried to use lambda as well as tried to convert each variable to float using .astype(float) but unfortunately nothing worked with me.

The data type for lon1, lat1, lon2 and lat2 is float64.a sample of the data:

lon1
-1.826892
-1.287685
-1.534229
-1.534229
-1.826892
1.775173
-0.062252
1
show some of your data and dtypes. - Mark
@mark I have added what you asked for in the post. Thank you very much - s_am
Can you try this code and see the output if this is what you want. (no error for me but not sure if the output is correct or not) a = (dlat/2).apply(lambda x : sin(x)) ** 2 + lat1.apply(lambda x : cos(x)) * lat2.apply(lambda x:cos(x))* (dlon/2).apply(lambda x : sin(x)) ** 2 c = 2 * a.apply(lambda x : asin(sqrt(x))) results = 3959.0 * c - vb_rises
@Vishal yes that did the job perfectly thank you very much - s_am

1 Answers

0
votes

Below is the code which works without error. Basically you need to use Series.apply(lambda x: ) function.

a = (dlat/2).apply(lambda x : sin(x)) ** 2 + lat1.apply(lambda x : cos(x)) * lat2.apply(lambda x:cos(x))* (dlon/2).apply(lambda x : sin(x)) ** 2 
c = 2 * a.apply(lambda x : asin(sqrt(x))) 
results = 3959.0 * c