首页 > 解决方案 > Python for循环遍历一列的所有行

问题描述

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

我为此使用了半正弦公式,我只输入中心点的纬度和经度值以及要测试的点的纬度和经度值(如果它在给定的半径内)。

所以我认为我需要一个 for 循环,在其中我为 lat 和 lon 列的每一行运行 hasrsine 公式,如果坐标在半径内,我将它们保存在一个列表中。

#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

标签: pythonpandasfor-loopmathhaversine

解决方案


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

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序列而不是值的方式构建,并且可以比 using 更快地实现df.apply,但这需要更改一些不在问题中的代码。


推荐阅读