pyshp 在 shapefile 中生成随机点

pyshp generate random points in shapefile

我想使用 pyshp 在特定邮政编码制表区域 shapefile 中生成 1000 个随机点。我的代码是:

import shapefile

zctashape = shapefile.Reader('C:/mypath/tl_2019_us_zcta510.shp')

shapefile_len = len(zctashape.shapes())

#identify the index for zcta 84049 and designate number of points.
zcta_to_use = '84049'
pointcount = 1000

for i in range(0,shapefile_len):
    if zctashape.record(i)[1] == zcta_to_use:
        record_i=i
        break

record_i

我该如何从这里开始?如果这是基本的,我深表歉意,我主要是 R 用户,使用该语言非常容易。从 https://www.census.gov/cgi-bin/geo/shapefiles/index.php?year=2019&layergroup=ZIP+Code+Tabulation+Areas

下载的形状文件

我正在使用 geopandas,因为我认为它更容易。我不知道是否有一种简单的方法可以单独使用 pyshp:

import numpy as np
import random
from shapely.geometry import Point
import geopandas as gpd
import matplotlib.pyplot as plt

filename = 'tl_2019_us_zcta510.shp'
gdf = gpd.read_file(filename)

#identify the index for zcta 84049 and designate number of points.
zcta_to_use = '84049'
pointcount = 100

aoi = gdf[gdf['ZCTA5CE10'] == zcta_to_use]
aoi_geom = aoi.unary_union

# find area bounds
bounds = aoi_geom.bounds
xmin, ymin, xmax, ymax = bounds

xext = xmax - xmin
yext = ymax - ymin

points = []
while len(points) < pointcount:
    # generate a random x and y
    x = xmin + random.random() * xext
    y = ymin + random.random() * yext
    p = Point(x, y)
    if aoi_geom.contains(p):  # check if point is inside geometry
        points.append(p)

gs = gpd.GeoSeries(points)

fig, ax = plt.subplots()

aoi.plot(ax=ax, facecolor='none', edgecolor='steelblue')
gs.plot(ax=ax, color='r')