Python arcpy.CalculateField_management() Examples

The following are 5 code examples of arcpy.CalculateField_management(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module arcpy , or try the search function .
Example #1
Source File: CreateDischargeTable.py    From python-toolbox-for-rapid with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #3
Source File: WMX_Generalization.py    From CTM with Apache License 2.0 5 votes vote down vote up
def setEdgeHierarchy(fcs, aoi, hier_field):
    """ sets the hierarchy of all features touching the aoi to 0"""
    arcpy.AddMessage("Setting hierarcy for edge features")
    for fc in fcs:
        fields = [f.name for f in arcpy.ListFields(fc)]
        if hier_field in fields:
            lyr = arcpy.MakeFeatureLayer_management(fc, "layera")
            arcpy.SelectLayerByLocation_management(lyr, "INTERSECT", aoi)
            arcpy.CalculateField_management(lyr, hier_field, "0")
            arcpy.Delete_management(lyr) 
Example #4
Source File: Validate_Mapunit_Slope_Range.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
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 ""

## =============================================================================================================== 
Example #5
Source File: Extract_PLU_by_NASIS_Project.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
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

## ===================================================================================