【Python基础绘图】Geopandas矢量化txt点数据为shp数据

【Python基础绘图】Geopandas矢量化txt点数据为shp数据

在这里插入图片描述

01 引言:

Python Geopandas轻松读取txt点数据进行矢量化并保存为shp格式,相较于gdal ogr相对更加便捷。现记录在此分享给更多有需要的同学。

02 txt数据如下:

【Python基础绘图】Geopandas矢量化txt点数据为shp数据_第1张图片

03 代码如下:

# -*- encoding: utf-8 -*-
'''
@File    :   read shp.py
@Time    :   2022/06/15 20:07:34
@Author  :   HMX 
@Version :   1.0
@Contact :   [email protected]
'''

# here put the import lib
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from  cartopy.mpl.ticker import LatitudeFormatter,LongitudeFormatter
import time



def txt2shp(txtpath,shppath,lon,lat):    
    df = pd.read_csv(txtpath,header=0)
    print(df)
    gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[lon], df[lat])
    ,crs = "EPSG:4326")
    ds = gpd.read_file(r'E:\Project\CHINA\shp\cnshp\china.shp')
    clipgdf = gpd.clip(gdf,ds)
    clipgdf.to_file(shppath)
    return


if __name__ == '__main__':
    t1 = time.time()
    txtpath = r'D:\公众号\ATL08_V5.txt'
    shppath = r'D:\公众号\NO.22\ATL08out.shp'
    txt2shp(txtpath,shppath,'lon','lat')
    t2 = time.time()
    print('共计用时:{:.2f}s'.format(t2-t1))

04 读取可视化:

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from  cartopy.mpl.ticker import LatitudeFormatter,LongitudeFormatter
from cnmaps import get_adm_maps
import numpy as np
import time


t1 = time.time()
shppath = r'D:\公众号\NO.22\ATL08out.shp'
gdf = gpd.read_file(shppath)
print(gdf)
proj = ccrs.PlateCarree()
fig,ax = plt.subplots(figsize=(4,3),subplot_kw={'projection':proj})
region = [71, 137, 1, 56]
ax.set_extent(region, crs=proj)
china, sourth_sea = get_adm_maps(level='国', only_polygon=True)
ax.add_geometries(china, crs=ccrs.PlateCarree(), edgecolor='k', facecolor='none')
ax.add_geometries(sourth_sea, crs=ccrs.PlateCarree(), edgecolor='k')
ax.add_feature(cfeature.COASTLINE.with_scale('10m'))
# ax.stock_img()
ax.imshow(plt.imread(r'E:\Project\World\HYP_LR_SR_OB_DR\HYP_LR_SR_OB_DR.tif'), origin='upper', transform=ccrs.PlateCarree(), extent=[-180, 180, -90, 90])
ax.set_xticks(np.arange(region[0],region[1]+1,22), crs = proj)
ax.set_yticks(np.arange(region[2],region[3]+1,11), crs = proj)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.minorticks_on()
ax.scatter(gdf.lon,gdf.lat,c = gdf.h_mean_can, s = 1)
plt.tight_layout()
plt.savefig('txt2shp.png',dpi = 600)
plt.show()
t2 = time.time()
print('共计用时:{:.2f}s'.format(t2-t1))

05 可视化如下:

06 gis读取:

利用Arcgis pro 软件打开写好的shp,可以发现所有字段均写入成功,也可成功读取。
【Python基础绘图】Geopandas矢量化txt点数据为shp数据_第2张图片

​如果对你有帮助的话,请‘点赞’、‘收藏’,‘关注’,你们的支持是我更新的动力。
欢迎关注公众号【森气笔记】。

你可能感兴趣的:(python基础绘图,GIS,python,开发语言,计算机视觉)