GeoPandas是Python中用于地理空间数据处理的核心库,它扩展了Pandas的功能,使其能够处理带有几何信息的数据。本文将介绍GeoPandas的基本用法和常用空间分析操作。
一、安装与环境配置
首先需要安装GeoPandas及其依赖库:
pip install geopandas matplotlib descartes
二、读取空间数据
GeoPandas支持多种空间数据格式,包括Shapefile、GeoJSON、GPKG等。
import geopandas as gpd
# 读取Shapefile
gdf = gpd.read_file("data/cities.shp")
# 读取GeoJSON
gdf = gpd.read_file("data/cities.geojson")
# 查看数据结构
print(gdf.head())
print(gdf.crs)
三、空间数据基本操作
3.1 数据探索
# 查看几何类型
print(gdf.geometry.type)
# 计算面积
gdf["area"] = gdf.geometry.area
# 计算质心
gdf["centroid"] = gdf.geometry.centroid
# 边界框
bbox = gdf.geometry.total_bounds
3.2 空间索引
空间索引可以显著提高空间查询的效率。
# 创建空间索引
sindex = gdf.sindex
# 使用空间索引查询
possible_matches_index = list(sindex.intersection(bbox))
possible_matches = gdf.iloc[possible_matches_index]
四、常用空间分析
4.1 缓冲区分析
# 创建缓冲区
buffered = gdf.geometry.buffer(1000) # 1000米缓冲区
4.2 叠加分析
# 交集分析
intersection = gpd.overlay(gdf1, gdf2, how="intersection")
# 并集分析
union = gpd.overlay(gdf1, gdf2, how="union")
# 差集分析
difference = gpd.overlay(gdf1, gdf2, how="difference")
4.3 空间连接
# 空间连接
joined = gpd.sjoin(gdf_points, gdf_polygons, how="left", op="within")
五、数据可视化
import matplotlib.pyplot as plt
# 基础可视化
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(ax=ax, column="population", legend=True)
plt.title("城市人口分布图")
plt.show()
GeoPandas是Python空间分析的利器,掌握它可以大大提升地理数据处理的效率。后续我会分享更多高级分析技巧和实战案例。