错误,python,python-3.x,pandas,jupyter-notebook"/>

首页 > 解决方案 > 如何克服 TypeError: cannot convert the series to错误

问题描述

我正在尝试计算我尝试使用此代码的一些(系列)航班的纬度和经度

import pandas as pd
from math import radians, cos, sin, asin, sqrt
# convert decimal degrees to radians 
lon1 = df1['from_lon'].map(radians)
lat1 = df1['from_lat'].map(radians)
lon2 = df1['dest_lon'].map(radians)
lat2 = df1['dest_lat'].map(radians)
# 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))
results = 3959.0 * c

但我不断收到此错误

TypeError: cannot convert the series to <class 'float'>

我看到很多人在 stackoverflow 上询问这个错误,并尝试了提供给他们的答案。我尝试过以这种方式使用方程

a = dlat.divide(2).apply(sin).pow(2) + cos(lat1) * lat2.apply(cos).multiply(dlon.divide(2).apply(sin).pow(2))

我还尝试使用lambda以及尝试将每个变量转换为浮动使用.astype(float),但不幸的是,我没有任何工作。

lon1、lat1、lon2 和 lat2 的数据类型是float64.a 数据样本:

lon1
-1.826892
-1.287685
-1.534229
-1.534229
-1.826892
1.775173
-0.062252

标签: pythonpython-3.xpandasjupyter-notebook

解决方案


以下是可以正常工作的代码。基本上你需要使用 Series.apply(lambda x: ) 函数。

a = (dlat/2).apply(lambda x : sin(x)) ** 2 + lat1.apply(lambda x : cos(x)) * lat2.apply(lambda x:cos(x))* (dlon/2).apply(lambda x : sin(x)) ** 2 
c = 2 * a.apply(lambda x : asin(sqrt(x))) 
results = 3959.0 * c 

推荐阅读