当前位置: 首页 > article >正文

Python 中有哪些库可以帮助读取和操作 shapefile 文件?

Python操作Shapefile文件库推荐

在这里插入图片描述

1. PyShp (pyshp)
  • 特点:纯Python实现,无外部依赖,轻量级,支持完整的Shapefile格式(shp、dbf、shx)读写。
  • 适用场景:基础读写、简单几何操作、文件格式转换。
  • 安装
    pip install 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()
    
    引用[1]详细说明了PyShp的读取流程和功能。

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依赖)。


http://www.kler.cn/a/594996.html

相关文章:

  • 启动方法jupyter(Anaconda)
  • 【最后203篇系列】021 Q201再计划
  • SEARCH-R1:大型语言模型的多轮搜索推理革命
  • 实现一个日语假名自测小程序java之swing版
  • 共注意力机制及创新点深度解析
  • 【原创】通过S3接口将海量文件索引导入elasticsearch
  • VSCode中操作gitee
  • 27.巡风:企业内网漏洞快速应急与巡航扫描系统
  • Flutter 用户电话号码 中间显示*
  • 反射型(CTFHUB)
  • redis MISCONF Redis is configured to save RDB snapshots报错解决
  • 【Kafka】深入了解Kafka
  • C# MethodBase 类使用详解
  • acwing1295. X的因子链
  • CMake 函数和宏
  • 嵌入式软件单元测试的必要性、核心方法及工具深度解析
  • 在 Windows 系统下,将 FFmpeg 编译为 .so 文件
  • Touch Diver:Weart为XR和机器人遥操作专属设计的触觉反馈动捕手套
  • 对敏捷研发的反思,是否真是灵丹妙药?
  • HTTPS 加密过程详解