geopandas
简介
基础使用
安装依赖
# setp1:
访问`https://www.lfd.uci.edu/~gohlke/pythonlibs/`
# setp2: 搜索GDAL
# 下载并安装 GDAL‑x.x.x-cpxx-cpxx-win_amd64.whl 的最新版
# cpxx 对应的是你python版本
GDAL‑3.4.3‑cp311‑cp311‑win_amd64.whl
# setp2: 搜索Fiona
# 下载并安装 Fiona‑x.x.x-cpxx-cpxx-win_amd64.whl 的最新版
# cpxx 对应的是你python版本
Fiona‑3.4.3‑cp311‑cp311‑win_amd64.whl
# 通过pip安装
pip install GDAL‑3.4.3‑cp311‑cp311‑win_amd64.whl
poetry run pip install GDAL‑3.4.3‑cp311‑cp311‑win_amd64.whl
PS poetry安装
如果使用poetry管理依赖,本地
# 剩余依赖
shapely pykrige
安装本体
pip install geopandas
使用示例
通过DataFrame创建shp文件
# 配置输出的文件名 xxx.shp
out_file = 'xxxx.shp'
csr = None # 设置坐标系
# 创建对应的基础数据对象
data={"x": xy[0], "y": xy[1], "z": z}
# 创建DataFrame
df = DataFrame(data)
# 保存为 shp 点文件
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.x, df.y), csr=csr)
gdf.to_file(out_file)
合并两个shp文件
ChatGPT编写
import geopandas as gpd
# 读取两个Shapefile文件
file1 = 'path/to/shapefile1.shp'
file2 = 'path/to/shapefile2.shp'
gdf1 = gpd.read_file(file1)
gdf2 = gpd.read_file(file2)
# 判断两个文件是否为点文件
is_point_file1 = gdf1.geometry.type.unique()[0] == 'Point'
is_point_file2 = gdf2.geometry.type.unique()[0] == 'Point'
if is_point_file1 and is_point_file2:
# 判断两个文件的点数是否一致
num_points_file1 = len(gdf1)
num_points_file2 = len(gdf2)
if num_points_file1 == num_points_file2:
# 合并字段
merged_gdf = gpd.GeoDataFrame(pd.concat([gdf1, gdf2], axis=1))
# 生成新的Shapefile
merged_file = 'path/to/merged_shapefile.shp'
merged_gdf.to_file(merged_file)
print("合并完成,生成新的Shapefile:", merged_file)
else:
print("两个Shapefile的点数不一致。")
else:
print("至少一个文件不是点文件。")