AGS Python開發(fā)-ArcPy基礎(chǔ)功能開發(fā)


1、數(shù)據(jù)列表與參數(shù)設(shè)置

1.1、數(shù)據(jù)列表與遍歷

(1)返回?cái)?shù)據(jù)列表的函數(shù)

ArcPy中提供了大量可以返回?cái)?shù)據(jù)列表的函數(shù),可以方便后續(xù)遍歷數(shù)據(jù)。

函數(shù)名 說明
ListFields(dataset, wild_card, field_type) 返回?cái)?shù)據(jù)集中的字段列表
ListIndexes(dataset, wild_card) 返回?cái)?shù)據(jù)集中屬性索引列表
ListDatasets(wild_card, feature_type) 返回工作空間中的數(shù)據(jù)集
ListFeatureClasses(wild_card, feature_type, feature_dataset) 返回工作空間中的要素類
ListFiles(wild_card) 返回工作空間中的文件
ListRasters(wild_card,raster_type) 返回工作空間中的柵格數(shù)據(jù)
ListTables(wild_card, table_type) 返回工作空間中的表
ListWorkspaces(wild_card, workspace_type) 返回工作空間列表
ListVersions(sde_workspace) 返回版本列表

參數(shù)說明:wild_card:字符串參數(shù),用于過濾,支持通配符。

arcpy.env.workspace="c:/map.gdb"
fcs = arcpy.ListFeatureClasses("*","polygon")
fcCount = len(fcs)

(2)遍歷數(shù)據(jù)列表
使用循環(huán)語句遍歷。

dirPath = "D:/mapdata/test/worldshp"
arcpy.env.workspace=dirPath
ftClasses = arcpy.ListFeatureClasses()
for ftClass in ftClasses:
    print(ftClass)

(3)返回工具、工具箱和環(huán)境設(shè)置列表的函數(shù)
工具列表:arcpy.ListTools({wildcard})
環(huán)境設(shè)置列表:arcpy.ListEnvironments({wildcard})
工具箱列表:arcpy.ListToolboxes({wildcard})

(4)遍歷子目錄
ArcPy中遍歷目錄以及子目錄,需要使用arcpy.da.Walk函數(shù)。Walk(top, topdown, onerror, followlinks, datatype, type)返回結(jié)果是一個(gè)元組(dirpath, dirnames,filenames)

workspace = "D:/mapdata/test/china/"
for dirpath,dirnames,filenames in arcpy.da.Walk(workspace,datatype="FeatureClass",type="Point"):
    print(dirpath,type(dirpath))
    print(dirnames)
    print(filenames)

1.2、多值參數(shù)設(shè)置

對(duì)于接收列表類型參數(shù)的地理處理工具,列表參數(shù)的設(shè)置有三種方式:列表、字符串、ValueTable。
(1)列表

fields=["AREA","PERIMETER","ORIG_FID"]
arcpy.DeleteField_management("citiesbuffer",fields)

(2)字符串
將多個(gè)值以逗號(hào)隔開。

strFlds="BUFF_DIST;ADCLASS"
arcpy.DeleteField_management("citiesbuffer",strFlds)

(3)ValueTable

vt = arcpy.ValueTable()
vt.addRow("PINYIN")
vt.addRow("ADCODE93")
arcpy.DeleteField_management("citiesbuffer",vt)

1.3、字段映射

在執(zhí)行合并或追加等地理處理工具時(shí),需要將輸入源的字段映射到輸出數(shù)據(jù)的字段上。對(duì)于這種字段映射關(guān)系的定義使用Fieldmappings和Fieldmap對(duì)象,F(xiàn)ieldmappings由Fieldmap組成,F(xiàn)ieldmap定義了多個(gè)輸入字段與一個(gè)輸出字段的映射關(guān)系。
(1)定義Fieldmap對(duì)象
方式1:創(chuàng)建空的Fieldmap對(duì)象

fldmap = arcpy.Fieldmap()

方式2:從Fieldmappings中創(chuàng)建

fc1 = "C:/data/CityData.gdb/Blocks1"
fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(fc1)
fldmap = fieldmappings.getFieldMap(fieldmappings.findFieldMapIndex("POP2000"))

(2)設(shè)置輸入輸出字段映射關(guān)系
如圖層fc1的字段name,fc2的字段str,映射到輸出圖層的strname字段。

