如何在Python中读取shapefile?


23

我的问题是多边形shapefile垂直线的扩展。请先参考该问题。

您将看到的是一种以用户定义的间距相对于边界框生成垂直线的方法。我知道OGR,Fiona,Shapely等可用于下一步剪切,但我不了解它们的使用情况。

如何读取多边形shapefile的一行?每个使用Shapely的应用程序都显示了如何生成LineString,Point或Polygon,但是从不读取现有shapefile

请至少为我提供一个骨架结构,以便我可以在其上进行构建。

Answers:


40

1)使用geo_interface协议(GeoJSON)使用FionaPyShp,ogr或... 读取shapefile :

与菲奥娜

import fiona
shape = fiona.open("my_shapefile.shp")
print shape.schema
{'geometry': 'LineString', 'properties': OrderedDict([(u'FID', 'float:11')])}
#first feature of the shapefile
first = shape.next()
print first # (GeoJSON format)
{'geometry': {'type': 'LineString', 'coordinates': [(0.0, 0.0), (25.0, 10.0), (50.0, 50.0)]}, 'type': 'Feature', 'id': '0', 'properties': OrderedDict([(u'FID', 0.0)])}

与PyShp

import shapefile
shape = shapefile.Reader("my_shapefile.shp")
#first feature of the shapefile
feature = shape.shapeRecords()[0]
first = feature.shape.__geo_interface__  
print first # (GeoJSON format)
{'type': 'LineString', 'coordinates': ((0.0, 0.0), (25.0, 10.0), (50.0, 50.0))}

与OGR:

from osgeo import ogr
file = ogr.Open("my_shapefile.shp")
shape = file.GetLayer(0)
#first feature of the shapefile
feature = shape.GetFeature(0)
first = feature.ExportToJson()
print first # (GeoJSON format)
{"geometry": {"type": "LineString", "coordinates": [[0.0, 0.0], [25.0, 10.0], [50.0, 50.0]]}, "type": "Feature", "properties": {"FID": 0.0}, "id": 0}

2)转换为Shapely几何(具有形状功能)

# now use the shape function of Shapely
from shapely.geometry import shape
shp_geom = shape(first['geometry']) # or shp_geom = shape(first) with PyShp)
print shp_geom
LINESTRING (0 0, 25 10, 50 50)
print type(shp_geom)
<class 'shapely.geometry.linestring.LineString'>

3)计算

4)保存生成的shapefile


5
我会在列表中添加“ geopandas”:geopandas.read_file("my_shapefile.shp")
joris

从GDAL 2.0开始,osgeo.ogr.Open使用而不是,请使用osgeo.gdal.OpenExdetails)。
凯文(Kevin)

1
与ogr一起,我首先必须将json定义为json,以便能够以匀称的方式进一步处理它:'first = json.loads(first)'
Leo

11

我发现Geopandas在这里表现最好。码:

import geopandas as gpd
shapefile = gpd.read_file("shapefile.shp")
print(shapefile)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.