工作中需要处理一些GIS数据,在 Python 中解析地理信息系统 (GIS) 的 Shapefile (.shp) 文件通常可以通过 geopandas
库来完成。geopandas
是基于 pandas
的一个扩展库,它支持地理空间数据的操作和分析。
下面是一个简单的示例,展示如何使用 geopandas
读取并解析一个 Shapefile 文件:
-
首先确保已经安装了
geopandas
:pip install geopandas
-
使用
geopandas
读取 Shapefile 或压缩的 zip 文件:
import geopandas as gpd
# 指定 Shapefile 的路径
file_path = './data/ne_10m_admin_0_countries.zip'
# 读取 Shapefile
data = gpd.read_file(file_path)
protected_lands_area = gpd.read_file('./data/10m_cultural/ne_10m_parks_and_protected_lands_area.shp')
# 显示数据的基本信息
print("Data columns:", data.columns)
print("Geometry type:", data.geometry.type)
# 显示数据的前几行
print(data.head())
Data columns: Index(['featurecla', 'scalerank', 'LABELRANK', 'SOVEREIGNT', 'SOV_A3',
'ADM0_DIF', 'LEVEL', 'TYPE', 'TLC', 'ADMIN',
...
'FCLASS_TR', 'FCLASS_ID', 'FCLASS_PL', 'FCLASS_GR', 'FCLASS_IT',
'FCLASS_NL', 'FCLASS_SE', 'FCLASS_BD', 'FCLASS_UA', 'geometry'],
dtype='object', length=169)
Geometry type: 0 MultiPolygon
1 MultiPolygon
2 MultiPolygon
3 Polygon
4 MultiPolygon
...
253 MultiPolygon
254 Polygon
255 Polygon
256 Polygon
257 Polygon
Length: 258, dtype: object
featurecla scalerank LABELRANK SOVEREIGNT SOV_A3 ADM0_DIF LEVEL \
0 Admin-0 country 0 2 Indonesia IDN 0 2
1 Admin-0 country 0 3 Malaysia MYS 0 2
2 Admin-0 country 0 2 Chile CHL 0 2
3 Admin-0 country 0 3 Bolivia BOL 0 2
4 Admin-0 country 0 2 Peru PER 0 2
TYPE TLC ADMIN ... FCLASS_TR FCLASS_ID FCLASS_PL \
0 Sovereign country 1 Indonesia ... None None None
1 Sovereign country 1 Malaysia ... None None None
2 Sovereign country 1 Chile ... None None None
3 Sovereign country 1 Bolivia ... None None None
4 Sovereign country 1 Peru ... None None None
FCLASS_GR FCLASS_IT FCLASS_NL FCLASS_SE FCLASS_BD FCLASS_UA \
0 None None None None None None
1 None None None None None None
2 None None None None None None
3 None None None None None None
4 None None None None None None
geometry
0 MULTIPOLYGON (((117.70361 4.16341, 117.70361 4...
1 MULTIPOLYGON (((117.70361 4.16341, 117.69711 4...
2 MULTIPOLYGON (((-69.51009 -17.50659, -69.50611...
3 POLYGON ((-69.51009 -17.50659, -69.51009 -17.5...
4 MULTIPOLYGON (((-69.51009 -17.50659, -69.63832...
[5 rows x 169 columns]
- 绘制地图
示例数据是全球地图和一些陆地保护区(美国的,红色区域),我们可以将两个数据叠加在一起绘制,代码如下:
import matplotlib.pyplot as plt
# 绘制地图
fig, ax = plt.subplots(1, 1)
data.plot(ax=ax)
protected_lands_area.plot(ax=ax, color='red')
plt.show()