fldmap.addInputField(fc1, "name")
fldmap.addInputField(fc2, "str")
fldmap_outField = fldmap.outputField
fldmap_outField.name =  "strname"
fldmap.outputField = fldmap_outField

(3)定義輸入圖層與輸出圖層映射關(guān)系

fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(fc1)
fieldmappings.addTable(fc2)
fieldmappings.addFieldMap(fldmap)

(4)執(zhí)行分析

vTab = arcpy.ValueTable()
vTab.addRow(fc1)
vTab.addRow(fc2)
outfc = "C:/data/CityData.gdb/AllBlocks"
arcpy.Merge_management(vTab, outfc, fieldmappings)

1.3、驗(yàn)證表和字段名稱

在操作地理數(shù)據(jù)庫(kù)中的要素類以及字段信息時(shí),需要注意是否違反數(shù)據(jù)庫(kù)的命名規(guī)范,如表名是否重復(fù),是否包含非法字符等。ArcPy提供了如下函數(shù)供檢驗(yàn)正確與否:
arcpy.ValidateTableName(name,{workspace}) #獲取表名和工作空間路徑并為該工作空間返回一個(gè)有效表名
arcpy.ValidateFieldName(name, {workspace}) #獲取字符串(字段名)和工作空間路徑,并基于輸出地理數(shù)據(jù)庫(kù)中的名稱限制返回一個(gè)有效字段名

arcpy.env.workspace="D:/mapdata/test/worldshp"
ftClasses = arcpy.ListFeatureClasses()
for fc in ftClasses:
    outputFt = arcpy.ValidateTableName(fc)
    print(outputFt)

2、訪問地理數(shù)據(jù)

2.1、檢查數(shù)據(jù)是否存在

Exists(dataset)函數(shù)用于檢查數(shù)據(jù)是否存在。
(1)檢查GDB中的圖層是否存在

arcpy.env.workspace = "d:/St_Johns/data.gdb"
fc = "roads"
if arcpy.Exists(fc):
    print(u"存在")

(2)檢查SDE中的圖層是否存在

arcpy.env.workspace = "Database Connections/Bluestar.sde"
fc = "ORASPATIAL.Rivers"
if arcpy.Exists(fc): 
    print(u"存在")

2.2、讀取數(shù)據(jù)的屬性信息

Describe函數(shù)用于讀取數(shù)據(jù)的屬性信息。

ftDesc = arcpy.Describe(ftClass)
print(ftDesc.shapeType)
print(ftDesc.spatialReference)

2.3、讀取數(shù)據(jù)的字段信息

(1)從Describe()中獲取

ftDesc = arcpy.Describe(ftClass)
fields = ftDesc.fields

(2)使用ListFields()獲取

fields = arcpy.ListFields(ftClass)

2.4、空間參考

(1)讀取空間參考

ftDesc = arcpy.Describe(ftClass)
sr = ftDesc.spatialReference

(2)創(chuàng)建空間參考
方式1(投影文件):sr = arcpy.SpatialReference("c:/prj/NAD 1983.prj")
方式2(坐標(biāo)系名稱):sr = arcpy.SpatialReference("GCS_China_Geodetic_Coordinate_System_2000")
方式3(wkid):sr = arcpy.SpatialReference(4490)

2.5、訪問要素集和記錄集

FeatureSet要素集對(duì)應(yīng)要素類,RecordSet記錄集對(duì)應(yīng)表。兩者操作方式一樣。
(1)從要素類中讀取數(shù)據(jù)集
方式1:

ft_set = arcpy.FeatureSet()
ft_set.load("c:/map/roads.shp")

方式2:

ft_set = arcpy.FeatureSet("c:/map/roads.shp")

(2)從Result對(duì)象中獲取數(shù)據(jù)集

result = arcpy.BufferPoints_servertools(in_featureset, "5 feet")
out_featureset = result[0]

或者out_featureset = result.getOutput(0)
(3)保存要素集

out_featureset.save("c:/temp/base.gdb/towers_buffer")

3、游標(biāo)

游標(biāo)用于增、刪、查、改地理數(shù)據(jù)。ArcPy中提供的游標(biāo)有三種:查詢游標(biāo)、插入游標(biāo)、更新游標(biāo)。

