我有一个我从https://github.com/GeospatialPython/pyshp/tree/master/shapefiles下载的shapefile (blockgroups.shp
我想用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时,有没有办法保持原始shapefile的部件数?我该如何处理这个问题。
如果能帮上忙我会很感激。谢谢
发布于 2019-05-24 16:42:30
我发现这个问题是在寻找一个使用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()编辑前的结果:

编辑后的结果:

https://stackoverflow.com/questions/51527720
复制相似问题