使用Python计算多边形图形文件中的点数

wuf*_*uff 2 python geolocation shapefile qgis shapely

我有一个由各个州组成的美国多边形图形文件,作为其属性值。此外,我还有一些数组,用于存储我也感兴趣的点事件的纬度和经度值。从本质上讲,我想“空间连接”点和面(或执行检查以查看每个面和面[即状态])点),然后求和每个州的点数,找出哪个州的“事件”数最多。

我相信伪代码将是这样的:

Read in US.shp
Read in lat/lon points of events
Loop through each state in the shapefile and find number of points in each state
print 'Here is a list of the number of points in each state: '
Run Code Online (Sandbox Code Playgroud)

任何库或语法将不胜感激。

根据我的判断,OGR库是我所需要的,但是我在语法上遇到了麻烦:

dsPolygons = ogr.Open('US.shp')  

polygonsLayer = dsPolygons.GetLayer()  


#Iterating all the polygons  
polygonFeature = polygonsLayer.GetNextFeature()  
k=0  
while polygonFeature:
    k = k + 1  
    print  "processing " + polygonFeature.GetField("STATE") + "-" + str(k) + " of " + str(polygonsLayer.GetFeatureCount())  

    geometry = polygonFeature.GetGeometryRef()          

    #Read in some points?
    geomcol = ogr.Geometry(ogr.wkbGeometryCollection)
    point = ogr.Geometry(ogr.wkbPoint)
    point.AddPoint(-122.33,47.09)
    point.AddPoint(-110.11,33.33)
    #geomcol.AddGeometry(point)
    print point.ExportToWkt()
    print point
    numCounts=0.0   
    while pointFeature:  
        if pointFeature.GetGeometryRef().Within(geometry):  
            numCounts = numCounts + 1  
        pointFeature = pointsLayer.GetNextFeature()
    polygonFeature = polygonsLayer.GetNextFeature()
    #Loop through to see how many events in each state
Run Code Online (Sandbox Code Playgroud)

kwi*_*nks 5

我喜欢这个问题。我怀疑我能给您最好的答案,但绝对不能帮助您进行OGR,但是FWIW我会告诉您我现在正在做什么。

我使用的是GeoPandas,这是熊猫的地理空间扩展。我推荐它-它是高级的,而且功能很多,可以免费为您提供Shapelyfiona中的所有功能。它正在由twitter / @ kajord等人积极开发。

这是我的工作代码版本。它假定您在shapefile中包含所有内容,但是geopandas.GeoDataFrame从列表中生成一个很容易。

import geopandas as gpd

# Read the data.
polygons = gpd.GeoDataFrame.from_file('polygons.shp')
points = gpd.GeoDataFrame.from_file('points.shp')

# Make a copy because I'm going to drop points as I
# assign them to polys, to speed up subsequent search.
pts = points.copy() 

# We're going to keep a list of how many points we find.
pts_in_polys = []

# Loop over polygons with index i.
for i, poly in polygons.iterrows():

    # Keep a list of points in this poly
    pts_in_this_poly = []

    # Now loop over all points with index j.
    for j, pt in pts.iterrows():
        if poly.geometry.contains(pt.geometry):
            # Then it's a hit! Add it to the list,
            # and drop it so we have less hunting.
            pts_in_this_poly.append(pt.geometry)
            pts = pts.drop([j])

    # We could do all sorts, like grab a property of the
    # points, but let's just append the number of them.
    pts_in_polys.append(len(pts_in_this_poly))

# Add the number of points for each poly to the dataframe.
polygons['number of points'] = gpd.GeoSeries(pts_in_polys)
Run Code Online (Sandbox Code Playgroud)

开发人员告诉我,空间连接是“开发版本中的新增功能”,因此,如果您想在那儿闲逛,我很想听听情况如何!我的代码的主要问题是速度很慢。