游標(biāo)對(duì)象 游標(biāo)對(duì)象的方法 說明
arcpy.da.SearchCursor next 檢索下一行
reset 將游標(biāo)重置到起始位置
arcpy.da.InsertCursor insertRow 插入一行
arcpy.da.UpdateCursor updateRow 更新當(dāng)前行
deleteRow 刪除當(dāng)前行
reset 將游標(biāo)重置到起始位置
next 檢索下一行

3.1、查詢游標(biāo)SearchCursor

(1)迭代游標(biāo)
方式1:for語句(也可以使用while語句結(jié)合next()方法迭代)

cursor = arcpy.da.SearchCursor(fc, ['fieldA', 'fieldB'])
for row in cursor:
    print(row)
del row
del cursor

方式2:with語句

with arcpy.da.SearchCursor(fc, ['fieldA', 'fieldB']) as cursor:
    for row in cursor:
        print(row)

(2)游標(biāo)重置
游標(biāo)只支持向前導(dǎo)航,如果需要重新導(dǎo)航,需要調(diào)用reset方法重置。
(3)過濾查詢
方式1:where條件查詢。過濾條件建議寫在三重引號(hào)中。

fc = "D:/St_Johns/data.gdb/roads"
cursor = arcpy.da.SearchCursor(fc, ("roadclass", "name"), """"roadclass" = 2""")
for row in cursor:
    print(row[1])
del row
del cursor

ArcGIS中對(duì)字段名的引用因數(shù)據(jù)源不同而不同,文件GDB和shape引用字段使用雙引號(hào),SDE不使用任何符號(hào)。為避免麻煩,使用AddFieldDelimiters函數(shù)處理。

fc = "D:/St_Johns/data.gdb/roads"
fieldname = "roadclass"
whereclause = """{} = 2""".format(arcpy.AddFieldDelimiters(fc, fieldname))
cursor = arcpy.da.SearchCursor(fc, ("roadclass", "name"), whereclause)
for row in cursor:
    # Print the name of the residential road
    print(row[1])
del row
del cursor

方式2:額外條件查詢。額外條件包括:前綴條件(None、DISTINCT、TOP),后綴條件(None 、ORDER BY、GROUP BY)

cities = "D:/mapdata/test/worldshp/cities.shp"
flds = "CNTRY_NAME"
cursor = arcpy.da.SearchCursor(cities,flds,sql_clause=(None,"ORDER BY "+flds))
for row in cursor:
    print(row)
del row
del cursor

3.2、插入游標(biāo)InsertCursor

(1)插入新數(shù)據(jù)

cursor = arcpy.da.InsertCursor("c:/base/data.gdb/roads_lut",  ["roadID", "distance"])
for i in range(0,25):
    cursor.insertRow([i, 100])
del cursor

3.3、更新游標(biāo)UpdateCursor

更新游標(biāo)支持?jǐn)?shù)據(jù)更新和刪除。
(1)更新數(shù)據(jù)

with arcpy.da.UpdateCursor("c:/base/data.gdb/roads", ["roadtype", "distance"]) as cursor:
    for row in cursor:
        row[1] = row[0] * 100
        #或者使用
        #row[1].setValue("distance", row[0].getValue("roadtype") * 100)
        cursor.updateRow(row)

(2)刪除數(shù)據(jù)

with arcpy.da.UpdateCursor("c:/base/data.gdb/roads",  ["roadtype"]) as cursor:
    for row in cursor:
        if row[0] == 4:
            cursor.deleteRow()

3.4、Cursor對(duì)象與Row對(duì)象

查詢游標(biāo)、插入游標(biāo)、更新游標(biāo)返回的結(jié)果都是Cursor對(duì)象,它代表的是數(shù)據(jù)列表,由Row對(duì)象組成,Row對(duì)應(yīng)是表中的一行記錄。
(1)Cursor對(duì)象的方法

方法 說明
deleteRow(row) 刪除表中的一行
insertRow(row) 向表插入一行
newRow() 創(chuàng)建空行
next() 檢索下一行
reset() 重置索引到起始位置
updateRow(row) 更新一行
import datetime
import arcpy
 
cursor = arcpy.InsertCursor("c:/base/data.gdb/roads_maint")
for i in range(1000, 1025):
    row = cursor.newRow()
    row.setValue('rowid', i)
    row.setValue('distance', 100)
    row.setValue('CFCC', 'A10')
    row.setValue('LastInsp', datetime.datetime.now())
    cursor.insertRow(row)
