Python 中有哪些库可以帮助读取和操作 shapefile 文件?
Python操作Shapefile文件库推荐
1. PyShp (pyshp)
- 特点:纯Python实现,无外部依赖,轻量级,支持完整的Shapefile格式(shp、dbf、shx)读写。
- 适用场景:基础读写、简单几何操作、文件格式转换。
- 安装:
pip install pyshp
- 示例代码:
引用[1]详细说明了PyShp的读取流程和功能。import shapefile # 读取文件 sf = shapefile.Reader("example.shp") shapes = sf.shapes() # 几何对象 records = sf.records() # 属性表 # 写入文件 w = shapefile.Writer("new_file.shp") w.field("name", "C") # 添加字段 w.point(120, 30) # 添加点几何 w.record("Point1") # 添加属性记录 w.close()
2. GeoPandas
- 特点:基于Pandas的扩展,提供高级数据操作(如空间连接、空间查询),支持直接读写Shapefile。
- 优势:集成Shapely几何操作、支持空间索引、与Matplotlib无缝结合可视化。
- 依赖:需安装
fiona
(读写库)、shapely
(几何操作)、pyproj
(坐标转换)。 - 安装:
pip install geopandas
- 示例代码:
import geopandas as gpd # 读取文件 gdf = gpd.read_file("example.shp") # 空间查询(如筛选包含某点的要素) from shapely.geometry import Point point = Point(120, 30) result = gdf[gdf.contains(point)] # 写入文件 gdf.to_file("output.shp")
3. Fiona
- 特点:基于GDAL的高性能读写库,支持多种地理空间格式(包括Shapefile)。
- 适用场景:复杂格式处理、批量操作、与GDAL工具链集成。
- 安装:
pip install fiona
- 示例代码:
import fiona # 读取文件 with fiona.open("example.shp") as src: for feature in src: geometry = feature["geometry"] # 几何对象(GeoJSON格式) properties = feature["properties"] # 属性表 # 写入文件 schema = {"geometry": "Point", "properties": {"name": "str"}} with fiona.open("output.shp", "w", "ESRI Shapefile", schema) as dst: dst.write({"geometry": {"type": "Point", "coordinates": (120, 30)}, "properties": {"name": "Point1"}})
4. Shapely(辅助库)
- 作用:处理几何对象(如计算面积、缓冲区分析、空间关系判断)。
- 搭配使用:常与PyShp或Fiona联合使用。
- 示例:
from shapely.geometry import Polygon polygon = Polygon([(0, 0), (1, 1), (1, 0)]) print(polygon.area) # 计算面积
推荐选择
- 简单读写:优先选择
PyShp
(代码简洁,依赖少)。 - 数据分析:使用
GeoPandas
(支持Pandas操作,适合复杂分析)。 - 高性能/多格式:选择
Fiona
(需处理GDAL依赖)。