如何从GeoPandas DataFrame生成Shapefile,解决to_file输出为空问题
GeoPandas导出Shapefile异常问题解决方案
核心问题定位
- 代码遍历所有CSV文件时,每次导出均使用固定文件名
file.shp,后续CSV的导出结果会直接覆盖前序文件,若最后遍历到的CSV为空或无有效坐标数据,最终就会得到空Shapefile - ESRI Shapefile要求字段名长度不超过10个字符,若DataFrame中存在超长列名,会导致字段写入失败,甚至整个文件导出为空
- 经纬度列存在空值、无效值时,生成的Point几何对象非法,会导致导出无结果且无显性报错
修复后可直接运行的代码
import arcpy import pandas as pd import glob import geopandas as gpd from shapely.geometry import Point arcpy.env.overwriteOutput = True arcpy.env.workspace = r'F:\\GY539_Programming\\project_data' ws = arcpy.env.workspace files = glob.glob(ws + '/*.csv') for filename in files: df = pd.read_csv(filename, sep=',') # 过滤经纬度为空的无效行 df = df.dropna(subset=['Longitude', 'Latitude']) if df.empty: print(f"文件{filename}无有效坐标数据,跳过导出") continue # 截断超长字段名,适配Shapefile字段长度限制 df.columns = [col[:10] for col in df.columns] geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])] gdf = gpd.GeoDataFrame(df, crs='EPSG:4326', geometry=geometry) # 按CSV原名生成输出文件名,避免覆盖 output_shp = filename.replace('.csv', '.shp') gdf.to_file(output_shp, driver='ESRI Shapefile') print(f"导出成功:{output_shp},共写入{len(gdf)}条要素")
额外排查建议
- 导出前可打印
print(gdf.geometry.is_valid.value_counts()),确认所有几何对象合法 - 低版本fiona库会导致Shapefile驱动异常,可执行
pip install -U fiona geopandas升级依赖 - 存储路径、文件名避免包含中文、特殊符号,防止驱动识别路径失败
内容的提问来源于stack exchange,提问作者socode
相关产品推荐
相关产品推荐

