當前位置: 首頁>>代碼示例>>Python>>正文


Python arcpy.AddField_management方法代碼示例

本文整理匯總了Python中arcpy.AddField_management方法的典型用法代碼示例。如果您正苦於以下問題:Python arcpy.AddField_management方法的具體用法?Python arcpy.AddField_management怎麽用?Python arcpy.AddField_management使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在arcpy的用法示例。


在下文中一共展示了arcpy.AddField_management方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: generate_cls_boundary

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def generate_cls_boundary(cls_input,cntr_id_field,boundary_output,cpu_core):
    arcpy.env.parallelProcessingFactor=cpu_core
    arcpy.SetProgressorLabel('Generating Delaunay Triangle...')
    arrays=arcpy.da.FeatureClassToNumPyArray(cls_input,['SHAPE@XY',cntr_id_field])
   
    cid_field_type=[f.type for f in arcpy.Describe(cls_input).fields if f.name==cntr_id_field][0]
    delaunay=Delaunay(arrays['SHAPE@XY']).simplices.copy()
    arcpy.CreateFeatureclass_management('in_memory','boundary_temp','POLYGON',spatial_reference=arcpy.Describe(cls_input).spatialReference)
    fc=r'in_memory\boundary_temp'
    arcpy.AddField_management(fc,cntr_id_field,cid_field_type)
    cursor = arcpy.da.InsertCursor(fc, [cntr_id_field,"SHAPE@"])
    arcpy.SetProgressor("step", "Copying Delaunay Triangle to Temp Layer...",0, delaunay.shape[0], 1)
    for tri in delaunay:
        arcpy.SetProgressorPosition()
        cid=arrays[cntr_id_field][tri[0]]
        if cid == arrays[cntr_id_field][tri[1]] and cid == arrays[cntr_id_field][tri[2]]:
            cursor.insertRow([cid,arcpy.Polygon(arcpy.Array([arcpy.Point(*arrays['SHAPE@XY'][i]) for i in tri]))])
    arcpy.SetProgressor('default','Merging Delaunay Triangle...')
    if '64 bit' in sys.version:
        arcpy.PairwiseDissolve_analysis(fc,boundary_output,cntr_id_field)
    else:
        arcpy.Dissolve_management(fc,boundary_output,cntr_id_field)
    arcpy.Delete_management(fc)
    
    return 
開發者ID:lopp2005,項目名稱:HiSpatialCluster,代碼行數:27,代碼來源:section_cpu.py

示例2: calculateTimeField

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def calculateTimeField(self, out_table, start_datetime, time_interval):
        """Add & calculate TimeValue field: scripts adapted from TimeTools.pyt developed by N. Noman"""
        timeIndexFieldName = self.fields_oi[0]
        timeValueFieldName = self.fields_oi[3]
        #Add TimeValue field
        arcpy.AddField_management(out_table, timeValueFieldName, "DATE", "", "", "", timeValueFieldName, "NULLABLE")
        #Calculate TimeValue field
        expression = "CalcTimeValue(!" + timeIndexFieldName + "!, '" + start_datetime + "', " + time_interval + ")"
        codeBlock = """def CalcTimeValue(timestep, sdatestr, dt):
            if (":" in sdatestr):
                sdate = datetime.datetime.strptime(sdatestr, '%m/%d/%Y %I:%M:%S %p')
            else:
                sdate = datetime.datetime.strptime(sdatestr, '%m/%d/%Y')
            tv = sdate + datetime.timedelta(hours=(timestep - 1) * dt)
            return tv"""

        arcpy.AddMessage("Calculating " + timeValueFieldName + "...")
        arcpy.CalculateField_management(out_table, timeValueFieldName, expression, "PYTHON_9.3", codeBlock)

        return 
開發者ID:Esri,項目名稱:python-toolbox-for-rapid,代碼行數:22,代碼來源:CreateDischargeTable.py

示例3: create_feature_class

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def create_feature_class(out_path,
                         out_name,
                         geom_type,
                         wkid,
                         fields,
                         objectIdField):
    """ creates a feature class in a given gdb or folder """
    if arcpyFound == False:
        raise Exception("ArcPy is required to use this function")
    arcpy.env.overwriteOutput = True
    field_names = []
    fc =arcpy.CreateFeatureclass_management(out_path=out_path,
                                            out_name=out_name,
                                            geometry_type=lookUpGeometry(geom_type),
                                            spatial_reference=arcpy.SpatialReference(wkid))[0]
    for field in fields:
        if field['name'] != objectIdField:
            field_names.append(field['name'])
            arcpy.AddField_management(out_path + os.sep + out_name,
                                      field['name'],
                                      lookUpFieldType(field['type']))
    return fc, field_names
