本文主要是介绍geopandas 导出shp文件的一种方法,解决报编码错误(中文列名的情况下),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
解决问题:
geopandas 导出shp文件报编码错误(中文标题的情况下),改成utf-8和gbk都不行,取代用pyhsp导出
使用方法:一共三步
第1步:导入包
import geopandas as gpd
import shapefile
from itertools import chain
from osgeo import osr
第2步:导入数据
city_map = gpd.read_file('d:/city.shp') #或者tab,geojson或者自己生成的gdf都可以
第3步:导出shp,不报编码错误
# 使用下面代码中的to_shp函数
to_shp(city_map ,
out_path='d:/city_new.shp',
encoding='gbk',
geometry_name='geometry')
完成
import geopandas as gpd
import shapefile
from itertools import chain
from osgeo import osrdef to_shp(self,gdf_data,out_path='d:/polygon.shp',encoding='gbk',geometry_name='geometry'):'''功能:将geopandas导入的gdf导出为shp格式文件,目前支持polygon,MultiPolygon,BaseMultipartGeometryPoint,MultiPoint,LineString,LinearRing,MultiLineString不支持 GeometryCollection主要解决geopandas导出shp文件中文乱码问题'''#将‘geometry’列放到最后gdf_data = gdf_data.reindex(columns=(gdf_data.columns.drop(geometry_name).insert(gdf_data.shape[1],geometry_name)))gdf_data = gpd.GeoDataFrame(gdf_data,crs="epsg:4326",geometry=geometry_name)w = shapefile.Writer(out_path,encoding='gbk')#列名传给shp的属性列名[w.field(x) for x in gdf_data.drop(columns=geometry_name).columns]#循环每一行数据判断类型整理成对应的列表写入wfor row in gdf_data.iterrows():geo = row[1]['geometry']if geo.type == 'MultiPolygon':#判断是否为MultiPolygon是就循环下exterior_z = []for data in geo:data_a = data.exteriorexterior_z.append([[list(x) for x in list(data_a.coords)]])for data_i in data.interiors:exterior_z.append([[list(x) for x in list(data_i.coords)]])exterior = list(chain(*exterior_z))w.poly(exterior)elif geo.type == 'Polygon':def to_co(ring):return [[list(x) for x in list(ring.coords)]]exterior = list(chain.from_iterable(map(to_co,[geo.exterior, *geo.interiors])))w.poly(exterior)elif geo.type == 'Point':exterior = (geo.x, geo.y)w.point(exterior)elif geo.type == 'MultiPoint':exterior = list(map(lambda x:[x.x,x.y],geo))w.multipoint(exterior)elif geo.type == 'LineString':exterior = [[list(x) for x in list(geo.coords)]]w.line(exterior)elif geo.type == 'LinearRing':exterior = [[list(x) for x in list(geo.coords[:-1])]]w.line(exterior)elif geo.type == 'MultiLineString':exterior = [[list(x) for x in list(x.coords)] for x in geo]w.linem(exterior)else:print('错误一行')print(geo.type)w.record(*[x for x in row[1][:-1]]) # 输出每一行的内容除了geometryw.close()# 设置投影,通过.prj文件设置,需要写入一个wkt字符串##gdal的GetProjection()返回的是wkt字符串,需要ImportFromWkt#projstr="""PROJCS["WGS_1984_UTM_zone_50N",proj = osr.SpatialReference()proj.ImportFromEPSG(4326)#或 proj.ImportFromProj4(proj4str)等其他的来源wkt = proj.ExportToWkt()#写出prj文件f = open(out_path.replace(".shp",".prj"), 'w')f.write('GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]')f.close()
这篇关于geopandas 导出shp文件的一种方法,解决报编码错误(中文列名的情况下)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!