我要学习Python大约4个小时,所以这可能是一个非常愚蠢的问题。
我不太了解为什么测地线对于我提供的2个坐标之间的距离返回0.0。
import csv
from geopy.distance import geodesic
with open('sample_data.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
coordinate_set = 1
coordinates_1 = 0
coordinates_2 = 0
for row in csv_reader:
if line_count == 0:
line_count += 1
continue
else:
print("------------------------------------")
print(line_count)
if coordinate_set == 1:
# added cast to float as per recommendation from IftahP
coordinates_1 = (float(row['Lat']),float(row['Long']))
# coordinate_set_1 = (41.49008, -71.312796)
print("Set 1: ")
print(coordinate_set_1)
coordinate_set = 2
if coordinate_set == 2:
# added cast to float as per recommendation from IftahP
coordinates_2 = (float(row['Lat']),float(row['Long']))
#coordinate_set_2 = (41.499498, -81.695391)
print("Set 2: ")
print(coordinates_2)
## Distance between the 2 coordinates
print(coordinates_1,coordinates_2)
print(geodesic(coordinates_1,coordinates_2).miles)
coordinate_set = 1
line_count += 1
这是输出...
------------------------------------
1
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.458595, -80.20754)
(25.458595, -80.20754) (25.458595, -80.20754)
0.0
------------------------------------
2
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4586116, -80.207505)
(25.4586116, -80.207505) (25.4586116, -80.207505)
0.0
------------------------------------
3
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4586083, -80.2075033)
(25.4586083, -80.2075033) (25.4586083, -80.2075033)
0.0
------------------------------------
4
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4585966, -80.2075216)
(25.4585966, -80.2075216) (25.4585966, -80.2075216)
0.0
------------------------------------
5
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4585883, -80.20755)
(25.4585883, -80.20755) (25.4585883, -80.20755)
0.0
------------------------------------
6
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4585833, -80.2075316)
(25.4585833, -80.2075316) (25.4585833, -80.2075316)
0.0
------------------------------------
7
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4585833, -80.207495)
(25.4585833, -80.207495) (25.4585833, -80.207495)
0.0
------------------------------------
8
Set 1:
('26.0595233', '-80.1332766')
Set 2:
(25.4585783, -80.2074866)
(25.4585783, -80.2074866) (25.4585783, -80.2074866)
0.0
------------------------------------
我“硬编码” https://pypi.org/project/geopy/上提供的坐标,当我使用它们时,它会显示一个距离。它只是不喜欢我输入的坐标。没有显示错误信息。
答案 0 :(得分:1)
问题:coordinate_1
和coordinate_2
都是从同一个row
读取的(因此距离始终等于0)
解决方案是在coordinate_set
个周期内将开关if
的值从row
s中移出:
for row in csv_reader:
if coordinate_set == 1:
coordinates_1 = (float(row['Lat']),float(row['Long']))
# coordinate_set = 2 ## 1st source of error
if coordinate_set == 2:
coordinates_2 = (float(row['Lat']),float(row['Long'])) # the same row is readen twice
print(geodesic(coordinates_1,coordinates_2).miles)
# coordinate_set = 1 ## 2nd error
coordinate_set = 2 if (coordinate_set==1) else 1 # Correct switcher
line_count += 1