Python 如何将数据帧中的数据调用到Haversine函数中
我有一个名为lat_long的数据帧,其中包含一些位置的纬度和经度。我想找出以下每个位置之间的差异。当我使用示例函数时,我得到一个错误。KeyError:('1',u'发生在索引0') 尝试: 演示: 尝试: 演示:Python 如何将数据帧中的数据调用到Haversine函数中,python,function,pandas,haversine,Python,Function,Pandas,Haversine,我有一个名为lat_long的数据帧,其中包含一些位置的纬度和经度。我想找出以下每个位置之间的差异。当我使用示例函数时,我得到一个错误。KeyError:('1',u'发生在索引0') 尝试: 演示: 尝试: 演示: “每行的距离”是什么意思?我想找出下面每行之间的差异。@AmyRose,这就是你想要的吗?@MaxU是的,但它一直告诉我“float”对象没有属性“radians”,我导入了数学和numpy。@AmyRose,我在答案中添加了一个演示,其中包含了你的数据-请检查…你的意思是什么“每
“每行的距离”是什么意思?我想找出下面每行之间的差异。@AmyRose,这就是你想要的吗?@MaxU是的,但它一直告诉我“float”对象没有属性“radians”,我导入了数学和numpy。@AmyRose,我在答案中添加了一个演示,其中包含了你的数据-请检查…你的意思是什么“每行的距离?“我想找出下面每一行之间的差异。@AmyRose,这就是你想要的吗?@MaxU是的,但它一直告诉我‘float’对象没有属性‘radians’。我导入了数学和numpy。@AmyRose,我在答案中添加了一个带有你数据的演示-请检查……非常感谢你。”mcuh@AmyRose)非常感谢mcuh@AmyRose,不客气:)
1 2
0 -6.081689 145.391881
1 -5.207083 145.788700
2 -5.826789 144.295861
3 -6.569828 146.726242
4 -9.443383 147.220050
def haversine(row):
lon1 = lat_long['1']
lat1 = lat_long['2']
lon2 = row['1']
lat2 = row['2']
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * arcsin(sqrt(a))
km = 6367 * c
return km
lat_long['distance'] = lat_long.apply(lambda row: haversine(row), axis=1)
lat_long
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
All args must be of equal length.
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6367 * c
return km
In [17]: df
Out[17]:
lat lon
0 -6.081689 145.391881
1 -5.207083 145.788700
2 -5.826789 144.295861
3 -6.569828 146.726242
4 -9.443383 147.220050
In [18]: df['dist'] = \
...: haversine_np(df.lon.shift(), df.lat.shift(), df.ix[1:, 'lon'], df.ix[1:, 'lat'])
In [19]: df
Out[19]:
lat lon dist
0 -6.081689 145.391881 NaN
1 -5.207083 145.788700 106.638117
2 -5.826789 144.295861 178.907364
3 -6.569828 146.726242 280.904983
4 -9.443383 147.220050 323.913612