python - 尝试使用经度和纬度获取距离,但一直运行到错误 : 'Series' object has no attribute 'radians'

标签 python pandas distance haversine

我有一个包含经度、纬度和其他数据的 csv 文件。使用 pd.read_csv 读取数据,然后将经度和纬度放入数据框中。定义了一个新的 DF:longLat = gps[["Longitude", "Latitude"]] 尝试了 longLat = longLat.apply(pd.to_numeric, errors='raise'),但没有用

Error message: AttributeError: 'Series' object has no attribute 'radians'.

这是我尝试过的:

data1 = pd.read_csv("xxx.csv",index_col = False)
# data1 = data1.apply(pd.to_numeric, errors='ignore')

timestamps = data1["time"]
latitude = data1["latitude"]
longitude = data1["longitude"]
travelstate = data1["travelstate"]

month = []
day = []
hour = []
weekday= []
timestamps.head()
data1.head()
for timestamp in timestamps:
        month.append(datetime.utcfromtimestamp(float(timestamp)).strftime('%m'))
        day.append(datetime.utcfromtimestamp(float(timestamp)).strftime('%d'))
        hour.append(datetime.utcfromtimestamp(float(timestamp)).strftime('%H'))
        weekday.append((pd.to_datetime(timestamp, unit = "s").weekday()))

gps = pd.DataFrame(columns = ["Month","Day","Hour","Weekday","Longitude","Latitude","Travel State"])
gps["Month"] = month
gps["Day"] = day
gps["Hour"] = hour
gps["Weekday"] =weekday
gps["Longitude"] = longitude
gps["Latitude"] = latitude
gps["Travel State"] = travelstate

longLat = gps[["Longitude", "Latitude"]]

def haversine(lat1, lon1, lat2, lon2, to_radians= True,
    earth_radius=6371):
        if to_radians:
            lat1, lon1, lat2, lon2 = numpy.radians([lat1, lon1, lat2, lon2])

        a = np.sin((lat2-lat1)/2.0)**2 + \
            np.cos(lat1) * np.cos(lat2) * numpy.sin((lon2-lon1)/2.0)**2

        return earth_radius * 2 * np.arcsin(np.sqrt(a))

a = haversine(longLat.Longitude.shift(), longLat.Latitude.shift(),
    longLat.loc[1:,"Longitude"], longLat.loc[1:,"Latitude"])

print(a)

最佳答案

gps['p_latitude'] = gps['Latitude'].shift(1)
gps['p_longitude'] = gps['Longitude'].shift(1)


distanceI = gps[['p_latitude', 'p_longitude', 'Latitude','Longitude']].apply(lambda x: haversine(x[1], x[0], x[3], x[2]), axis=1)

这是一个很好的解决方案,除了你必须交换 haversine(x[1], x[0], x[3], x[2]), axis=1) 到 apply(lambda x: haversine(x[ 0], x[1], x[2], x[3]), 轴=1)

关于python - 尝试使用经度和纬度获取距离,但一直运行到错误 : 'Series' object has no attribute 'radians' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582492/

相关文章:

python - 使用 Python 在 PDF 3D 中保存 3D 图

python - 搜索列中有多个字符串但显示错误 Python Pandas

python - 使用 iloc() 根据范围和单个整数选择列

c++ - 两根弦之间的距离

distance - 使用哪种数据结构来存储二进制字符串并使用汉明距离进行查询

python - 如何设置pyqtgraph轴标签偏移量?

python - 有效扩张线性回归

OOP 中的 python 属性装饰器

algorithm - 如何找到数组中的最小距离?

python - 在 pandas 中传播缺失日期的值