You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于lon_bnds、lat_bnds边界数组筛选网格内部坐标点

问题说明

现有由两组边界数组lon_bnds和lat_bnds定义的非规则网格,需要筛选所有落在网格内部的坐标点,最终返回仅包含内部点的DataFrame对象。

示例代码与效果

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd


lon_bnds = np.array([[-77.9645  , -77.56074 , -77.162025, -76.76827 , -76.37937 ],
                    [-77.88815 , -77.48613 , -77.08915 , -76.69711 , -76.30993 ],
                    [-77.811676, -77.41139 , -77.01614 , -76.62582 , -76.24034 ],
                    [-77.73638 , -77.337814, -76.944275, -76.55565 , -76.17186 ],
                    [-77.66197 , -77.265114, -76.87326 , -76.48632 , -76.1042  ]])

lat_bnds = np.array([[-77.34674 , -77.35804 , -77.36858 , -77.378395, -77.38752 ],
                    [-77.28847 , -77.299614, -77.31001 , -77.31969 , -77.328674],
                    [-77.23022 , -77.24122 , -77.25147 , -77.26101 , -77.26986 ],
                    [-77.17193 , -77.182785, -77.192894, -77.20229 , -77.211006],
                    [-77.11363 , -77.12434 , -77.13431 , -77.14357 , -77.15215 ]])

plt.scatter(lon_bnds, lat_bnds, label='corner')

d = {'longitude': [-79, -77.2, -77, -75.5], 'latitude': [-77.4, -77.2, -77.3, -77.3]}
df_points = pd.DataFrame(data=d)
plt.scatter(df_points['longitude'], df_points['latitude'], c='r', label='points')

plt.legend()

示例效果图

注:基于kdTree的近邻搜索方案仅能匹配距离最近的网格点,无法直接基于精确边界做点包含判断,不适用于当前场景。

实现方案

采用多边形点包含判断逻辑,逐网格单元构造四边形边界,批量判断点是否落在单元内部,最终汇总所有命中的点即可。

import numpy as np
import pandas as pd
from matplotlib.path import Path

# 沿用上述示例中的lon_bnds、lat_bnds、df_points数据
points = df_points[['longitude', 'latitude']].values
in_grid_mask = np.zeros(len(points), dtype=bool)

# 边界数组维度为(M,N)时,对应(M-1)*(N-1)个四边形网格单元
n_rows, n_cols = lon_bnds.shape
for i in range(n_rows - 1):
    for j in range(n_cols - 1):
        # 提取当前单元四个角点的坐标,按顺时针/逆时针顺序构造四边形
        cell_lon = [
            lon_bnds[i, j], lon_bnds[i, j+1],
            lon_bnds[i+1, j+1], lon_bnds[i+1, j]
        ]
        cell_lat = [
            lat_bnds[i, j], lat_bnds[i, j+1],
            lat_bnds[i+1, j+1], lat_bnds[i+1, j]
        ]
        cell_polygon = np.column_stack((cell_lon, cell_lat))
        # 判断所有点是否落在当前单元内
        cell_path = Path(cell_polygon)
        in_current_cell = cell_path.contains_points(points)
        in_grid_mask = in_grid_mask | in_current_cell

# 筛选得到网格内部点,结果正好包含预期的2个点
df_inner_points = df_points[in_grid_mask].reset_index(drop=True)

方案说明

  • 直接基于输入的边界数组构造网格多边形,不需要额外做网格插值、坐标转换,完全适配精确边界的判断需求
  • 内置的点包含判断逻辑支持形变的四边形网格,不要求网格为规则等距经纬度网格
  • 针对超大规模网格场景,可以将所有网格多边形合并为多要素几何后做批量空间判断,进一步提升运行效率,中小规模网格下当前遍历写法可读性更高。

内容的提问来源于stack exchange,提问作者zxdawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 08:15:32