Python forloop遍历一列的所有行

2024-10-02 02:39:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从给定半径内的表格中提取所有坐标。 我需要如何设置for循环

我使用哈弗斯公式,输入中心点的lat和lon值,如果在给定的半径内,输入要测试点的lat和lon值

所以我想我需要一个for循环,在这里我为lat和lon列的每一行运行haversine公式,如果cooridnate在半径范围内,我将它们保存在一个列表中

#Get coordinates
#Center coordinates = nearest road location
lat1 = float(lowParkingUtilization.iloc[roadIndex].toLat)
lon1 = float(lowParkingUtilization.iloc[roadIndex].toLon)
#Test coordinates = scooter coordinates
insideRadius = []

radius = 2.50 # in kilometer

for i in eScooterVOI['lat']:
    lat2 = float(eScooterVOI['lat'][i])
    lon2 = float(eScooterVOI['lon'][i])
    a = haversine(lon1, lat1, lon2, lat2)

    if a <= radius:
        insideRadius += str(lon2)+","+str(lat2)
    else:

使用给定的代码,我得到以下错误消息:

 File "<ipython-input-574-02dadebee55c>", line 18

    ^
SyntaxError: unexpected EOF while parsing

Tags: for半径float公式lonlatcoordinateshaversine
3条回答

出现此错误是因为else块。 当Python读取它时,它希望编写一些代码。Python没有发现任何错误,因此发生了错误

您的代码可能已经运行得很好了,只需删除else块,就可以使用if块,而不必绑定使用else

无论如何,如果您确实想使用else块,请尝试以下操作:

if a <= radius:
    insideRadius += str(lon2)+","+str(lat2)
else : 
    pass

但我不认为这是推荐的

SyntaxError: unexpected EOF while parsing错误消息意味着一些代码块没有完成,代码已经结束

else块至少需要一行应该在其中的代码

例如:

else:
    lots_of_code_to_write_here

“我需要如何设置for循环?”这个问题的正确答案是:你不需要pandas数据帧不用于在其行上循环。您需要做的是在dataframe中创建两个新列,一个用于计算距离,另一个用于以所需格式存储名称:

eScooterVOI['dist'] = eScooterVOI.apply(lambda x: haversine(lon1, lat1, x['lon'], x['lat']), axis=1)
eScooterVOI['name'] = eScooterVOI['lon'].astype(str) + ',' + eScooterVOI['lat'].astype(str)

然后,要获得仅包含距离小于半径的坐标名称的列表,请使用:

insideRadius = list(eScooterVOI[eScooterVOI['dist'] <= radius]['name'])

顺便说一句:haversine函数的构建方式是它接收一个pandas序列而不是一个值,通过这种方式,它的实现速度可能比使用df.apply要快得多,但这需要更改一些不在这里讨论的代码

相关问题 更多 >

    热门问题