del cursor, row

(2)Row對(duì)象的方法

方法 說明
getValue(field_name) 獲取字段值
isNull(field_name) 字段值是否為空
setNull(field_name) 將字段值設(shè)置為空
setValue(field_name,value) 設(shè)置字段值

除了使用get方法讀取字段值外,Row對(duì)象還支持直接訪問字段名的方式獲取值,如:row.NAME
(3)Cursor對(duì)象和Row對(duì)象使用注意事項(xiàng)
Cursor對(duì)象和Row對(duì)象使用完成,需要清除,如del row,cursor

3.5、游標(biāo)與鎖定

查詢游標(biāo)使用的是共享鎖,插入游標(biāo)和更新游標(biāo)使用的是排它鎖。使用排它鎖時(shí),會(huì)阻止其他應(yīng)用程序訪問數(shù)據(jù)集。游標(biāo)釋放方式:

  1. 在with語句中使用游標(biāo),會(huì)自動(dòng)釋放鎖。
  2. 調(diào)用游標(biāo)的reset()
  3. 游標(biāo)調(diào)用完成
  4. del語句刪除游標(biāo)
cur = None
try:
    cur = arcpy.da.InsertCursor(outFC, ["SHAPE@XY"])
    xy = (5997594.4753, 2069901.75682)
    cursor.insertRow([xy])
except Exception as e:
   print(e)
finally:
    if cur:
        del cur

3.6、讀寫B(tài)LOB字段

在 Python 中,BLOB 字段可接受字符串 bytearray 和 memoryviews。當(dāng)讀取 BLOB 字段時(shí),返回 memoryview 對(duì)象。
(1)寫B(tài)LOB

data = open("c:/images/image1.png", "rb").read()
ic = arcpy.da.InsertCursor("c:/data/fgdb.gdb/fc", ['imageblob'])
ic.insertRow([data])

(2)讀BLOB

sc = arcpy.da.SearchCursor("c:/data/fgdb.gdb/fc", ["imageblob"])
memview = sc.next()[0]
open("c:/images/image1_copy.png", "wb").write(memview.tobytes())

3.7、令牌

令牌是字段的一種快捷訪問方式。常用令牌:
ObjectID字段的令牌:OID@
shape字段的令牌:SHAPE@
要素質(zhì)心的令牌:SHAPE@XY
X、Y坐標(biāo)的令牌:SHAPE@XSHAPE@Y
坐標(biāo)JSON字符串的令牌:SHAPE@JSON
面積和長(zhǎng)度的令牌:SHAPE@AREASHAPE@LENGTH
示例:

for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]):
     print("Feature {}:".format(row[0]))
    for pnt in row[1]:
        print("{}, {}".format(pnt.X, pnt.Y))

4、空間幾何類型

ArcPy中提供的與幾何類型相關(guān)的對(duì)象有:GeometryPointMultiPointPointGeometryPolylinePolygonExtent。其中PointExtent不算幾何類型,它們無空間參考信息。

4.1、Point

Point是非幾何對(duì)象,常配合游標(biāo)使用。

point = arcpy.Point(5997577.46097, 2069905.81145)

4.2.、PointGeometry

point = arcpy.Point(25282, 43770)
ptGeometry = arcpy.PointGeometry(point)

4.3、Polyline

array = arcpy.Array([arcpy.Point(5997611.48964, 2069897.7022),arcpy.Point(5997577.46097, 2069905.81145)])
polyline = arcpy.Polyline(array)

4.4、Polygon

array = arcpy.Array([arcpy.Point(1, 2),arcpy.Point(2, 4), arcpy.Point(3, 7)])
polygon = arcpy.Polygon(array)

array中的坐標(biāo)不需要閉合。

4.5、Extent

記錄矩形范圍的最大最小XY等信息。

xmin = 12
xmax = 24
ymin = 8
ymax = 30
extent = arcpy.Extent(xmin,ymin,xmax,ymax)

4.6、與游標(biāo)結(jié)合使用

fc = "c:/data/gdb.gdb/roads"
cursor = arcpy.da.InsertCursor(fc, ["SHAPE@"])
array = arcpy.Array([arcpy.Point(5997611.48964, 2069897.7022), arcpy.Point(5997577.46097, 2069905.81145)])
polyline = arcpy.Polyline(array)
cursor.insertRow([polyline])

