关于 alterlab-geopandas
alterlab-geopandas 是面向地理空间分析任务的技能,指导使用 GeoPandas 处理矢量数据、执行空间运算并制作地图。内容涵盖数据读写、坐标参考系和常见分析流程。
主要功能
- 01读写多种矢量数据格式
- 02执行空间连接与叠加分析
- 03管理坐标参考系并重投影
- 04制作静态及交互式地图
适用场景
- 01转换 Shapefile、GeoJSON 等数据
- 02将点与多边形进行空间连接
- 03按合适坐标系测量面积和距离
- 04从矢量数据制作专题地图
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-geopandas安装后在 Claude Code 中输入/alterlab-geopandas确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
evals/evals.jsonreferences/crs-management.mddata-io.mddata-structures.mdgeometric-operations.mdspatial-analysis.mdvisualization.md详细介绍
GeoPandas
GeoPandas 扩展了 pandas,支持对几何类型执行空间操作。它结合了 pandas 和 shapely 的功能,用于地理空间数据分析。
何时使用此技能
当用户希望进行以下操作时,使用此技能:
- 读取、写入或转换矢量数据(Shapefile、GeoJSON、GeoPackage、GeoParquet、PostGIS)
- 执行空间连接、叠加、缓冲区、融合、裁剪或最近邻连接
- 在坐标参考系统之间重投影,并准确测量面积、长度和距离
- 根据表格矢量数据制作静态或交互式(folium)分级统计地图
不适用的情况
| 场景 | 改用 |
|---|---|
| 栅格、卫星影像、DEM、光谱指数、STAC/COG 或地球观测机器学习 | alterlab-geomaster |
| 不含几何信息的关系网络/图分析(中心性、社群) | alterlab-networkx |
| 基因组区间重叠(BED 文件)——沿染色体进行的“空间”连接 | alterlab-gtars |
| 天球坐标、FITS/WCS 天空位置 | alterlab-astropy |
安装
uv pip install geopandas # 1.x (current 1.1.x as of 2026-09); shapely 2 + pyogrio
GeoPandas 1.x 要求 shapely ≥ 2,并且默认通过 pyogrio 读取/写入(fiona 为可选项)。1.x 系列中已移除或弃用的内容包括:sjoin(op=...)(改用 predicate=)、unary_union(改用 union_all()),以及捆绑的 geopandas.datasets 文件(改用 geodatasets 包)。
可选依赖
# For interactive maps
uv pip install folium
# For classification schemes in mapping
uv pip install mapclassify
# For faster I/O operations (2-4x speedup)
uv pip install pyarrow
# For PostGIS database support (SQLAlchemy engine + driver; geoalchemy2 for to_postgis)
uv pip install sqlalchemy "psycopg[binary]" geoalchemy2
# For basemaps
uv pip install contextily
# For cartographic projections
uv pip install cartopy
快速入门
import geopandas as gpd
# Read spatial data
gdf = gpd.read_file("data.geojson")
# Basic exploration
print(gdf.head())
print(gdf.crs)
print(gdf.geometry.geom_type)
# Simple plot
gdf.plot()
# Reproject to a metric CRS suited to the data (local UTM zone)
gdf_projected = gdf.to_crs(gdf.estimate_utm_crs())
# Calculate area in m² (use an equal-area CRS such as EPSG:6933 for continental extents;
# never Web Mercator EPSG:3857 — it inflates areas ~4x at 60° latitude)
gdf_projected['area'] = gdf_projected.geometry.area
# Save to file
gdf.to_file("output.gpkg")
核心概念
数据结构
- GeoSeries:支持空间操作的几何向量
- GeoDataFrame:包含几何列的表格数据结构
详情请参阅 data-structures.md。
读取和写入数据
GeoPandas 支持读取/写入多种格式:Shapefile、GeoJSON、GeoPackage、PostGIS、Parquet。
# Read with filtering
gdf = gpd.read_file("data.gpkg", bbox=(xmin, ymin, xmax, ymax))
# Write with Arrow acceleration
gdf.to_file("output.gpkg", use_arrow=True)
有关完整的 I/O 操作说明,请参阅 data-io.md。
坐标参考系统
始终检查并管理 CRS,以确保空间操作准确:
# Check CRS
print(gdf.crs)
# Reproject (transforms coordinates). EPSG:3857 (Web Mercator) is for web tiles only;
# measure in a local UTM (gdf.estimate_utm_crs()) or an equal-area CRS
gdf_projected = gdf.to_crs("EPSG:3857")
# Set CRS (only when metadata missing)
gdf = gdf.set_crs("EPSG:4326")
有关 CRS 操作,请参阅 crs-management.md。
常见操作
几何操作
缓冲区、简化、质心、凸包、仿射变换:
# Buffer by 10 units
buffered = gdf.geometry.buffer(10)
# Simplify with tolerance
simplified = gdf.geometry.simplify(tolerance=5, preserve_topology=True)
# Get centroids
centroids = gdf.geometry.centroid
有关所有操作,请参阅 geometric-operations.md。
空间分析
空间连接、叠加操作、融合:
# Spatial join (intersects)
joined = gpd.sjoin(gdf1, gdf2, predicate='intersects')
# Nearest neighbor join
nearest = gpd.sjoin_nearest(gdf1, gdf2, max_distance=1000)
# Overlay intersection
intersection = gpd.overlay(gdf1, gdf2, how='intersection')
# Dissolve by attribute
dissolved = gdf.dissolve(by='region', aggfunc='sum')
有关分析操作,请参阅 spatial-analysis.md。
可视化
创建静态和交互式地图:
# Choropleth map
gdf.plot(column='population', cmap='YlOrRd', legend=True)
# Interactive map
gdf.explore(column='population', legend=True).save('map.html')
# Multi-layer map
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
gdf1.plot(ax=ax, color='blue')
gdf2.plot(ax=ax, color='red')
有关制图技术,请参阅 visualization.md。
详细文档
- Data Structures - GeoSeries 和 GeoDataFrame 基础知识
- Data I/O - 读取/写入文件、PostGIS、Parquet
- Geometric Operations - 缓冲区、简化、仿射变换
- Spatial Analysis - 连接、叠加、融合、裁剪
- Visualization - 绘图、分级统计地图、交互式地图
- CRS Management - 坐标参考系统和投影
常见工作流
加载、转换、分析、导出
# 1. Load data
gdf = gpd.read_file("data.shp")
# 2. Check and transform CRS (metric, local UTM zone)
print(gdf.crs)
gdf = gdf.to_crs(gdf.estimate_utm_crs())
# 3. Perform analysis
gdf['area'] = gdf.geometry.area
buffered = gdf.copy()
buffered['geometry'] = gdf.geometry.buffer(100)
# 4. Export results
gdf.to_file("results.gpkg", layer='original')
buffered.to_file("results.gpkg", layer='buffered')
空间连接与聚合
# Join points to polygons
points_in_polygons = gpd.sjoin(points_gdf, polygons_gdf, predicate='within')
# Aggregate by polygon (named aggregation: total value and number of points)
aggregated = points_in_polygons.groupby('index_right').agg(
value_sum=('value', 'sum'),
n_points=('value', 'size'),
)
# Merge back to polygons
result = polygons_gdf.merge(aggregated, left_index=True, right_index=True)
多源数据集成
# Read from different sources
roads = gpd.read_file("roads.shp")
buildings = gpd.read_file("buildings.geojson")
parcels = gpd.read_postgis("SELECT * FROM parcels", con=engine, geom_col='geom')
# Ensure matching CRS
buildings = buildings.to_crs(roads.crs)
parcels = parcels.to_crs(roads.crs)
# Perform spatial operations
buildings_near_roads = buildings[buildings.geometry.distance(roads.union_all()) < 50]
性能提示
- 使用空间索引:GeoPandas 会为大多数操作自动创建空间索引
- 读取时筛选:使用
bbox、mask或where参数,仅加载所需数据 - 使用 Arrow 进行 I/O:添加
use_arrow=True,读取/写入速度可提升 2-4 倍 - 简化几何:精度要求不高时,使用
.simplify()降低复杂度 - 批量操作:矢量化操作远快于逐行迭代
- 使用合适的 CRS:面积计算使用等面积 CRS,距离/缓冲区计算使用本地 UTM,存储使用地理坐标系
最佳实践
- 进行空间操作前,务必检查 CRS
- 测量时使用合适的投影 CRS——面积计算使用等积投影(例如 EPSG:6933 或区域性的 Albers 投影),距离计算使用
estimate_utm_crs();切勿使用 EPSG:3857 - 进行空间连接或叠加前,确保 CRS 一致
- 操作前使用
.is_valid验证几何图形 - 修改几何列时使用
.copy(),以避免副作用 - 为分析进行简化时,保留拓扑结构
- 在现代工作流中使用 GeoPackage 格式(优于 Shapefile)
- 在 sjoin_nearest 中设置 max_distance,以提升性能
AlterLab 学术技能套件的一部分。