python - 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
解决方案
问题“我需要如何设置 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
,但这需要更改一些不在问题中的代码。
推荐阅读
- python - 时间复杂度 - Python eval 的 BigO 表示法
- html - html 顶部的白条(已经没有边距)
- angular - ViewChild 返回“未定义”-Angular2
- javascript - keycloak 版本和带有 JS 前端的 Spring Boot App 的自动令牌更新问题
- javascript - 检查名称列上的哪个单元格等于某些文本
- c++ - 为什么这个随机数生成器不是线程安全的?
- javascript - 如何获取数组中子项的长度
- mysql - mysql - 使用 sum 和 rollup 获取列的百分比
- c# - 避免在 Entity Framework Core 的 DbContext 中使用“使用块”是否安全?
- r - 在 R 中安装“预测”包的问题