【问题标题】:Problems with multipart shapes using PyShp when creating a new Shapefile创建新 Shapefile 时使用 PyShp 的多部分形状问题
【发布时间】:2018-07-25 21:11:34
【问题描述】:

我有一个 shapefile (blockgroups.shp),我从以下网址下载: https://github.com/GeospatialPython/pyshp/tree/master/shapefiles

我想使用 PyShp 创建一个只有四个属性(bkg_key、pop1990、white 和 black)的新 Shapefile。

我已尝试使用此代码:

import shapefile
file= "blockgroups.shp"
outFile = "newblockgroup3000"
sf = shapefile.Reader(file)
shapeRec= sf.shapeRecords()
w = shapefile.Writer(shapefile.POLYGON)
w.field('BKG_KEY', 'C', 40)
w.field('POP1990', 'N', 40)
w.field('NWHITES', 'N', 40)
w.field('NBLACKS', 'N', 40)
for row in shapeRec:
    bkg_key = row.record[1]
    pop1990 = row.record[2]
    white = row.record[7]
    black = row.record[8]
    points = row.shape.points
    parts = row.shape.parts
    w.parts = parts
    w.poly([points])
    w.record(bkg_key,pop1990,white,black)
    w.save(outFile)

它适用于除一个以外的所有形状。

有一个记录有多个部分。包含多个部分的记录是'BKG_KEY = 060750601001'和'POP = 4531'。在新的 shapefile 中,这条记录的形状很奇怪,因为 pyShp 会自动连接来自特征不同部分的第一个和最后一个顶点。

如果我只选择 'POP1990 4531' 的记录(不包括提到的记录)它可以工作,所以只有当有多个部分的记录时才会出现问题。

当我创建新的 shapefile 时,有什么方法可以保留原始 shapefile 的部分数量吗?我该如何处理这个问题。

我将不胜感激。 谢谢

【问题讨论】:

    标签: python shapefile pyshp


    【解决方案1】:

    我在寻找使用 pyshp 将多个形状保存在一个 shapefile 中的解决方案时发现了这个问题。你的代码帮助我解决了我的问题,所以我会为此提供一个解决方案。

    import shapefile
    
    file= "blockgroups.shp"
    outFile = "newblockgroup3000"
    sf = shapefile.Reader(file)
    shapeRec= sf.shapeRecords()
    w = shapefile.Writer(shapefile.POLYGON)
    w.field('BKG_KEY', 'C', 40)
    w.field('POP1990', 'N', 40)
    w.field('NWHITES', 'N', 40)
    w.field('NBLACKS', 'N', 40)
    
    for row in shapeRec:
        bkg_key = row.record[1]
        pop1990 = row.record[2]
        white = row.record[7]
        black = row.record[8]
        points = row.shape.points
        parts = row.shape.parts
        geom = []
    
        # handle parts here
        for i in range(len(parts)):
            xy = []
            pt = None
            if i < len(parts) - 1:
                pt = points[parts[i]:parts[i + 1]]
            else:
                pt = points[parts[i]:]
            for x, y in pt:
                xy.append([x, y])
            geom.append(xy)
    
        w.poly(geom)
        w.record(bkg_key,pop1990,white,black)
    w.save()
    
    

    编辑前的结果:

    编辑后的结果:

    【讨论】:

    • 谢谢,我很感激。我什至找到了一个更简单的解决方案,该解决方案在 pyshp 的早期版本(版本 1.x)中有效,但在最新版本(版本 2.x)中却没有。该库发生了重大变化,因此我不得不更新我曾经编写的脚本,您的解决方案非常有帮助。但是,请小心,因为如果您安装最新的 pyshp 版本,您的脚本可能无法运行。
    • 现在,Writer() 参数必须是新文件的名称(不是几何类型),您不需要在脚本末尾使用 save() 保存 shapefile .我建议您查看 pyshp 最新版本的文档。由于这些更改,您可能需要更新脚本。
    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 2018-06-11
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多