首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pyshp在shapefile中生成随机点

pyshp在shapefile中生成随机点
EN

Stack Overflow用户
提问于 2020-03-04 20:30:24
回答 1查看 516关注 0票数 0

我想要生成1000个随机点在一个特定的ZIP代码表区格式文件使用pyshp。我的代码是:

代码语言:javascript
复制
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下载的Shapefile

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-04 21:14:48

我正在使用geopandas,因为我认为它使它更容易。我不知道是否有一种简单的方法仅用pyshp来实现这一点

代码语言:javascript
复制
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')

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60534219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档