CSV/txt转点shp python+gdal

2021/10/9 11:39:43

本文主要是介绍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)

有用的话给个赞和关注~



这篇关于CSV/txt转点shp python+gdal的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程