栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

CSV/txt转点shp python+gdal

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

CSV/txt转点shp python+gdal

废话不说,直接上码 
from osgeo import ogr
import pandas as pd
from osgeo import osr


def csv2shp(csv_path, shp_path):
    # 解决中文字符问题
    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
    gdal.SetConfigOption("SHAPE_ENCODING", "")

    # 设置空间参考,4326代表WGS84
    SpatialReference = osr.SpatialReference()
    SpatialReference.importFromEPSG(4326)

    # 新建DataSource,Layer
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.CreateDataSource(shp_path)
    layer = data_source.CreateLayer('Point', SpatialReference, ogr.wkbPoint)

    # 读取csv文件
    csv_df = pd.read_csv(csv_path)
    # csv所有列名,即shp的字段名
    filed_names = list(csv_df)

    # layer添加上述字段
    for filed_name in filed_names:
        print(str(csv_df[filed_name].dtypes))
        if ("int" in str(csv_df[filed_name].dtypes)):
            field = ogr.FieldDefn(filed_name, ogr.OFTInteger)
            field.SetWidth(10)
        elif ("float" in str(csv_df[filed_name].dtypes)):
            field = ogr.FieldDefn(filed_name, ogr.OFTReal)
            field.SetWidth(10)
            field.SetPrecision(6)
        else:
            field = ogr.FieldDefn(filed_name, ogr.OFTString)
            field.SetWidth(10)
        layer.CreateField(field)

    # 从layer中读取相应的feature类型,并创建feature
    featureDefn = layer.GetLayerDefn()
    feature = ogr.Feature(featureDefn)

    # 设定几何形状
    point = ogr.Geometry(ogr.wkbPoint)

    # 循环输入字段属性值
    for i in range(len(csv_df)):
        for j in range(len(filed_names)):
            if ("int" in str(csv_df[filed_names[j]].dtypes)):
                feature.SetField(filed_names[j], int(csv_df.iloc[i, j]))
            elif ("float" in str(csv_df[filed_names[j]].dtypes)):
                feature.SetField(filed_names[j], float(csv_df.iloc[i, j]))
            else:
                feature.SetField(filed_names[j], str(csv_df.iloc[i, j]))

        # 设置几何信息部分
        # 利用经纬度创建点,X为经度,Y为纬度(我的数据第0列是纬度,第1列是经度)
        point.AddPoint(float(csv_df.iloc[i, 0]), float(csv_df.iloc[i, 1]))
        feature.SetGeometry(point)

        # 将feature写入layer
        layer.CreateFeature(feature)

    # 从内存中清除 ds,将数据写入磁盘中
    data_source.Destroy()


csv_path = 'csv路径'
shp_path = '.shp输出路径'
csv2shp(csv_path, shp_path)
有用的话给个赞和关注~
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307491.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号