首页 > 解决方案 > 在 Python 中将列转换为多边形以在多边形中执行点

问题描述

我已经编写了代码以在 Python 中建立多边形中的点,该程序使用我读入的 shapefile 作为多边形。我现在有一个数据框,其中包含一个包含多边形的列,例如[[28.050815,-26.242253],[28.050085,-26.25938],[28.011934,-26.25888],[28.020216,-26.230127],[28.049828,-26.230704],[28.050815,-26.242253]]. 我想将此列转换为多边形以执行多边形中的点,但所有示例都使用geometry = [Point(xy) for xy in zip(dataPoints['Long'], dataPoints['Lat'])]但我的已经是 zip?我将如何实现这一目标?

谢谢

标签: pythongeopandaspoint-in-polygon

解决方案


以上面的示例为例,您可以执行以下操作:

list_coords = [[28.050815,-26.242253],[28.050085,-26.25938],[28.011934,-26.25888],[28.020216,-26.230127],[28.049828,-26.230704],[28.050815,-26.242253]]
from shapely.geometry import Point, Polygon

# Create a list of point objects using list comprehension

point_list = [Point(x,y) for [x,y] in list_coords]

# Create a polygon object from the list of Point objects

polygon_feature = Polygon([[poly.x, poly.y] for poly in point_list])

如果您想将其应用于数据框,您可以执行以下操作:

import pandas as pd
import geopandas as gpd

df = pd.DataFrame({'coords': [list_coords]})

def get_polygon(list_coords):

    point_list = [Point(x,y) for [x,y] in list_coords]

    polygon_feature = Polygon([[poly.x, poly.y] for poly in point_list])

    return polygon_feature

df['geom'] = df['coords'].apply(get_polygon)

但是,为了避免“重新发明轮子”,可能有 geopandas 内置功能,所以让我们看看是否有其他人有建议:)


推荐阅读