利用arcpy實現arcgis中欄位自動編號(pycharm匯入arcpy站點包,欄位建立、更新與寫值)
一、問題來源
今天看到群裡有一個小夥伴,要實現這樣的一個功能,來看一下他的提問:
問下各位大神,如果圖層裡面有2000個小班,我需要將這2000小班在屬性表裡面編號依次為1 2 3 4……1998 1999 2000該怎麼操作呢 。
於是下面有人說可以對欄位的FID操作,FID+1,或者編寫一個小工具。
二、Pycharm匯入arcpy站點包
於是這裡嘗試著用python寫一個工具。由於現在我是在新的電腦上開發,很多軟體是新安裝的,我這裡使用的pycharm,需要將arcpy站點包匯入到pycharm中,於是問題就來了。首先如下圖所示,在寫import arcpy找到不到站點包。於是網上找了相關資料,來解決這個問題。
試了多種方法,依舊如下圖所示,沒有將arcpy匯入到External Libraries。
於是後面在建立新的python工程時,選擇了Project interpreter下面有兩個選擇,可以用來建立虛擬環境,如果使用New environment using那麼必須勾選上inherit global site-packges,下面的Make available to all projects可以選擇性勾選,但建議大家最後一次性勾選,後面新建的工程就不用勾選了,然後在Location 設定相應的名字,以及Base interpreter中設定我們在安裝arcgis desktop中的python路徑。而如果選擇的是黃色框內,則直接選擇arcgis desktop的python路徑即可。
這樣新建的工程,我們在External Libraries中就可以看到arcpy站點包了,這個包將用於我們的工具開發
三、程式編寫
按照要求,我們只需要建立一個編號(BH)的欄位,然後讀取FID,再將FID+1,所獲得該值填入到BH欄位中,說白了就是更新一下欄位,就完事了。來看一下程式碼,是不是非常簡單,幾句話的事。
實現程式碼:
# coding:utf-8 import arcpy def excute(shapePath): arcpy.AddField_management(shapePath, "BH", "TEXT", field_length=25) with arcpy.da.UpdateCursor(shapePath, ["FID",'BH']) as cursor: for row in cursor: fid=row[0] row[1]=fid+1 cursor.updateRow(row) del cursor
打包程式碼:
# coding:gbk
import arcpy
from OrderByID import excute
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "自動編號(測繪科技)"
self.description = "自動編號(測繪科技)"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
shapePath = arcpy.Parameter(
displayName="需要修改的shapefile資料",
name="shapePath",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input"
)
params = [shapePath]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
shapePath = parameters[0].valueAsText
excute(shapePath)
return
最後做出工具如下圖所示。
將資料新增到選擇框,執行即可。
來看一下最終結果,下圖是處理之前的資料。
處理後的資料處理後的資料
至此,這個小功能就實現完了,當然也可以不用寫程式碼那麼麻煩,只不過這對於寫程式來說是一個不小鍛鍊。
更多內容,請關注公眾號