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

如何使用shapely判断DataFrame中所有坐标点是否在指定Polygon范围内

批量判断DataFrame坐标点是否在多边形内的实现方法

错误原因

你原有代码无法得到正确结果的核心原因是Point()构造函数仅支持传入单个x/y值生成单个点对象,无法直接传入整列数组批量生成点,因此直接调用.within()只会返回单个布尔值,无法得到对应每一行的布尔序列。

实现方案

方案1:pandas apply逐行处理(适合小数据量,写法简洁)

from shapely.geometry import Point, Polygon

# 构造多边形逻辑和原有逻辑一致
box_coords = [top_right_inner, top_left_inner, bottom_left_inner, bottom_right_inner]
poly = Polygon(box_coords)

# 逐行构造点判断是否在多边形内,生成新列
df['Is_In_Center'] = df.apply(
    lambda row: Point(row['Mean_Body_Position_x'], row['Mean_Body_Position_y']).within(poly),
    axis=1
)

方案2:geopandas矢量运算(适合万行以上大数据量,性能远高于逐行处理)

import geopandas as gpd
from shapely.geometry import Polygon

box_coords = [top_right_inner, top_left_inner, bottom_left_inner, bottom_right_inner]
poly = Polygon(box_coords)

# 批量生成所有点的几何列,矢量判断
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['Mean_Body_Position_x'], df['Mean_Body_Position_y']))
df['Is_In_Center'] = gdf.geometry.within(poly)

示例数据验证

你提供的示例坐标(897.615198, 752.755139)的x值大于多边形右上角x坐标828.252039,不在多边形范围内,返回结果为False,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:08