我有一个csv文件" f1.csv" (没有标题):
Index,Lattitude,Longitude
1,52.2296756,21.0122287
2,52.406374,16.9251681
3,52.346374,19.9251681
4,52.406374,16.9251681
我想计算每个索引的距离,并在另一个csv文件中附加sortest距离索引。我想要这样的输出:
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
这里是我试过的python代码,它只计算一行的距离。
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)
输出是:
0.0
278.545589351
75.0915410407
278.545589351
[0.0, 75.0915410407001, 278.54558935106695, 278.54558935106695]