#---------------------------------------------------------------------- 
開發者ID:Esri,項目名稱:ArcREST,代碼行數:25,代碼來源:spatial.py

示例4: execute

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def execute(in_datasets, out_fc):
    # use gcs as output sr since all extents will fit in it
    out_sr = arcpy.SpatialReference("WGS 1984")

    in_datasets = in_datasets.split(";")

    arcpy.CreateFeatureclass_management(os.path.dirname(out_fc),
                                        os.path.basename(out_fc),
                                        "POLYGON",
                                        spatial_reference=out_sr)

    arcpy.AddField_management(out_fc, "dataset", "TEXT", 400)

    # add each dataset's extent & the dataset's name to the output
    with arcpy.da.InsertCursor(out_fc, ("SHAPE@", "dataset")) as cur:

        for i in in_datasets:
            d = arcpy.Describe(i)
            ex = d.Extent
            pts = arcpy.Array([arcpy.Point(ex.XMin, ex.YMin),
                              arcpy.Point(ex.XMin, ex.YMax),
                              arcpy.Point(ex.XMax, ex.YMax),
                              arcpy.Point(ex.XMax, ex.YMin),
                              arcpy.Point(ex.XMin, ex.YMin),])

            geom = arcpy.Polygon(pts,  d.SpatialReference)

            if d.SpatialReference != out_sr:
                geom = geom.projectAs(out_sr)
            cur.insertRow([geom, d.CatalogPath]) 
開發者ID:arcpy,項目名稱:sample-gp-tools,代碼行數:32,代碼來源:datasetExtentToFeatures.py

示例5: rename_col

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def rename_col(tbl, col, newcol, alias = ''):
    """Rename column in table tbl and return the new name of the column.

    This function first adds column newcol, re-calculates values of col into it,
    and deletes column col.
    Uses arcpy.ValidateFieldName to adjust newcol if not valid.
    Raises ArcapiError if col is not found or if newcol already exists.

    Required:
    tbl -- table with the column to rename
    col -- name of the column to rename
    newcol -- new name of the column

    Optional:
    alias -- field alias for newcol, default is '' to use newcol for alias too
    """
    if col != newcol:
        d = arcpy.Describe(tbl)
        dcp = d.catalogPath
        flds = arcpy.ListFields(tbl)
        fnames = [f.name.lower() for f in flds]
        newcol = arcpy.ValidateFieldName(newcol, tbl) #os.path.dirname(dcp))
        if col.lower() not in fnames:
            raise ArcapiError("Field %s not found in %s." % (col, dcp))
        if newcol.lower() in fnames:
            raise ArcapiError("Field %s already exists in %s" % (newcol, dcp))
        oldF = [f for f in flds if f.name.lower() == col.lower()][0]
        if alias == "": alias = newcol
        arcpy.AddField_management(tbl, newcol, oldF.type, oldF.precision, oldF.scale, oldF.length, alias, oldF.isNullable, oldF.required, oldF.domain)
        arcpy.CalculateField_management(tbl, newcol, "!" + col + "!", "PYTHON_9.3")
        arcpy.DeleteField_management(tbl, col)
    return newcol 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:34,代碼來源:arcapi.py

示例6: add_fields_from_table

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def add_fields_from_table(in_tab, template, add_fields=[]):
    """Add fields (schema only) from one table to another

    Required:
    in_tab -- input table
    template -- template table containing fields to add to in_tab
    add_fields -- fields from template table to add to input table (list)

    Example:
    >>> add_fields_from_table(parcels, permits, ['Permit_Num', 'Permit_Date'])
    """

    # fix args if args from script tool
    if isinstance(add_fields, str):
        add_fields = add_fields.split(';')

    # grab field types
    f_dict = dict((f.name, [get_field_type(f.type), f.length, f.aliasName]) for f in arcpy.ListFields(template))

    # Add fields
    for field in add_fields:
        if field in f_dict:
            f_ob = f_dict[field]
            arcpy.AddField_management(in_tab, field, f_ob[0], field_length=f_ob[1], field_alias=f_ob[2])
            msg('Added field: {0}'.format(field))
    return 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:28,代碼來源:arcapi.py

示例7: check_field

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def check_field(fc_class, field):
    print("Checking for " + field + " on " + fc_class)
    field_names = [f.name for f in arcpy.ListFields(fc_class)]
    if field not in field_names:
        arcpy.AddMessage("Adding Field to " + str(fc_class))
        arcpy.AddField_management(fc_class, field, "Long") 
