【发布时间】:2021-02-20 20:10:56
【问题描述】:
我不熟悉经纬度的东西。我发现了一个看起来很有趣的半正弦函数。我尝试将两个数据框输入到函数中,但出现错误。
这是函数。
import numpy as np
lon1 = df["longitude_fuze"]
lat1 = df["latitude_fuze"]
lon2 = df["longitude_air"]
lat2 = df["latitude_air"]
# Haversine
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, 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['haversine_dist'] = haversine(lon1,lat1,lon2,lat2)
函数编译正常,但是当我尝试调用它时,我得到了这个错误。
df['haversine_dist'] = haversine(lon1,lat1,lon2,lat2)
Traceback (most recent call last):
File "<ipython-input-38-cc7e470610ee>", line 1, in <module>
df['haversine_dist'] = haversine(lon1,lat1,lon2,lat2)
File "<ipython-input-37-f357b0fc2e88>", line 16, in haversine
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
File "C:\Users\ryans\anaconda3\lib\site-packages\pandas\core\series.py", line 129, in wrapper
raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'float'>
这是我正在测试的两个数据框。
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['NY', 'Uniondale', 'Nassau', '40.72', '-73.59'],
['NY', 'Uniondale', 'Nassau', '40.72', '-73.59'],
['NY', 'Uniondale', 'Nassau', '40.72', '-73.59'],
['NY', 'NY', 'New York', '40.76', '73.98'],
['NY', 'NY', 'New York', '40.76', '73.98']]
# Create the pandas DataFrame
df_result = pd.DataFrame(data, columns = ['state', 'city', 'county','latitude_fuze','longitude_fuze'])
# print dataframe.
df_result
data = [['New York', 'JFK', '40.63', '-73.60'],
['New York', 'JFK', '40.64', '-73.78'],
['Los Angeles', 'LAX', '33.94', '-118.41'],
['Chicago', 'ORD', '40.98', '73.90'],
['San Francisco', 'SFO', '40.62', '73.38']]
# Create the pandas DataFrame
df_airports = pd.DataFrame(data, columns = ['municipality_name', 'airport_code', 'latitude_air','longitude_air'])
# print dataframe.
df_airports
我在这个链接找到了这个函数。
【问题讨论】:
标签: python python-3.x haversine