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