要计算pandas数据帧中两个站点的纬度和经度之间的距离,可以使用Haversine公式。Haversine公式用于计算地球表面两点之间的最短距离(大圆距离)。以下是详细的步骤和示例代码:
Haversine公式基于球面三角学,适用于计算地球表面上两点之间的距离。公式如下:
[ a = \sin^2\left(\frac{\Delta \phi}{2}\right) + \cos(\phi_1) \cdot \cos(\phi_2) \cdot \sin^2\left(\frac{\Delta \lambda}{2}\right) ]
[ c = 2 \cdot \text{atan2}\left(\sqrt{a}, \sqrt{1-a}\right) ]
[ d = R \cdot c ]
其中:
以下是一个使用Python和pandas计算两个站点之间距离的示例代码:
import pandas as pd
import numpy as np
# 示例数据帧
data = {
'site': ['A', 'B'],
'latitude': [34.0522, 40.7128],
'longitude': [-118.2437, -74.0060]
}
df = pd.DataFrame(data)
# 将纬度和经度转换为弧度
df['latitude'] = np.radians(df['latitude'])
df['longitude'] = np.radians(df['longitude'])
# 计算两个站点之间的距离
R = 6371 # 地球半径,单位为公里
def haversine(row):
phi1, lon1 = row['latitude'], row['longitude']
phi2, lon2 = df.loc[df['site'] != row['site'], 'latitude'].values[0], df.loc[df['site'] != row['site'], 'longitude'].values[0]
dphi = phi2 - phi1
dlon = lon2 - lon1
a = np.sin(dphi / 2) ** 2 + np.cos(phi1) * np.cos(phi2) * np.sin(dlon / 2) ** 2
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
return R * c
df['distance'] = df.apply(haversine, axis=1)
print(df)
通过以上步骤和代码示例,你可以计算pandas数据帧中两个站点的纬度和经度之间的距离。
领取专属 10元无门槛券
手把手带您无忧上云