I have a .csv file with 3 columns. The first column is titled Distance and it is empty. The second and third columns are titled Longitude and Latitude which contain coordinates, for example:
I have wrote a script that computes the distance between the two points using the haversine formula (see below), but I have to manually enter the coordinates, which is not desirable:
import math lat1 = 40.31117 long1 = -77.60483 lat2 = 40.3045 long2 = -77.58167 def distance_on_unit_sphere(lat1, long1, lat2, long2): # Converts lat & long to spherical coordinates in radians. degrees_to_radians = math.pi/180.0 # phi = 90 - latitude phi1 = (90.0 - lat1)*degrees_to_radians phi2 = (90.0 - lat2)*degrees_to_radians # theta = longitude theta1 = long1*degrees_to_radians theta2 = long2*degrees_to_radians # Compute the spherical distance from spherical coordinates. # For two locations in spherical coordinates: # (1, theta, phi) and (1, theta', phi')cosine( arc length ) = # sin phi sin phi' cos(theta-theta') + cos phi cos phi' distance = rho * arc length cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2)) arc = math.acos(cos)*6371 #radius of the earth in km return arc print distance_on_unit_sphere(lat1,long1,lat2,long2)
My goal is to populate the empty distance column using Python by computing the distance between the 1st location (-77.60483,40.31117) and the 2nd location (-77.58167,40.3045) and then print that value into the Distance column and then compute the distance between the 2nd (-77.58167,40.3045) and 3rd point (-77.52883,40.24917) and then print that value below the previously computed value in Distance column and so on for the subsequent coordinates. I need some help or an example provided to input the .csv file, run the haversine formula, and then write the result into the appropriate location in an output .csv.