開發者ID:Esri,項目名稱:CTM,代碼行數:8,代碼來源:parseVST.py

示例8: __getattr__

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def __getattr__(self, attr):
            """Recursively raise not implemented error for any calls to arcpy:

                arcpy.management.AddField(...)

            or:

                arcpy.AddField_management(...)
            """
            return Callable() 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:12,代碼來源:common_types.py

示例9: createOutputFC

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def createOutputFC():
    # Input theAOI is the original first parameter (usually CLU feature layer)
    #
    # Given the path for the new output featureclass, create it as polygon and add required fields
    # Later it will be populated using a cursor.

    try:

        epsgWGS84 = 4326 # EPSG code for: GCS-WGS-1984
        outputCS = arcpy.SpatialReference(epsgWGS84)

        nasisProjectFC = arcpy.CreateScratchName("nasisProject", workspace=arcpy.env.scratchGDB,data_type="FeatureClass")

        # Create empty polygon featureclass with coordinate system that matches AOI.
        arcpy.CreateFeatureclass_management(env.scratchGDB, os.path.basename(nasisProjectFC), "POLYGON", "", "DISABLED", "DISABLED", outputCS)
        arcpy.AddField_management(nasisProjectFC,"mukey", "TEXT", "", "", "30")   # for outputShp

        if not arcpy.Exists(nasisProjectFC):
            AddMsgAndPrint("\tFailed to create " + nasisProjectFC + " TEMP Layer",2)
            return False

        return nasisProjectFC

    except:
        errorMsg()
        return False


## =================================================================================== 
開發者ID:ncss-tech,項目名稱:geo-pit,代碼行數:31,代碼來源:SDA_JSON_Testing.py

示例10: insert_rows

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def insert_rows(fc,
                features,
                fields,
                includeOIDField=False,
                oidField=None):
    """ inserts rows based on a list features object """
    if arcpyFound == False:
        raise Exception("ArcPy is required to use this function")
    icur = None
    if includeOIDField:
        arcpy.AddField_management(fc, "FSL_OID", "LONG")
        fields.append("FSL_OID")
    if len(features) > 0:
        fields.append("SHAPE@")
        workspace = os.path.dirname(fc)
        with arcpy.da.Editor(workspace) as edit:
            date_fields = getDateFields(fc)
            icur = arcpy.da.InsertCursor(fc, fields)
            for feat in features:
                row = [""] * len(fields)
                drow = feat.asRow[0]
                dfields = feat.fields
                for field in fields:
                    if field in dfields or \
                       (includeOIDField and field == "FSL_OID"):
                        if field in date_fields:
                            row[fields.index(field)] = toDateTime(drow[dfields.index(field)])
                        elif field == "FSL_OID":
                            row[fields.index("FSL_OID")] = drow[dfields.index(oidField)]
                        else:
                            row[fields.index(field)] = drow[dfields.index(field)]
                    del field
                row[fields.index("SHAPE@")] = feat.geometry
                icur.insertRow(row)
                del row
                del drow
                del dfields
                del feat
            del features
            icur = None
            del icur
            del fields
        return fc
    else:
        return fc
#---------------------------------------------------------------------- 
開發者ID:Esri,項目名稱:ArcREST,代碼行數:48,代碼來源:spatial.py

示例11: concatenate_fields

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def concatenate_fields(table, new_field, length, fields=[], delimiter='', number_only=False):
    """Create a new field in a table and concatenate user defined fields.

    This can be used in situations such as creating a Section-Township-Range
    field from 3 different fields.
    Returns the field name that was added.

    Required:
    table -- Input table
    new_field -- new field name
    length -- field length
    fields -- list of fields to concatenate

    Optional:
    delimiter -- join value for concatenated fields
        (example: '-' , all fields will be delimited by dash)
    number_only -- if True, only numeric values from a text field are extracted.
        Default is False.

    Example:
    >>> sec = r'C:\Temp\Sections.shp'
    >>> concatenate_fields(sec, 'SEC_TWP_RNG', 15, ['SECTION', 'TOWNSHIP', 'RANGE'], '-')
    """

    # Add field
    new_field = create_field_name(table, new_field)
    arcpy.AddField_management(table, new_field, 'TEXT', field_length=length)

    # Concatenate fields
    if arcpy.GetInstallInfo()['Version'] != '10.0':
        # da cursor
        with arcpy.da.UpdateCursor(table, fields + [new_field]) as rows:
            for r in rows:
                r[-1] = concatenate(r[:-1], delimiter, number_only)
                rows.updateRow(r)

    else:
        # 10.0 cursor
        rows = arcpy.UpdateCursor(table)
        for r in rows:
            r.setValue(new_field, concatenate([r.getValue(f) for f in fields], delimiter, number_only))
            rows.updateRow(r)
        del r, rows
    return new_field 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:46,代碼來源:arcapi.py

