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)

有用的话给个赞和关注~

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值