pyhton 创建shp文件并投影,批量进行坐标转换与添加投影信息,合并shp文件,分割shp文件

这篇博客介绍了如何使用Python进行地理数据分析,包括通过arcgis获取和设置投影信息,将地理坐标系转换为投影坐标系,以及批量处理多个文件的投影变换。示例中展示了创建点数据、存储地理位置、合并不同图层,并根据X坐标分割数据的过程。
摘要由CSDN通过智能技术生成

代码如下,注释是经过百度翻译的中文。这是我的python地理分析课程作业之一。

如何获取投影信息,可以通过arcgis输出投影信息,更换投影信息的时候主要也要进行坐标转换,尤其从地理坐标系转到投影坐标系。

import shapefile
import utm


# Add projection information, the spatial coordinate system is wgs-1984-mercator projection CGS
def projection(filename, ind):
    with open(filename, 'w') as ww:
        if ind == 1:
            ww.write('GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],'
                     'PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]')
        if ind == 2:
            ww.write('PROJCS["WGS_1984_UTM_Zone_50N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",'
                     '6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],'
                     'PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER['
                     '"False_Northing",0.0],PARAMETER["Central_Meridian",117.0],PARAMETER["Scale_Factor",0.9996],'
                     'PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]')
    with open(filename.replace(".prj", ".cpg"), 'w') as ww1:
        ww1.write("UTF-8")


# Create a series of points using pyshp library. Only geometric figures of the same type can be merged.
# Shapetype=1 represents points
with shapefile.Writer("./data/school", shapeType=1, encoding='UTF-8') as w:
    # Define two attributes, namely the name and number of the point
    w.field('name', 'C', 50, 0)
    w.field('id', 'N', 10, 0)
    # Storing geometric locations and attributes
    w.point(117.239252, 31.510307)
    w.record('合肥工业大学', 152453)
    w.point(117.169232, 31.550335)
    w.record('安徽大学', 312854)
    w.point(117.288322, 31.821104)
    w.record('三联学院', 323664)
    projection("./data/school.prj", 1)

with shapefile.Writer("./data/hospital", shapeType=1, encoding='UTF-8') as w:
    w.field('name', 'C', 50, 0)
    w.field('id', 'N', 10, 0)
    w.point(117.262517, 31.841903)
    w.record('安徽省人民医院', 135978)
    w.point(117.260985, 31.861645)
    w.record('安徽省第二医院', 132043)
    w.point(117.269712, 31.863475)
    w.record('工大附属医院', 343124)
    projection("./data/hospital.prj", 1)

with shapefile.Writer("./data/market", shapeType=1, encoding='UTF-8') as w:
    w.field('name', 'C', 50, 0)
    w.field('id', 'N', 10, 0)
    w.point(117.244368, 31.846191)
    w.record('万达购物广场', 136852)
    w.point(117.297992, 31.836775)
    w.record('家乐购', 246951)
    w.point(117.206234, 31.870627)
    w.record('直达便利店', 133456)
    projection("./data/market.prj", 1)

# Perform batch projection
files = ["./data/hospital", "./data/school", "./data/market"]
for file in files:
    r = shapefile.Reader(file)
    w = shapefile.Writer(file + 'UTM-50N', encoding='UTF-8')
    w.fields = r.fields
    for i in r.iterShapeRecords():
        lon, lat = i.shape.points[0]
        y, x, zone, band = utm.from_latlon(lat, lon)
        w.point(x, y)
        w.record(*i.record)
    w.close()
    projection(file + 'UTM-50N' + '.prj', 2)

# Merge three point layers into city layer
with shapefile.Writer("./city", shapeType=1, encoding='UTF-8') as w:
    for m in files:
        r = shapefile.Reader(m + 'UTM-50N')
        w.fields = r.fields
        for i in r.iterShapeRecords():
            w.shape(i.shape)
            w.record(*i.record)
    projection('city.prj', 2)

# Divide the city layer and save points with X coordinate greater than 4080694
with shapefile.Writer('./city_spilt', encoding='UTF-8') as w:
    r = shapefile.Reader('city')
    w.fields = r.fields
    for i in r.iterShapeRecords():
        if i.shape.points[0][0] > 4080694:
            w.shape(i.shape)
            w.record(*i.record)
    projection('./city_spilt.prj', 2)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果您想使用Python批量将不是矩形的shp文件裁剪nc文件的范围,您可以使用以下步骤: 1. 使用Python的GDAL库读取shp文件,选择您要使用的多边形范围并将其裁剪。 ```python from osgeo import ogr, gdal # 打开shp文件 driver = ogr.GetDriverByName('ESRI Shapefile') dataSource = driver.Open('input.shp', 0) layer = dataSource.GetLayer() # 选择要裁剪的多边形 layer.SetAttributeFilter("field='value'") # 根据属性字段筛选 geom = layer.GetNextFeature().GetGeometryRef() # 裁剪 ds = gdal.Warp('output_mask.nc', dataSource, format='netCDF', cutlineDSName='', cutlineLayer=layer.GetName(), cutlineWhere="field='value'", cropToCutline=True) ``` 2. 使用软件(如cdo、nco)将新的nc格式的mask文件转换为二进制掩码文件。以下是一个nco命令的示例: ``` ncrename -d x,lon -d y,lat -v Band1,mask -v x,lon -v y,lat mask.nc ncap2 -s "mask=mask>0.5?1:0" mask.nc mask_binary.nc ``` 3. 使用Python的xarray库打开nc文件和新的nc格式的mask二进制掩码文件,并将它们合并为一个新的nc文件。 ```python import xarray as xr # 打开nc文件和mask二进制掩码文件 data = xr.open_dataset('input.nc') mask = xr.open_dataset('mask_binary.nc') # 将掩码应用到数据 data_masked = data.where(mask.mask==1) # 保存新的nc文件 data_masked.to_netcdf('output.nc') ``` 4. 使用循环来批量处理多个shp和nc文件。 ```python import os # 循环处理多个shp和nc文件 shp_files = ['file1.shp', 'file2.shp', 'file3.shp'] nc_files = ['file1.nc', 'file2.nc', 'file3.nc'] for i in range(len(shp_files)): # 裁剪 ds = gdal.Warp('mask.nc', shp_files[i], format='netCDF', cutlineDSName='', cutlineLayer=layer.GetName(), cutlineWhere="field='value'", cropToCutline=True) # 转换为二进制掩码文件 os.system('ncrename -d x,lon -d y,lat -v Band1,mask -v x,lon -v y,lat mask.nc') os.system('ncap2 -s "mask=mask>0.5?1:0" mask.nc mask_binary.nc') # 合并数据和掩码 data = xr.open_dataset(nc_files[i]) mask = xr.open_dataset('mask_binary.nc') data_masked = data.where(mask.mask==1) data_masked.to_netcdf('output_{}.nc'.format(i+1)) ``` 这样,您就可以使用Python批量将不是矩形的shp文件裁剪nc文件的范围了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值