示例12: getZoneField

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def getZoneField(muLayerPath, analysisType):
    # This function will return a field name based on the analysis type that
    # was chosen by the user.  If analysis type is MUKEY, then MUKEY is returned if
    # the field exists, otherwise a newly created field "MLRA_Temp" will be returned.
    # "MLRA_Temp" will be returned for MLRA analysis type
    # OID field will be returned for each polygon

    try:

        theDesc = arcpy.Describe(muLayerPath)
        theFields = theDesc.fields
        theField = theFields[0]
        idField = theDesc.OIDFieldName

        if analysisType.find('Mapunit (MUKEY)') > -1:

            if len(arcpy.ListFields(muLayerPath,"MUKEY")) > 0:
                return "MUKEY"
            else:
                AddMsgAndPrint("\nAnalysis Cannot be done by Mapunit since MUKEY is missing.",1)
                AddMsgAndPrint("Proceeding with analysis using MLRA ",1)

                if not len(arcpy.ListFields(muLayerPath, "MLRA_Temp")) > 0:
                    arcpy.AddField_management(muLayer,"MLRA_Temp","TEXT", "", "", 15)

                arcpy.CalculateField_management(muLayer,"MLRA_Temp", "\"MLRA Mapunit\"", "PYTHON_9.3", "")
                return "MLRA_Temp"

        elif analysisType.find('MLRA Mapunit') > -1:
            if not len(arcpy.ListFields(muLayerPath, "MLRA_Temp")) > 0:
                arcpy.AddField_management(muLayer,"MLRA_Temp","TEXT", "", "", 15)

            arcpy.CalculateField_management(muLayer,"MLRA_Temp", "\"MLRA Mapunit\"", "PYTHON_9.3", "")
            return "MLRA_Temp"

        # Analysis Type = Polygon
        else:
            AddMsgAndPrint("\nWARNING Reporting by polygon might be very verbose")
            return idField

    except:
        errorMsg()
        return ""

## =============================================================================================================== 
開發者ID:ncss-tech,項目名稱:geo-pit,代碼行數:47,代碼來源:Validate_Mapunit_Slope_Range.py

示例13: createOutputFC

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def createOutputFC(dictOfFields,preFix="Temp",shape="POLYGON"):
    """ This function will creat an empty polygon feature class within the scratch FGDB.  The feature class will be in WGS84
        and will have have 2 fields created: mukey and mupolygonkey.  The feature class name will have a prefix of
        'nasisProject.' This feature class is used by the 'requestGeometryByMUKEY' function to write the polygons associated with a NASIS
        project.

        fieldDict ={field:(fieldType,fieldLength,alias)
        fieldDict = {"mukey":("TEXT",30,"Mapunit Key"),"mupolygonkey":("TEXT","",30)}

        Return the new feature class  including the path.  Return False if error ocurred."""

    try:
        epsgWGS84 = 4326 # EPSG code for: GCS-WGS-1984
        outputCS = arcpy.SpatialReference(epsgWGS84)

        newFC = arcpy.CreateScratchName(preFix, workspace=arcpy.env.scratchGDB,data_type="FeatureClass")

        # Create empty polygon featureclass with coordinate system that matches AOI.
        arcpy.CreateFeatureclass_management(env.scratchGDB, os.path.basename(newFC), shape, "", "DISABLED", "DISABLED", outputCS)

        for field,params in dictOfFields.iteritems():
            try:
                fldLength = params[1]
                fldAlias = params[2]
            except:
                fldLength = 0
                pass

            arcpy.AddField_management(newFC,field,params[0],"#","#",fldLength,fldAlias)

##            if len(params[1]) > 0:
##                expression = "\"" + params[1] + "\""
##                arcpy.CalculateField_management(helYesNo,field,expression,"VB")

##        arcpy.AddField_management(nasisProjectFC,"mukey", "TEXT", "", "", "30")
##        arcpy.AddField_management(nasisProjectFC,"mupolygonkey", "TEXT", "", "", "30")   # for outputShp

        if not arcpy.Exists(newFC):
            AddMsgAndPrint("\tFailed to create scratch " + newFC + " Feature Class",2)
            return False

        return newFC

    except:
        errorMsg()
        AddMsgAndPrint("\tFailed to create scratch " + newFC + " Feature Class",2)
        return False

