Python划分巴拿马地图等距经纬度坐标的循环错误修正求助
代码修正方案
修改点说明
- 调整经纬度序列的长度:将经度序列
cols的生成参数num设为646,满足long.nunique()返回646的需求,纬度序列rows的num设为276,匹配原有正确的纬度唯一值数量 - 修正循环索引范围:使用
len()动态获取数组长度作为range参数,避免写死数值导致丢失最后一个元素 - 修正索引与数组的对应关系:避免用超出经度数组长度的索引取值导致报错
- 删除无效代码:
i + 1、l + 1、i = 0无赋值操作,完全不影响运行逻辑,直接移除 - 修正
searchsorted参数对应:纬度值匹配纬度序列,经度值匹配经度序列,避免后续站点映射错误
完整修正后代码
import pandas as pd import numpy as np bottomLeft = (7.239013, -82.94546842973114) bottomRight = (7.239013, -77.177479) topLeft = (9.62079503922844, -82.94546842973114) topRight = (9.62079503922844, -77.177479) df = pd.read_csv('sites_unique.csv') # 调整经纬度序列长度,经度设为646个点 cols = np.linspace(bottomLeft[1], bottomRight[1], num=646) rows = np.linspace(bottomLeft[0], topLeft[0], num=276) # 修正searchsorted的参数对应,纬度匹配纬度序列,经度匹配经度序列 df['col'] = np.searchsorted(cols, df['Average of long'], 'right') df['row'] = np.searchsorted(rows, df['Average of lat'], 'right') grid_dict = {'lat':[],'long':[]} # 修正循环范围和索引对应 for lon_idx in range(len(cols)): for lat_idx in range(len(rows)): grid_dict['lat'].append(rows[lat_idx]) grid_dict['long'].append(cols[lon_idx]) grid_centroid = pd.DataFrame(grid_dict)
运行后执行grid_centroid.long.nunique()将返回646,符合需求。
内容的提问来源于stack exchange,提问作者Dubey Capital
相关产品推荐
相关产品推荐

