python在GIS数据处理中扮演者很重要的角色。很多时候比我们使用Arcmap工具和二次开发方便很多。尤其是处理批量数据的时候 。
这些常用的类:https://www.cnblogs.com/alex-bn-lee/p/8256775.html
一些部分代码示例:
添加字段
import arcpy
import os
# 设置工作空间
arcpy.env.workspace = "E:\project\水务\坐标点\topo.gdb"
# 原始图层和字段名
output_feature_class = "triTriangle"
field_names = ["point_x1", "point_y1", "point_x2", "point_y2", "point_x3", "point_y3"]
# 为新图层添加字段
for field in field_names[1:]:
if field not in [f.name for f in arcpy.ListFields(output_feature_class)]:
arcpy.AddField_management(output_feature_class, field, "DOUBLE")
# 单个添加
arcpy.AddField_management(output_feature_class, "uniq_id1", "LONG")
arcpy.AddField_management(output_feature_class, "uniq_id2", "LONG")
arcpy.AddField_management(output_feature_class, "uniq_id3", "LONG")
相交
import arcpy
from arcpy import env
# 设置工作空间
arcpy.env.workspace = "E:\project\水务\坐标点\topo.gdb"
# 设置两个要相交的图层
layer1 = "triTriangle.shp"
layer2 = "cgcPoint (1).shp"
# 设置相交后的结果要素类名称
output_feature_class = "Intersection_Result"
# 执行相交分析
arcpy.Intersect_analysis([layer1, layer2], output_feature_class)
#如果你想要保留顶点,可以使用以下代码
# arcpy.Intersect_analysis([layer1, layer2], output_feature_class, "INCLUDE_ALL", "#", "Point")
print("相交操作完成。")
条件赋值:
import arcpy
from arcpy import env
# 设置工作空间
workspace = "C:/Users/P52S/Desktop/三角网测试"
env.workspace = workspace
# 输入的面要素图层
input_layer = "triPolygon.shp"
# 添加一个新的字段
arcpy.AddField_management(input_layer, "mergefield", "SHORT")
# 更新要素类
with arcpy.da.UpdateCursor(input_layer, ["fid", "mergefield"]) as cursor:
for row in cursor:
if row[0] < 100000:
row[1] = 1 # 设置你想要的值
elif row[0] >= 100000 and row[0] < 200000:
row[1] = 2 # 设置你想要的值
elif row[0] >= 200000 and row[0] < 300000:
row[1] = 3 # 设置你想要的值
elif row[0] >= 300000 and row[0] < 400000:
row[1] = 4 # 设置你想要的值
elif row[0] >= 400000 and row[0] < 500000:
row[1] = 5 # 设置你想要的值
elif row[0] >= 500000 and row[0] < 600000:
row[1] = 6 # 设置你想要的值
else:
row[1] = 7 # 设置你想要的值
cursor.updateRow(row)
融合
import arcpy
from arcpy import env
# 设置工作空间
workspace = "C:/Users/P52S/Desktop/三角网测试"
env.workspace = workspace
# 输入的面要素图层
input_layer = "triPolygon.shp"
# 输出图层
output_layer = "merged_layer.shp"
# 指定根据哪个字段进行融合
merge_field = "mergefield"
# 进行图层融合
arcpy.Dissolve_management(input_layer, output_layer, merge_field)
print("图层融合完成。")
裁剪
import arcpy
from arcpy import env
# 设置工作空间
env.workspace = "C:/Users/P52S/Desktop/三角网测试"
# 获取图层
clip_features = "merged_layer.shp" # 替换为你的裁剪图层名
input_features = "triPolygon.shp" # 替换为你的被裁剪图层名
# 遍历裁剪图层的每个面
count = 1
with arcpy.da.SearchCursor(clip_features, ["SHAPE@"]) as cursor:
for row in cursor:
clip_geometry = row[0]
# 为每个裁剪结果创建一个唯一的输出文件名
output_name = "triPolygon" + str(count) + ".shp"
# 执行裁剪操作
arcpy.Clip_analysis(input_features, clip_geometry, output_name)
count = count+1