0

I have a csv file "f1.csv" (without header):

Index,Lattitude,Longitude
    1,52.2296756,21.0122287
    2,52.406374,16.9251681
    3,52.346374,19.9251681
    4,52.406374,16.9251681

I want to calculate distance for every index and append the sortest distance index in the other csv file. I want output like this:

Index,Lattitude,Longitude,ShortestIndex
    1,52.2296756,21.0122287,2
    2,52.406374,16.9251681,4
    3,52.346374,19.9251681,3
    4,52.406374,16.9251681,4

Here, is the python code that i tried, it is calculating distance only for one row.

from math import sin, cos, sqrt, atan2, radians
import csv

R = 6373.0

distance=[]
with open('f1.csv', 'r') as inf:
  for l in inf:
            #for j in inf:
                e = l[:-1].split(',')
                lat2= radians(float(e[1]))
                lon2= radians(float(e[2]))
                lat1 = radians(float(52.2296756))
                lon1 = radians(float(21.0122287))
                dlon = lon2 - lon1
                dlat = lat2 - lat1
                a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
                c = 2 * atan2(sqrt(a), sqrt(1 - a))
                dist = R * c
                distance.append(dist)
                print (dist)
distance.sort()
print (distance)

Output of this is:

 0.0
278.545589351
75.0915410407
278.545589351
[0.0, 75.0915410407001, 278.54558935106695, 278.54558935106695]

0 Answers0