我在excel中有以下数据,我需要使用python计算距离。
i / p:
Source lat1 lon1 Destination lat2 lon2
A1 41.66 -2.21 B1 40.62 -2.16
A2 43.92 -4.76 B2 63.99 -7.17
A3 40.56 -1.17 B3 47.03 -5.11
A4 45.20 -6.77 B4 41.64 -6.18
A5 54.66 -3.07 B5 48.34 -4.41
A6 49.92 -1.14 B6 34.63 0.33
A7 50.05 -4.29 B7 45.49 -0.68
A8 51.69 -3.90 B8 56.13 -1.14
A9 53.05 -2.76 B9 27.89 -5.63
A10 60.06 0.36 B10 36.03 -2.16
A11 30.55 -1.57 B11 28.56 -3.81
所需的o / p:
Source lat1 lon1 Destination lat2 lon2 Distance
A1 41.66 -2.21 B1 40.62 -2.16 115.6404811
A2 43.92 -4.76 B2 63.99 -7.17 2235.355382
A3 40.56 -1.17 B3 47.03 -5.11 785.070477
A4 45.2 -6.77 B4 41.64 -6.18 398.4394688
A5 54.66 -3.07 B5 48.34 -4.41 708.3334745
A6 49.92 -1.14 B6 34.63 0.33 1703.22874
A7 50.05 -4.29 B7 45.49 -0.68 573.8040788
A8 51.69 -3.9 B8 56.13 -1.14 525.3010398
A9 53.05 -2.76 B9 27.89 -5.63 2805.741242
A10 60.06 0.36 B10 36.03 -2.16 2676.308887
A11 30.55 -1.57 B11 28.56 -3.81 309.4651911
我正在使用下面的hasrsine公式来获取excel中的距离输出。
Code :
import pandas as pd
import numpy as np
df = pd.read_excel("df.xlsx")
def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
if to_radians:
lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])
a = np.sin((lat2-lat1)/2.0)**2 + \
np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2
return earth_radius * 2 * np.arcsin(np.sqrt(a))
df['dist'] = \
haversine(df.lat1.shift(), df.lon1.shift(), df.lat2.shift(), df.lon2.shift())
df.to_excel("df_output.xlsx", index = False)`
*尽管我得到了所需的结果,但是它向下移动了一位,如下所示:
使用上面的代码生成的o / p:
Source lat1 lon1 Destination lat2 lon2 Distance
A1 41.66 -2.21 B1 40.62 -2.16
A2 43.92 -4.76 B2 63.99 -7.17 115.6404811
A3 40.56 -1.17 B3 47.03 -5.11 2235.355382
A4 45.2 -6.77 B4 41.64 -6.18 785.070477
A5 54.66 -3.07 B5 48.34 -4.41 398.4394688
A6 49.92 -1.14 B6 34.63 0.33 708.3334745
A7 50.05 -4.29 B7 45.49 -0.68 1703.22874
A8 51.69 -3.9 B8 56.13 -1.14 573.8040788
A9 53.05 -2.76 B9 27.89 -5.63 525.3010398
A10 60.06 0.36 B10 36.03 -2.16 2805.741242
A11 30.55 -1.57 B11 28.56 -3.81 2676.308887
请帮助我获取正确的代码。
预先感谢:)
请帮助某人plzzzzz:)
答案 0 :(得分:0)
尝试使用此代码代替较早的代码:
import pandas as pd
import numpy as np
df = pd.read_excel("df_output.xlsx")
def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
if to_radians:
lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])
a = np.sin((lat2-lat1)/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2
return earth_radius * 2 * np.arcsin(np.sqrt(a))
df['dist'] = haversine(df['lat1'], df['lon1'], df['lat2'], df['lon2'])
df.to_excel("df_output.xlsx", index = False)
这将帮助您...