创建新的Shapefile时使用PyShp进行多部分形状的问题

时间:2018-07-25 21:11:35

标签: python shapefile pyshp

我有一个shapefile(blockgroups.shp)是从以下位置下载的: https://github.com/GeospatialPython/pyshp/tree/master/shapefiles

我想使用PyShp创建一个只有四个属性(bkg_key,pop1990,白色和黑色)的新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”记录和“ POP1990> 4531”记录(不包括提到的记录),则它可以正常工作,因此仅当包含多个部分的记录时才会出现此问题。

当我创建新的shapefile时,有什么方法可以保留它的数量吗?我该如何解决这个问题。

我将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:0)

我在寻找一种使用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()

编辑前的结果: enter image description here

编辑后的结果: enter image description here