## =================================================================================== 
開發者ID:ncss-tech,項目名稱:geo-pit,代碼行數:51,代碼來源:Extract_PLU_by_NASIS_Project.py

示例14: getZoneField

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def getZoneField(analysisType):
    # This function will return a field name based on the analysis type that
    # was chosen by the user.  If analysis type is MUKEY, then MUKEY is returned if
    # it exists, otherwise a newly created field "MLRA_Temp" will be returned.
    # "MLRA_Temp" will be returned for MLRA analysis type
    # OID field will be returned for each polygon

    try:
        mlraTempFld = "MLRA_Temp"

        if analysisType.find('Mapunit (MUKEY)') > -1:

            if len(arcpy.ListFields(muLayerPath,"MUKEY")) > 0:
                return "MUKEY"
            else:
                AddMsgAndPrint("\nAnalysis Cannot be done by Mapunit since MUKEY is missing.",1)
                AddMsgAndPrint("Proceeding with analysis using MLRA ",1)

                if not len(arcpy.ListFields(muLayerPath,mlraTempFld)) > 0:
                    arcpy.AddField_management(muLayerPath,mlraTempFld,"TEXT", "", "", 15)

                # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
                with arcpy.da.UpdateCursor(muLayerPath,mlraTempFld) as cursor:
                    for row in cursor:
                        row[0] = "MLRA_Mapunit"
                        cursor.updateRow(row)

                return mlraTempFld

        elif analysisType.find('MLRA Mapunit') > -1:
            if not len(arcpy.ListFields(muLayerPath,mlraTempFld)) > 0:
                arcpy.AddField_management(muLayerPath,mlraTempFld,"TEXT", "", "", 15)
                arcpy.RefreshCatalog(outputFolder)

            # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
            with arcpy.da.UpdateCursor(muLayerPath,mlraTempFld) as cursor:
                for row in cursor:
                    row[0] = "MLRA_Mapunit"
                    cursor.updateRow(row)

            return mlraTempFld

        # Analysis Type = Polygon
        else:
            AddMsgAndPrint("\nWARNING Reporting by polygon might be very verbose")
            return idField

    except:
        errorMsg()
        return False

# =================================================================================== 
開發者ID:ncss-tech,項目名稱:geo-pit,代碼行數:54,代碼來源:Mapunit_Geodata_Breakdown_Description.py

示例15: getZoneField

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import AddField_management [as 別名]
def getZoneField(analysisType):
    # This function will return a field name based on the analysis type that
    # was chosen by the user.  If analysis type is MUKEY, then MUKEY is returned if
    # it exists, otherwise a newly created field "MLRA_Temp" will be returned.
    # "MLRA_Temp" will be returned for MLRA analysis type
    # OID field will be returned for each polygon

    try:
        mlraTempFld = "MLRA_Temp"

        if analysisType.find('Mapunit (MUKEY)') > -1:

            if len(arcpy.ListFields(muLayer,"MUKEY")) > 0:
                return "MUKEY"
            else:
                AddMsgAndPrint("\nAnalysis Cannot be done by Mapunit since MUKEY is missing.",1)
                AddMsgAndPrint("Proceeding with analysis using MLRA ",1)

                if not len(arcpy.ListFields(muLayer,mlraTempFld)) > 0:
                    arcpy.AddField_management(muLayer,mlraTempFld,"TEXT", "", "", 15)

            # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
            with arcpy.da.UpdateCursor(muLayer,mlraTempFld) as cursor:
                for row in cursor:
                    row[0] = "MLRA_Mapunit"
                    cursor.updateRow(row)

            return "MLRA_Temp"

        elif analysisType.find('MLRA Mapunit') > -1:
            if not len(arcpy.ListFields(muLayer,mlraTempFld)) > 0:
                arcpy.AddField_management(muLayer,mlraTempFld,"TEXT", "", "", 15)
                arcpy.RefreshCatalog(outputFolder)

            # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
            with arcpy.da.UpdateCursor(muLayer,mlraTempFld) as cursor:
                for row in cursor:
                    row[0] = "MLRA_Mapunit"
                    cursor.updateRow(row)

            return "MLRA_Temp"

        # Analysis Type = Polygon
        else:
            AddMsgAndPrint("\nWARNING Reporting by polygon might be very verbose")
            return idField

    except:
        errorMsg()
        return False

# =================================================================================== 
開發者ID:ncss-tech,項目名稱:geo-pit,代碼行數:54,代碼來源:Area_Geodata_Breakdown_Description.py


注:本文中的arcpy.AddField_management方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。