问题描述
我正在尝试创建一个新列来操作数据集:
df['longitude'] = df['longitude'].astype(float)
df['latitude'] = df['latitude'].astype(float)
然后运行半正弦函数: 从数学导入弧度、cos、sin、asin、sqrt
def haversine(lon1,lat1,lat2,lon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1,lon2,lat2 = map(radians,[lon1,lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
但是当我运行这段代码时:
df['d_centre']=haversine(lon1,df.longitude.astype(float),df.latitude.astype(float))
Error: cannot convert the series to <class 'float'>
我也试过这个:
df['d_centre']= haversine(lon1,lon2)
haversine 正在工作,但是当我尝试在我的 df 中创建新列时,出现此错误。我也尝试转换为列表,但结果相同
解决方法
我想出了答案:必须使用 numpy 进行所有数学运算,并使用 df 为新列编写代码
从数学导入弧度、cos、sin、asin、sqrt def haversine_np(lon1,lat1,lon2,lat2): """ 计算两点之间的大圆距离 在地球上(以十进制度数指定) """ # 将十进制度数转换为弧度 lon1,lat2 = map(np.radians,[lon1,lat2]) # 半正弦公式 dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2 c = 2 * np.arcsin(np.sqrt(a)) 公里 = 6367 * c 回程公里
创建一个新列: df2['d_centre'] =haversine_np(df2['lon1'],df2['lat1'],df2['lon2'],df2['lat2'])