4.7、與地理處理工具結(jié)合使用

(1)作為輸入幾何參數(shù)
自定義構(gòu)建幾何對(duì)象,作為地理處理工具的參數(shù)。

coordinates = [ [2365000, 7355000],[2365000, 7455000], [2465000, 7455000], [2465000, 7355000]]
array = arcpy.Array([arcpy.Point(x, y) for x, y in coordinates])
boundary = arcpy.Polygon(array, arcpy.SpatialReference(2953))
result = arcpy.Clip_analysis('c:/data/rivers.shp', boundary, 'c:/data/rivers_clipped.shp')

(2)作為輸出幾何對(duì)象
將地理處理工具的輸出設(shè)置為空幾何對(duì)象,可以用來輸出幾何對(duì)象列表。

geometries = arcpy.CopyFeatures_management('c:/temp/outlines.shp', arcpy.Geometry())
length = sum([g.length for g in geometries])
print('Total length: {}'.format(length))

4.8、拓?fù)浜蛶缀尾僮?/h2>

每個(gè)幾何對(duì)象中都提供了拓?fù)浜蛶缀蜗嚓P(guān)的操作,如:buffer(distance)clip(envelope)crosses(second_geometry)intersect(other, dimension)等等。

5、arcpy.mapping地圖制圖模塊

地圖制圖模塊提供了管理mxd文檔和圖層,圖層渲染、地圖打印輸出、地圖服務(wù)發(fā)布等功能。
(1)訪問地圖文檔
方式1:訪問當(dāng)前地圖文檔

mxd = arcpy.mapping.MapDocument("CURRENT")

方式2:訪問指定路徑的地圖文檔

mxd = arcpy.mapping.MapDocument("C:/Project/Watersheds.mxd")

(2)列表函數(shù)
ListDataFrames:返回文檔中的圖層框DataFrame對(duì)象列表
ListLayers:返回地圖圖層Layer對(duì)象列表,Layer對(duì)應(yīng)的是lyr文件。
ListLayoutEelements:返回布局元素列表
ListTableViews:返回獨(dú)立表TableView對(duì)象列表
ListStyleItems:返回符號(hào)SytleItem對(duì)象列表

mxd = arcpy.mapping.MapDocument("CURRENT")
riverLyr = arcpy.mapping.ListLayers(mxd, "Rivers")[0]
titleTxt = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "title")[0]

(3)數(shù)據(jù)源修復(fù)

mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
mxd.findAndReplaceWorkspacePaths(r"C:\Project\Data", r"C:\Project\Data2")
mxd.saveACopy(r"C:\Project\Project2.mxd")
del mxd

(4)圖層顯示信息設(shè)置
如:打開標(biāo)注和設(shè)置透明度。

mxd = arcpy.mapping.MapDocument(r"c:\mapdata\chinamap\china.mxd")
dataFrame = arcpy.mapping.ListDataFrames(mxd, u"圖層")[0]
 
layer = arcpy.mapping.ListLayers(mxd, "", dataFrame)[0]
layer.showLabels = True
layer.labelClasses[0].expression = '[CITY NAME] +"-"+[CNTRY NAME]'
layer.transparency = 50
mxd.save()
del mxd

(5)地圖文檔輸出

arcpy.mapping.ExportToPDF(mxd, r"C:\Project\map.pdf")

詳情參考:http://desktop.arcgis.com/zh-cn/arcmap/latest/analyze/arcpy-mapping/exportreport.htm

6、SDE中執(zhí)行SQL操作

arcpy.ArcSDESQLExecute對(duì)象提供了直接使用SQL語句操作地理數(shù)據(jù)庫(kù)的方法。支持的SQL語句包括:SELECT、INSERT、UPDATE、DELETE。
使用SQL操作SDE的注意事項(xiàng)如下:

  1. 版本化的數(shù)據(jù)只能通過版本化視圖來使用SQL。非版本化的數(shù)據(jù)無此限制。
  2. 使用數(shù)據(jù)庫(kù)原生空間類型構(gòu)建的地理數(shù)據(jù)庫(kù),可以使用數(shù)據(jù)庫(kù)本身的空間SQL語句。

詳情參考:http://desktop.arcgis.com/zh-cn/arcmap/latest/analyze/python/executing-sql-using-an-egdb-connection.htm

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容