def linesAndPoints(fc, outputDir, logfile): addMsgAndPrint(' Translating {}...'.format(fc)) cp = fc.find('/') fcShp = fc[cp + 1:] + '.shp' LIN2 = fc[cp + 1:] + '2' LIN = 'xx' + fc[cp + 1:] #addMsgAndPrint(' Copying features from {} to {}'.format(fc, LIN2)) arcpy.CopyFeatures_management(fc, LIN2) arcpy.MakeFeatureLayer_management(LIN2, LIN) fieldNames = fieldNameList(LIN) if 'Type' in fieldNames: arcpy.AddField_management(LIN, 'Definition', 'TEXT', '#', '#', '254') arcpy.AddJoin_management(LIN, 'Type', 'Glossary', 'Term') arcpy.CalculateField_management(LIN, 'Definition', '!Glossary.Definition![0:254]', 'PYTHON') arcpy.RemoveJoin_management(LIN, 'Glossary') # command below are 9.3+ specific sourceFields = arcpy.ListFields(fc, '*SourceID') for sField in sourceFields: nFieldName = sField.name[:-2] arcpy.AddField_management(LIN, nFieldName, 'TEXT', '#', '#', '254') arcpy.AddJoin_management(LIN, sField.name, 'DataSources', 'DataSources_ID') arcpy.CalculateField_management(LIN, nFieldName, '!DataSources.Source![0:254]', 'PYTHON') arcpy.RemoveJoin_management(LIN, 'DataSources') arcpy.DeleteField_management(LIN, sField.name) dumpTable(LIN2, fcShp, True, outputDir, logfile, False, fc[cp + 1:]) arcpy.Delete_management(LIN) arcpy.Delete_management(LIN2)
def PipeDepthCheck(errtype,inDB1,inDB2,outDB,logDB): #inDB1 is Pipe #inDB2 is Node returnValue = 0 errcount = 0 dateofrun = datetime.datetime.now() view = arcpy.MakeTableView_management(inDB1,"tempview") view2 = arcpy.MakeTableView_management(inDB2,"tempview2") joinres = arcpy.AddJoin_management(view,[x.name for x in arcpy.ListFields(view) if "UpstreamNodeID" in x.name][0],view2,[x.name for x in arcpy.ListFields(view2) if "ObjectID" in x.name][0],"KEEP_COMMON") fields = [x.name for x in arcpy.ListFields(joinres) if "ObjectID" in x.name or "InvertLevel" in x.name or "GroundLevel" in x.name] #[u'GIS_VCS_DD_TEST.DANDAS.WW_Pipe.ObjectID', u'GIS_VCS_DD_TEST.DANDAS.WW_Pipe.UpstreamInvertLevel', u'GIS_VCS_DD_TEST.DANDAS.WW_Pipe.DownstreamInvertLevel', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.ObjectID', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.InvertLevel', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.InvertLevelOriginID', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.GroundLevel', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.GroundLevelOriginID'] cursorS = arcpy.da.SearchCursor(joinres,fields) cursorI = arcpy.da.InsertCursor(outDB,[x.name for x in arcpy.ListFields(outDB)[1:]]) #UpstreamDict = {} for row in cursorS: if (isinstance(row[1],float) or isinstance(row[1],int)) and (isinstance(row[4],float) or isinstance(row[4],int) ) and (isinstance(row[6],float) or isinstance(row[6],int) ): if row[1] < row[4] or row[1] > row[6]: cursorI.insertRow(["Join with Node","Pipe","Upstream",globalScriptSettings.getErrID(),row[0],row[3],row[6],row[1],row[4]]) errcount += 1 else: cursorI.insertRow(["Join with Node","Pipe","Upstream",globalScriptSettings.getErrID(),row[0],row[3],row[6],row[1],row[4]]) errcount += 1 arcpy.RemoveJoin_management(joinres) del cursorS joinres2 = arcpy.AddJoin_management(view,[x.name for x in arcpy.ListFields(view) if "DownstreamNodeID" in x.name][0],view2,[x.name for x in arcpy.ListFields(view2) if "ObjectID" in x.name][0],"KEEP_COMMON") cursorSearch = arcpy.da.SearchCursor(joinres2,fields) #caughtlist = set() for row in cursorSearch: if (isinstance(row[2],float) or isinstance(row[2],int)) and (isinstance(row[4],float) or isinstance(row[4],int) ) and (isinstance(row[6],float) or isinstance(row[6],int) ): if row[2] < row[4] or row[2] > row[6]: cursorI.insertRow(["Join with Node","Pipe","Downstream",globalScriptSettings.getErrID(),row[0],row[3],row[6],row[2],row[4]]) errcount += 1 else: cursorI.insertRow(["Join with Node","Pipe","Downstream",globalScriptSettings.getErrID(),row[0],row[3],row[6],row[2],row[4]]) errcount += 1 logcursorI = arcpy.da.InsertCursor(logDB,[x.name for x in arcpy.ListFields(logDB)[1:]]) del cursorSearch arcpy.RemoveJoin_management(joinres2) arcpy.Delete_management(view) arcpy.Delete_management(view2) del cursorI logcursorI.insertRow([dateofrun,errtype,errcount,globalScriptSettings.getRunCount()]) del logcursorI returnValue = errcount return returnValue
def pipe_attribute_add(pipeline): try: pipelyr = arcpy.MakeFeatureLayer_management(pipeline, "pipelyr") print "开始执行起始点" arcpy.AddMessage(u"开始执行起始点") P_start = select_identify_point("START") print P_start[0] base_p_start = os.path.basename(P_start[0]) P_end = select_identify_point('END') base_p_end = os.path.basename(P_end[0]) arcpy.AddJoin_management( pipelyr, "PipeLineNumber", P_start, "PipeLineNumber") arcpy.CalculateField_management( pipelyr, 'StartPointNum', "!%s.POINTNUMBER!"% base_p_start , "PYTHON_9.3") arcpy.CalculateField_management( pipelyr, 'OrgName', "!%s.OrgName_1!" % base_p_start, "PYTHON_9.3") arcpy.CalculateField_management( pipelyr, 'OrgCode', "!%s.OrgCode_1!" % base_p_start, "PYTHON_9.3") arcpy.RemoveJoin_management( pipelyr,base_p_start) print "起始点字段计算结束" arcpy.AddMessage(u"起始点字段计算结束") print "\n" print "开始执行终点" arcpy.AddMessage(u"开始执行终点") arcpy.AddJoin_management( pipelyr, "PipeLineNumber", P_end, "PipeLineNumber") arcpy.CalculateField_management( pipelyr, 'EndPointNum', "!POINTNUMBER!", "PYTHON_9.3") arcpy.RemoveJoin_management( pipelyr, base_p_end) pipewithattr = arcpy.CopyFeatures_management(pipelyr, "pipewithattr") arcpy.DeleteFeatures_management(pipeline) arcpy.Append_management(pipewithattr,pipeline) print "点号提取完成" arcpy.AddMessage(u"点号提取完成") except arcpy.ExecuteError as e: print e else: arcpy.Delete_management(pipewithattr)
def fc_joins(fcName, fcPath, glosPath, ds_path): """ Joins feature class with the Glossary and DataSources tables and calculates values to new fields. Returns a feature layer with the joins """ # reporting fc_in_fds = fds_and_name(fcPath) gems.addMsgAndPrint(' Joining {} to Glossary and DataSources...' .format(fc_in_fds)) if debug: print 1 print_field_names(fcPath) try: fcShp = fcName + '.shp' LIN = 'xx' + fcName #remove_joins(fcPath) arcpy.MakeFeatureLayer_management(fcPath, LIN) fieldNames = gems.fieldNameList(LIN) if 'Type' in fieldNames: arcpy.AddField_management(LIN, 'Definition', 'TEXT', '#', '#', '254') arcpy.AddJoin_management(LIN, 'Type', glosPath, 'Term') arcpy.CalculateField_management(LIN, 'Definition', '!Glossary.Definition![0:254]', 'PYTHON') arcpy.RemoveJoin_management(LIN, 'Glossary') # command below are 9.3+ specific sourceFields = arcpy.ListFields(fcPath, '*SourceID') for sField in sourceFields: nFieldName = sField.name[:-2] arcpy.AddField_management(LIN, nFieldName, 'TEXT', '#', '#', '254') arcpy.AddJoin_management(LIN, sField.name, ds_path, 'DataSources_ID') arcpy.CalculateField_management(LIN, nFieldName, '!DataSources.Source![0:254]', 'PYTHON') arcpy.RemoveJoin_management(LIN, 'DataSources') arcpy.DeleteField_management(LIN, sField.name) arcpy.MakeFeatureLayer_management(LIN, 'feature_layer') # cleanup gems.testAndDelete(LIN) arcpy.DeleteField_management(fcPath, ['Definition', nFieldName]) return 'feature_layer' except: gems.addMsgAndPrint(arcpy.GetMessages()) gems.addMsgAndPrint(' COULD NOT CREATE JOINS FOR {}'.format(fc_in_fds))
def route_data(route, block): arcpy.AddMessage("Joining clostest routes to blocks...") new_tbl = str(block)[:-4] + "_" + str(route)[:-4] arcpy.CopyRows_management(route, new_tbl) route_tbl = str(new_tbl) + "_tvw" arcpy.MakeTableView_management(new_tbl, route_tbl) arcpy.AddField_management(route_tbl, "GEOID10", "TEXT", "", "", 15, "GEOID10") arcpy.AddField_management(route_tbl, "SITE", "TEXT", "", "", 75, "SITE") arcpy.CalculateField_management(route_tbl, "GEOID10", "(!Name![0:15])", "PYTHON_9.3") arcpy.CalculateField_management(route_tbl, "SITE", "(!Name![18:])", "PYTHON_9.3") arcpy.CalculateField_management(route_tbl, "SITE", "(!SITE![:-6])", "PYTHON_9.3") arcpy.AddJoin_management(block, "GEOID10", route_tbl, "GEOID10") field_name = str(route_tbl)[:-4] arcpy.CalculateField_management(block, "DIST", "(!" + field_name + ".Total_Length!)", "PYTHON_9.3") arcpy.CalculateField_management(block, "DIST", "(!DIST!/5280)", "PYTHON_9.3") arcpy.RemoveJoin_management(block) arcpy.AddMessage("...completed!") return
def LateralRefrence(errtype,inDB1,inDB2,outDB,logDB): returnValue = 0 errcount = 0 dateofrun = datetime.datetime.now() view = arcpy.MakeTableView_management(inDB1,"tempview","NOT MainPipeID IS NULL") view2 = arcpy.MakeTableView_management(inDB2,"tempview2") joinres = arcpy.AddJoin_management(view,"MainPipeID",view2,"ObjectID","KEEP_ALL") joinfields = [x.name for x in arcpy.ListFields(joinres) if "ObjectID" in x.name or "MainPipeID" in x.name] cursorSwhere = arcpy.da.SearchCursor(joinres,joinfields,[x.name for x in arcpy.ListFields(joinres) if "MainPipe.ObjectID" in x.name][0] + " IS NULL") cursorI = arcpy.da.InsertCursor(outDB,[x.name for x in arcpy.ListFields(outDB)[1:]]) logcursorI = arcpy.da.InsertCursor(logDB,[x.name for x in arcpy.ListFields(logDB)[1:]]) for row in cursorSwhere: cursorI.insertRow(["Join on RefrenceID","LateralConnection","",globalScriptSettings.getErrID(),row[0],row[1]]) errcount += 1 del cursorI del cursorSwhere logcursorI.insertRow([dateofrun,errtype,errcount,globalScriptSettings.getRunCount()]) del logcursorI arcpy.RemoveJoin_management(joinres) arcpy.Delete_management(view) arcpy.Delete_management(view2) returnValue = errcount return returnValue
def ShpFixGeometry(fileRoot, item, newTempDir, timeItem, type): ###检查几何 arcpy.env.scratchWorkspace = newTempDir out_table = newTempDir + '\\' + 'outputTable' arcpy.CheckGeometry_management( fileRoot + '\\' + 'shapefile' + '_' + str(resolution) + '\\' + type + '_' + timeItem + '_' + str(resolution) + '\\' + item, out_table) ###修复几何 fcs = [] for row in arcpy.da.SearchCursor(out_table, ("CLASS")): if not row[0] in fcs: fcs.append(row[0]) for fc in fcs: # print("Processing " + fc) lyr = 'temporary_layer' if arcpy.Exists(lyr): arcpy.Delete_management(lyr) tv = "cg_table_view" if arcpy.Exists(tv): arcpy.Delete_management(tv) arcpy.MakeTableView_management(out_table, tv, ("\"CLASS\" = '%s'" % fc)) arcpy.MakeFeatureLayer_management(fc, lyr) arcpy.AddJoin_management(lyr, arcpy.Describe(lyr).OIDFieldName, tv, "FEATURE_ID") arcpy.RemoveJoin_management(lyr, os.path.basename(out_table)) arcpy.RepairGeometry_management(lyr)
def calc_counts(): #join Waze_OPTCS with Alerts # Join Waze_Optics with Waze Data cluster_original_join = arcpy.AddJoin_management("Waze_OPTICS", "SOURCE_ID", "Alerts", "ObjectId", "KEEP_ALL") # Count # waze incidents in each cluster summ_stats = arcpy.analysis.Statistics(cluster_original_join, "Alerts_Statistics", "Alerts.ObjectId COUNT", "Waze_OPTICS.CLUSTER_ID") arcpy.RemoveJoin_management (cluster_original_join) # Add Frequency Field arcpy.AddField_management("Waze_Ellipses", "TotalCount", "LONG", None, None, None, None, "NULLABLE", "NON_REQUIRED", None) # Join Ellipses to previously created Counts from above ellipses_counts_join = arcpy.AddJoin_management("Waze_Ellipses", "CLUSTER_ID", summ_stats, "CLUSTER_ID", "KEEP_ALL") # Update Counts Field # arcpy.CalculateField_management(ellipses_counts_join, "Waze_Ellipses.totalcounts", "!Static_Waze_Data_Statistics.FREQUENCY!", "PYTHON3", None) arcpy.management.CalculateField(ellipses_counts_join, "TotalCount", "!Alerts_Statistics.FREQUENCY!", "PYTHON3", None) arcpy.RemoveJoin_management (ellipses_counts_join) print("Counts added to Ellipses")
def FieldCombine(): rainIMERG = 'F:/Test/Paper180614/Data/IEMRG/' + 'RG83_IMERG.shp' # path = 'F:/Test/Paper180614/Data/IEMRG/RG83_IMERG.shp/' A = 'rainIMERG' arcpy.MakeFeatureLayer_management(rainIMERG, A) RGIMERGpath = 'F:/Test/Paper180614/Data/IEMRG/RG83/' arcpy.env.workspace = RGIMERGpath fs = arcpy.ListFeatureClasses() for i in range(0, len(fs), 1): if (len(fs[i]) == 16): curField = 'M' + str(fs[i][6:len(fs[i]) - 4]) print curField elif (len(fs[i]) == 15): curField = 'S' + str(fs[i][6:11]) print curField else: curField = 'Y' + str(fs[i][6:10]) print curField B = curField arcpy.MakeFeatureLayer_management(fs[i], B) arcpy.AddJoin_management(A, "FID", B, "FID") arcpy.CalculateField_management( A, 'RG83_IMERG.' + curField, "!" + fs[i][0:len(fs[i]) - 4] + ".RASTERVALU!", "PYTHON_9.3") arcpy.RemoveJoin_management(A)
def add_stats(stats_vw, core_id, fld_pre, table_vw, join_col): """Add zonal and calculated statistics to stick table.""" tmp_mea = fld_pre + "_tmp_mea" tmp_std = fld_pre + "_tmp_std" umin2std = fld_pre + "umin2std" # Add fields to stick table - has to be done before join arcpy.AddField_management(table_vw, tmp_mea, "Float", "", "", "", "", "NULLABLE") arcpy.AddField_management(table_vw, tmp_std, "Float", "", "", "", "", "NULLABLE") arcpy.AddField_management(table_vw, umin2std, "Float", "", "", "", "", "NULLABLE") # Join distance table to zonal stats table arcpy.AddJoin_management(table_vw, join_col, stats_vw, core_id) tbl_name = arcpy.Describe(table_vw).baseName stats_tbl_nm = arcpy.Describe(stats_vw).baseName # Insert values into fields mean_value = "!" + stats_tbl_nm + ".MEAN" + "!" std_value = "!" + stats_tbl_nm + ".STD" + "!" mea_fld = "!" + tbl_name + "." + tmp_mea + "!" std_fld = "!" + tbl_name + "." + tmp_std + "!" arcpy.CalculateField_management(table_vw, tmp_mea, mean_value, "PYTHON_9.3") arcpy.CalculateField_management(table_vw, tmp_std, std_value, "PYTHON_9.3") expression = mea_fld + " - " + std_fld + " - " + std_fld arcpy.CalculateField_management(table_vw, umin2std, expression, "PYTHON_9.3") # Remove join arcpy.RemoveJoin_management(table_vw, stats_tbl_nm)
def route_data(route, block): new_tbl = str(block)[:-4] + "_" + str(route)[:-4] arcpy.CopyRows_management(route, new_tbl) route_tbl = str(new_tbl) + "_tvw" arcpy.MakeTableView_management(new_tbl, route_tbl) arcpy.AddField_management(route_tbl, "GEOID10", "TEXT", "", "", 15, "GEOID10") arcpy.AddField_management(route_tbl, "SITE", "TEXT", "", "", 75, "SITE") expression1 = "(!Name![0:15])" expression2 = "(!Name![18:])" expression3 = "(!SITE![:-6])" arcpy.CalculateField_management(route_tbl, "GEOID10", expression1, "PYTHON_9.3") arcpy.CalculateField_management(route_tbl, "SITE", expression2, "PYTHON_9.3") arcpy.CalculateField_management(route_tbl, "SITE", expression3, "PYTHON_9.3") arcpy.AddJoin_management(block, "GEOID10", route_tbl, "GEOID10") field_name = str(route_tbl)[:-4] expression4 = "(!" + field_name + ".Total_Length!)" expression5 = "(!DIST!/5280)" arcpy.CalculateField_management(block, "DIST", expression4, "PYTHON_9.3") arcpy.CalculateField_management(block, "DIST", expression5, "PYTHON_9.3") arcpy.RemoveJoin_management(block) return
def braids(in_network_fc, tmp_network_tbl): arcpy.AddMessage("...braids") in_network_fc_lyr = "in_network_fc_lyr" arcpy.MakeFeatureLayer_management(in_network_fc, in_network_fc_lyr) # Set global variables FTR_CODE = 2 # Create temporary in_memory version of input stream network tmp_network_fc = r"in_memory\tmp_network_fc" #arcpy.FeatureClassToFeatureClass_conversion(in_network_fc_lyr, "in_memory", "tmp_network_fc") arcpy.FeatureClassToFeatureClass_conversion(in_network_fc_lyr, "in_memory", "tmp_network_fc") arcpy.MakeFeatureLayer_management(r"in_memory\tmp_network_fc", "tmp_network_fc_lyr") # Select reaches based on "IsBraided" attribute field expr = """"{0}" = {1}""".format("IsBraided", 1) arcpy.SelectLayerByAttribute_management("tmp_network_fc_lyr", "NEW_SELECTION", expr) arcpy.FeatureClassToFeatureClass_conversion("tmp_network_fc_lyr", "in_memory", "braids") arcpy.MakeFeatureLayer_management(r"in_memory\braids", "braids_lyr") # Add code values to network table arcpy.AddJoin_management(tmp_network_tbl, "ReachID", "braids_lyr", "ReachID", "KEEP_COMMON") arcpy.CalculateField_management(tmp_network_tbl, "FTR_CODE", FTR_CODE, "PYTHON_9.3") arcpy.RemoveJoin_management(tmp_network_tbl) # Clean up arcpy.Delete_management(tmp_network_fc) return
def fieldSubtract(): path = '' rainRes = 'F:/Test/Paper180614/Temp/' + 'rainResidual.shp' rainRGS = 'F:/Test/Paper180614/Temp/' + 'RainGauges.shp' A = 'rainRes' arcpy.MakeFeatureLayer_management(rainRes, A) B = 'RainGauges' arcpy.MakeFeatureLayer_management(rainRGS, B) arcpy.AddJoin_management(A, "FID", B, "FID") # arcpy.CalculateField_management(A, 'rainResidual.' + 'M201412','!' +'rainResidual.'+ 'M201412'+'!' +'-'+'!' + 'RainGauges.'+ 'M201412'+'!', # "PYTHON_9.3") # for y in range(15,18): # for m in range(1,13): # fieldName = 'M' + str((2000 + y) * 100 + m) # arcpy.CalculateField_management(A, 'rainResidual.' + fieldName, # '!' + 'rainResidual.' + fieldName + '!' + '-' + '!' + 'RainGauges.' + fieldName + '!', # "PYTHON_9.3") # for y in range(15,18): # for s in range(1,5): # fieldName='S'+str((2000+y)*10+s) # arcpy.CalculateField_management(A, 'rainResidual.' + fieldName, # '!' + 'rainResidual.' + fieldName + '!' + '-' + '!' + 'RainGauges.' + fieldName + '!', # "PYTHON_9.3") # for y in range(15, 18): # fieldName = 'Y' + str((2000 + y)) # arcpy.CalculateField_management(A, 'rainResidual.' + fieldName, # '!' + 'rainResidual.' + fieldName + '!' + '-' + '!' + 'RainGauges.' + fieldName + '!', # "PYTHON_9.3") arcpy.RemoveJoin_management(A)
def compute_CII_per_island(): # Compute the CII score per island as zonal statistics arcpy.CheckOutExtension("Spatial") arcpy.sa.ZonalStatisticsAsTable("buffered_islands", "STRONG", "cii_overall_score_ras1", "islands_with_CII_scores_table", "DATA", "MEAN") # Rename field MEAN to CII_Score_Overall arcpy.AlterField_management("islands_with_CII_scores_table", "MEAN", "CII_Score_Overall") # Join the resulting table back to the original islands feature class arcpy.AddJoin_management("islands", "STRONG", "islands_with_CII_scores_table", "STRONG", "KEEP_ALL") # Save to a new feature class arcpy.CopyFeatures_management("islands", "islands_with_score_with_nulls") arcpy.RemoveJoin_management("islands") # Remove any islands where the CII_Score_Overall is null ("> 0" does that) # Note: I did it differently from the other ones, because CopyFeatures_management() # was not dropping the nulls for some reason arcpy.Select_analysis("islands_with_score_with_nulls", "islands_with_score", 'islands_with_CII_scores_table_CII_Score_Overall > 0') # Delete some unnecessary fields drop_fields = ["islands_with_CII_scores_table_OBJECTID","islands_with_CII_scores_table_STRONG", "islands_with_CII_scores_table_COUNT", "islands_with_CII_scores_table_AREA"] arcpy.DeleteField_management("islands_with_score", drop_fields) # Rename some fields to their alias, to get rid of exagerated long names field_list = arcpy.ListFields("islands_with_score") for field in field_list: print(field.name) if field.aliasName in ["STRONG", "Orig_Length", "CII_Score_Overall"]: arcpy.AlterField_management("islands_with_score", field.name, field.aliasName) # Clean up remove_intermediary_layers(["buffered_islands","islands_with_CII_scores_table", "islands_with_score_with_nulls"]) turn_off_layers(["islands_with_score"])
def TVCCInRefrence(errtype, inDB1, inDB2, inDB3, outDB, logDB): #inDB1 is TVCCInspection #inDB2 is Report #inDB3 is PipeReport returnValue = 0 errcount = 0 dateofrun = datetime.datetime.now() view = arcpy.MakeTableView_management(inDB1, "tempview") view2 = arcpy.MakeTableView_management(inDB2, "tempview2") view3 = arcpy.MakeTableView_management(inDB3, "tempview3") joinres = arcpy.AddJoin_management(view, "ReportID", view2, "ObjectID", "KEEP_ALL") joinres2 = arcpy.AddJoin_management(joinres, [ x.name for x in arcpy.ListFields(joinres) if "Report.ObjectID" in x.name ][0], view3, "ReportID", "KEEP_ALL") joinfields = [ x.name for x in arcpy.ListFields(joinres2) if "ObjectID" in x.name or "InActive" in x.name ] #[u'GIS_VCS_DD_TEST.DANDAS.WW_CCTVInspection.ObjectID', u'GIS_VCS_DD_TEST.DANDAS.WW_CCTVInspection.InActive', u'GIS_VCS_DD_TEST.DANDAS.WW_Report.ObjectID', u'GIS_VCS_DD_TEST.DANDAS.WW_PipeReport.ObjectID'] cursorSwhere = arcpy.da.SearchCursor(joinres2, joinfields, [ x.name for x in arcpy.ListFields(joinres2) if "PipeReport.ObjectID" in x.name ][0] + " IS NULL") cursorI = arcpy.da.InsertCursor( outDB, [x.name for x in arcpy.ListFields(outDB)[1:]]) logcursorI = arcpy.da.InsertCursor( logDB, [x.name for x in arcpy.ListFields(logDB)[1:]]) for row in cursorSwhere: cursorI.insertRow([ "Join with Report and PipeReport", "TVCCInspection", "", globalScriptSettings.getErrID(), row[0], row[1] ]) errcount += 1 del cursorI del cursorSwhere logcursorI.insertRow( [dateofrun, errtype, errcount, globalScriptSettings.getRunCount()]) del logcursorI arcpy.RemoveJoin_management(joinres2) arcpy.Delete_management(view) arcpy.Delete_management(view2) arcpy.Delete_management(view3) returnValue = errcount return returnValue
def joinZonalStatsToTable (band, tableName, bandField): statsTable = tablesPath + "\\" + tableName arcpy.AddMessage("Stats_table: " + statsTable) print statsTable Field_Name_Calculate_field = gridName + "." + bandField print Field_Name_Calculate_field #Expression_Select_layer = tableName+".Mean IS NOT NULL" # Use this if the stats were saved to a dbf file "\""+tableName+".Mean\" IS NOT NULL" # Use this if the stats were saved to a table "\""+tableName+":Mean\" IS NOT NULL" # Use this if the stats were saved to a database table tableName+".Mean IS NOT NULL" #We will save the field Mean values of the table into the feature attributes #The round decimals are an input from the User Expression_Calculate_field = "!"+tableName+".Mean!" #Not to round #Expression_Calculate_field = "round(!"+tableName+".Mean!,"+ str(roundDecimals) +")" #the "!"+tableName+":Mean!" notation (:)is used when the stats are saved to a table #the "!"+tableName+".Mean!" notation (.)is used when the stats are saved to a dbf file print Expression_Calculate_field # Process: Zonal Statistics as Table arcpy.AddMessage("Zonal statistics...") print "Zonal statistics..." #Perform the zonalstatistics getting only the "MEAN" value of the cells #Save ALL statistics on table #"ALL" can be changed to get different statistics: #ALL,MEAN,MAJORITY,MAXIMUM,MEDIAN,MINIMUM,MINORITY,RANGE,STD,SUM,VARIETY,MIN_MAX,MEAN_STD,MIN_MAX_MEAN zs = arcpy.gp.ZonalStatisticsAsTable_sa(plot_polygons, Zone_field_and_join_Field, band, statsTable, "DATA", stats) arcpy.AddMessage("stats table: " + str(zs)) fields = gp.ListFields(gridLayer, bandField) field_found = fields.Next() if (not field_found): arcpy.AddField_management(gridLayer, bandField, "FLOAT", 10, 3, "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddMessage("Added field " + str(bandField)) else: arcpy.AddMessage("Field found " + str(field_found.name)) # Process: Add Join print "Joining..." arcpy.AddMessage("grid..."+ gridLayer) arcpy.AddMessage("field..."+Zone_field_and_join_Field) arcpy.AddJoin_management(gridLayer, Zone_field_and_join_Field, zs, Zone_field_and_join_Field, "KEEP_ALL") # Process: Select Layer By Attribute ## if i==1: ## print "Selecting Layer..." ## gridLayerSelection = arcpy.SelectLayerByAttribute_management(gridLayer, "NEW_SELECTION", Expression_Select_layer) # Process: Calculate Field print "Calculating field" arcpy.AddMessage("Calculating field...") arcpy.CalculateField_management(gridLayer, Field_Name_Calculate_field, Expression_Calculate_field, "PYTHON") # Process: Remove Join arcpy.AddMessage("remove Join") arcpy.RemoveJoin_management(gridLayer, "") #Erase stats table if not keep_tables: arcpy.Delete_management(zs)
def main(RouteTable, outDir, extraTable, extraParcelId): # Local variables msgTxt = "" startTime = time.time() connection = r"J:\pva\PVA_Routing\pvastaff_connection.sde" Parcel_Point = os.path.join(connection, "PVA.Land", "PVA.Parcel_Point") ParcelPnts = "Parcel_Pnts" try: # sys.path.append(r"J:\pva\PVA_Routing") sys.path.append(r"V:\Stan") import RoutingTable2Points RoutingTable2Points.main(RouteTable, outDir) # Convert the new feature class to a shapefile outShp = os.path.join(outDir, os.path.basename(RouteTable)) + ".shp" if arcpy.Exists(outShp): ScriptUtils.AddMsgAndPrint("\tAdding extra time...") # Connect to the new route points routingPointsLayer = "RouteShpOutput" # Process: Make Feature Layer from the new route points arcpy.MakeFeatureLayer_management(outShp, routingPointsLayer) # Connect to the extra time table extraTimeView = "ExtraTimeTable" # Process: Make Table View from the extra time table arcpy.MakeTableView_management(extraTable, extraTimeView) # Process: Add Join arcpy.AddJoin_management(routingPointsLayer, "PARCELID", extraTimeView, extraParcelId, "KEEP_COMMON") # Process: Calculate Field calcField = "{0}.TIME".format(os.path.basename(RouteTable)) expression = "ExtraTime(!{0}!)".format(calcField) codeBlk = ExtraTimeCodeBlock() # ScriptUtils.AddMsgAndPrint("\t\t calcField: {0}\n\t\tcalcExpression: {1}\n{2}...".format(calcField, expression, codeBlk)) arcpy.CalculateField_management(routingPointsLayer, calcField, expression, "PYTHON_9.3", codeBlk) # Process: Remove Join arcpy.RemoveJoin_management(routingPointsLayer, "") except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] gpmsg = "ARCPY ERRORS:\n{0}\n".format(arcpy.GetMessages(2)) pymsg = "PYTHON ERRORS:\n Traceback Info:\n{0}\n Error Info:\n\t{1}: {2}\n".format( tbinfo, str(sys.exc_type), str(sys.exc_value)) tmRun = time.strftime("%X", time.localtime()) endTime = time.time() prodInfo = "\tScript errored after running for {0} seconds.".format( str(round((endTime - startTime)))) msgTxt += "\n\n\tScript error at: {0}\n{1}\n\n{2}{3}".format( tmRun, prodInfo, gpmsg, pymsg) ScriptUtils.AddMsgAndPrint(msgTxt, 2)
def join_attr2_field(featuredata,com_fld_name,jointable,join_field): ad_fld_dic = {"PIPECODE":"管道编码","PIPENAME":"管道名称"} for key,val in ad_fld_dic.items(): arcpy.AddField_management(featuredata,key,"String",field_alias=val,field_length=255) tem_lyr = arcpy.MakeFeatureLayer_management(featuredata) arcpy.AddJoin_management(tem_lyr,com_fld_name,jointable,join_field) for key in ad_fld_dic.keys(): arcpy.CalculateField_management(tem_lyr,key,"!{0}.{1}!".format(jointable,key)) arcpy.RemoveJoin_management(tem_lyr,jointable)
def get_stats_per_zone(zone, out): # Compute SR stats for each zone. The output is a table arcpy.sa.ZonalStatisticsAsTable(zone, "OBJECTID", "Avg_SR_for_buildings_high_performance", main_data_path + "\\" + out + "_table", "DATA", "MEAN") arcpy.AddJoin_management(zone, "OBJECTID", out + "_table", "OBJECTID_1", "KEEP_ALL") arcpy.CopyFeatures_management(zone, main_data_path + "\\" + out) arcpy.RemoveJoin_management(zone)
def clim_env(): """Calculate Climate Envelope(s) for each core.""" lm_util.gprint( "Calculating Current Climate Envelope (clim_env) for each core") # calc score range normalization on current climate envelope cce_raster = normalize_raster(Raster(lp_env.CCERAST_IN), 0) # calc aerial mean climate envelope for each core cce_table = ZonalStatisticsAsTable( lp_env.COREFC, lp_env.COREFN, cce_raster, os.path.join(lm_env.SCRATCHDIR, "scratch.gdb", "core_clim_env_stats")) arcpy.AddJoin_management("core_lyr", lp_env.COREFN, cce_table, lp_env.COREFN) arcpy.CalculateField_management("core_lyr", lp_env.CORENAME + ".clim_env", "[core_clim_env_stats.MEAN]") arcpy.RemoveJoin_management("core_lyr") # score range normalize resulting values normalize_field("core_lyr", "clim_env", "nclim_env", 0) # future climate if lp_env.FCERAST_IN: lm_util.gprint( "Calculating Future Climate Envelope (fut_clim) for each core") # calc score range normalization on future climate envelope fce_raster = normalize_raster(Raster(lp_env.FCERAST_IN), 0) # calc aerial mean climate envelope for each core fce_table = ZonalStatisticsAsTable( lp_env.COREFC, lp_env.COREFN, fce_raster, os.path.join(lm_env.SCRATCHDIR, "scratch.gdb", "core_fclim_env_stats")) arcpy.AddJoin_management("core_lyr", lp_env.COREFN, fce_table, lp_env.COREFN) arcpy.CalculateField_management("core_lyr", lp_env.CORENAME + ".fut_clim", "[core_fclim_env_stats.MEAN]") arcpy.RemoveJoin_management("core_lyr") # score range normalize resulting values normalize_field("core_lyr", "fut_clim", "nfut_clim", 0)
def duplicates(in_network_fc, tmp_network_tbl): arcpy.AddMessage("...duplicate reaches") in_network_fc_lyr = "in_network_fc_lyr" arcpy.MakeFeatureLayer_management(in_network_fc, in_network_fc_lyr) # Set global variables FTR_CODE = 3 # Create temporary in_memory version of in_network_fc tmp_network_fc = r"in_memory\tmp_network_fc" arcpy.FeatureClassToFeatureClass_conversion(in_network_fc_lyr, "in_memory", "tmp_network_fc") arcpy.AddField_management(tmp_network_fc, "IsDuplicate", "SHORT") arcpy.AddField_management(tmp_network_fc, "Reach_Length", "DOUBLE") arcpy.MakeFeatureLayer_management(tmp_network_fc, "tmp_network_fc_lyr") arcpy.CalculateField_management("tmp_network_fc_lyr", "Reach_Length", "!shape.length@meters!", "PYTHON_9.3") # Find identical reaches based on length field with arcpy.da.SearchCursor("tmp_network_fc_lyr", ["Reach_Length"]) as length_cursor: lengths = [r[0] for r in length_cursor] with arcpy.da.UpdateCursor("tmp_network_fc_lyr", ["Reach_Length", "IsDuplicate"]) as cursor: for row in cursor: if lengths.count(row[0]) > 1: row[1] = 1 else: row[1] = 0 cursor.updateRow(row) # Select duplicate records expr = """"{0}" = {1}""".format("IsDuplicate", 1) arcpy.SelectLayerByAttribute_management("tmp_network_fc_lyr", "NEW_SELECTION", expr) arcpy.FeatureClassToFeatureClass_conversion("tmp_network_fc_lyr", "in_memory", "duplicates_only") arcpy.MakeFeatureLayer_management("in_memory\\duplicates_only", "duplicates_only_lyr") # Add feature code values to network table arcpy.AddJoin_management(tmp_network_tbl, "ReachID", "duplicates_only_lyr", "ReachID", "KEEP_COMMON") arcpy.CalculateField_management(tmp_network_tbl, "FTR_CODE", FTR_CODE, "PYTHON_9.3") arcpy.RemoveJoin_management(tmp_network_tbl) # Clean up arcpy.Delete_management(tmp_network_fc) arcpy.Delete_management("tmp_network_fc_lyr") arcpy.Delete_management("in_memory\\duplicates_only") arcpy.Delete_management("duplicates_only_lyr") return
def InvalidCover(errtype, inDB1, inDB2, outDB, logDB): #inDB1 is Cover #inDB2 is Node returnValue = 0 errcount = 0 dateofrun = datetime.datetime.now() view = arcpy.MakeTableView_management(inDB1, "tempview") view2 = arcpy.MakeTableView_management(inDB2, "tempview2") joinres = arcpy.AddJoin_management(view, "NodeID", view2, "ObjectID", "KEEP_COMMON") joinfields = [ x.name for x in arcpy.ListFields(joinres) if "ObjectID" in x.name or "NodeTypeCode" in x.name ] #[u'GIS_VCS_DD_TEST.DANDAS.WW_Cover.ObjectID', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.ObjectID', u'GIS_VCS_DD_TEST.DANDAS.WW_Node.NodeTypeCode'] cursorSwhere = arcpy.da.SearchCursor( joinres, joinfields, "NOT " + [ x.name for x in arcpy.ListFields(joinres) if "Node.ObjectID" in x.name ][0] + " IS NULL") cursorI = arcpy.da.InsertCursor( outDB, [x.name for x in arcpy.ListFields(outDB)[1:]]) logcursorI = arcpy.da.InsertCursor( logDB, [x.name for x in arcpy.ListFields(logDB)[1:]]) for row in cursorSwhere: if row[2] != 1 and row[2] != 4 and row[2] != 7 and row[2] != 8 and row[ 2] != 9 and row[2] != 10 and row[2] != 11 and row[2] != 12: cursorI.insertRow([ "Join with Node", "Cover", "", globalScriptSettings.getErrID(), row[0], row[1], row[2] ]) errcount += 1 del cursorI del cursorSwhere logcursorI.insertRow( [dateofrun, errtype, errcount, globalScriptSettings.getRunCount()]) del logcursorI arcpy.RemoveJoin_management(joinres) arcpy.Delete_management(view) arcpy.Delete_management(view2) returnValue = errcount return returnValue
def main(input_strm, input_seg, outFGB): arcpy.AddMessage( "Transferring original stream reach object IDs to segments features..." ) # create copy of stream segments, which will include new stream ID field seg_id = arcpy.FeatureClassToFeatureClass_conversion( input_seg, outFGB, r"seg_id") # generate the midpoint for each segmented stream network arcpy.FeatureToPoint_management(input_seg, outFGB + "\midpoint", "INSIDE") arcpy.MakeFeatureLayer_management(outFGB + "\midpoint", "midpoint_lyr") # field mapping for the spatial join (this is from ESRI help resources example) # create FieldMap and FieldMapping objects fm_strmOID = arcpy.FieldMap() fm_segOID = arcpy.FieldMap() fms = arcpy.FieldMappings() # set field names from input files strm_oid = arcpy.Describe(input_strm).OIDFieldName line_oid = "LineOID" # from seg_id # add fields to FieldMap objects fm_strmOID.addInputField(input_strm, strm_oid) fm_segOID.addInputField(seg_id, line_oid) # set output field properties for FieldMap objects (this is pure ESRI clunkiness) strmOID_name = fm_strmOID.outputField strmOID_name.name = "strmOID" fm_strmOID.outputField = strmOID_name segOID_name = fm_segOID.outputField segOID_name.name = "LineOID" fm_segOID.outputField = segOID_name # add FieldMap objects to the FieldMappings object fms.addFieldMap(fm_strmOID) fms.addFieldMap(fm_segOID) # spatial join between midpoints and original stream network polyline feature class ##midpoint_join = r"in_memory\midpoint_join" midpoint_join = outFGB + "\midpoint_join" arcpy.SpatialJoin_analysis("midpoint_lyr", input_strm, midpoint_join, "JOIN_ONE_TO_MANY", "KEEP_ALL", fms, "INTERSECT", 0.5) # join midpoints to segmented streams based on shared LineOID arcpy.MakeFeatureLayer_management(seg_id, "seg_id_lyr") arcpy.AddField_management("seg_id_lyr", "strmID", "TEXT") arcpy.AddJoin_management("seg_id_lyr", "LineOID", midpoint_join, "LineOID", "KEEP_ALL") arcpy.CalculateField_management("seg_id_lyr", "strmID", "!strmOID!", "PYTHON_9.3") arcpy.RemoveJoin_management("seg_id_lyr") return seg_id
def getImperv(inShpPath, inlandUsePath, indexField, weights): # Process Path if not os.path.exists('Process'): os.makedirs('Process') processPath = "./Process/" # Process Data Path outShpTempPath = processPath + "subcaTemp.shp" outLandTempPath = processPath + "landTemp.shp" outLandRasterPath = processPath + "landUseRaster" outTablePath = processPath + "impervTable.dbf" # Output Path if not os.path.exists('Result'): os.makedirs('Result') # Output Data Path outShpPath = "./Result/subcatchments.shp" # Execute CopyFeatures arcpy.CopyFeatures_management(inShpPath, outShpTempPath) arcpy.CopyFeatures_management(inlandUsePath, outLandTempPath) # Check out the ArcGIS Spatial Analyst extension license arcpy.CheckExtension("Spatial") # Execute AddField arcpy.AddField_management(outLandTempPath, "Weight", "DOUBLE", "", "", "", "weight", "NULLABLE", "NON_REQUIRED", "") # Calculate Weight codeBlock = """ def getWeight(type, weights): return weights[type]""" expression = "getWeight( !category! ," + json.dumps(weights) + ")" arcpy.CalculateField_management(outLandTempPath, "Weight", expression, "PYTHON", codeBlock) # Execute FeatureToRaster arcpy.FeatureToRaster_conversion(outLandTempPath, "Weight", outLandRasterPath, 5) # Execute ZonalStatisticsAsTable outImperv = ZonalStatisticsAsTable(outShpTempPath, indexField, outLandRasterPath, outTablePath, "NODATA", "MEAN") # Execute AddField arcpy.AddField_management(outShpTempPath, "Imperv", "DOUBLE", "", "", "", "imperv", "NULLABLE", "NON_REQUIRED", "") # Create a feature layer layerName = "subcaShp" arcpy.MakeFeatureLayer_management(outShpTempPath, layerName) # Join the feature layer to a table arcpy.AddJoin_management(layerName, indexField, outImperv, indexField) # Calculate Slope arcpy.CalculateField_management(layerName, "Imperv", "!impervTable.MEAN!", "PYTHON") # Remove the join arcpy.RemoveJoin_management(layerName, "impervTable") # Copy the layer to a new permanent feature class arcpy.CopyFeatures_management(layerName, outShpPath) return outShpPath
def disconnected(in_network_fc, tmp_network_tbl): arcpy.AddMessage("...disconnected reaches") FTR_CODE = 6 in_network_fc_lyr = "in_network_fc_lyr" arcpy.MakeFeatureLayer_management(in_network_fc, in_network_fc_lyr) # join topology table to stream network feature class, and select reaches not found in the topology table arcpy.AddJoin_management(in_network_fc_lyr, "ReachID", tmp_network_tbl, "ReachID", "KEEP_ALL") for field in arcpy.ListFields(in_network_fc_lyr, "*UpstreamID"): upstream_field = field.name expr = """"{0}" IS NOT NULL""".format(upstream_field) arcpy.SelectLayerByAttribute_management(in_network_fc_lyr, "NEW_SELECTION", expr) arcpy.SelectLayerByAttribute_management(in_network_fc_lyr, "SWITCH_SELECTION") arcpy.RemoveJoin_management(in_network_fc_lyr) # copy selected reaches to a temporary table and append to tmp_network_tbl arcpy.CopyRows_management(in_network_fc_lyr, r"in_memory\disconnected_reaches") arcpy.MakeTableView_management(r"in_memory\disconnected_reaches", "disconnected_view") arcpy.AddField_management("disconnected_view", "UpstreamID", "LONG") arcpy.AddField_management("disconnected_view", "TO_NODE", "DOUBLE") arcpy.AddField_management("disconnected_view", "FROM_NODE", "DOUBLE") arcpy.AddField_management("disconnected_view", "FTR_CODE", "SHORT") with arcpy.da.SearchCursor( "disconnected_view", ["ReachID", "UpstreamID", "TO_NODE", "FROM_NODE", "FTR_CODE" ]) as scursor: with arcpy.da.InsertCursor( tmp_network_tbl, ["ReachID", "UpstreamID", "TO_NODE", "FROM_NODE", "FTR_CODE" ]) as icursor: for srow in scursor: icursor.insertRow(srow) arcpy.SelectLayerByAttribute_management(tmp_network_tbl, "NEW_SELECTION", """"UpstreamID" IS NULL""") with arcpy.da.UpdateCursor(tmp_network_tbl, ["FTR_CODE"]) as ucursor: for urow in ucursor: if urow[0] == None: urow[0] = FTR_CODE ucursor.updateRow(urow) #del urow, ucursor # clean up arcpy.SelectLayerByAttribute_management(tmp_network_tbl, "CLEAR_SELECTION") arcpy.SelectLayerByAttribute_management(in_network_fc_lyr, "CLEAR_SELECTION")
def update(infiles, temp_file): arcpy.AddField_management(infiles, "BEARING", "TEXT") arcpy.MakeFeatureLayer_management(infiles, tbl1) arcpy.MakeTableView_management(temp_file, tbl2, "\"BEARING\" <> ''") arcpy.JoinField_management(tbl1, id_field, tbl2, id_field) jrows = arcpy.UpdateCursor(tbl1) for jrow in jrows: bear = jrow.getValue("tbl2.BEARING") jrow.BEARING = bear jrows.updateRow(jrow) arcpy.RemoveJoin_management(tbl1, tbl2) del jrow del jrows
def JoinAndCalc(inputDataset, inputJoinField, joinTable, joinTableJoinField, copyFields): try: inputLayer = "inputLayer" arcpy.MakeFeatureLayer_management(inputDataset, inputLayer) joinTableDesc = arcpy.Describe(joinTable) joinName = str(joinTableDesc.name) arcpy.AddJoin_management(inputLayer, inputJoinField, joinTable, joinTableJoinField) removeJoin = True tz = time.timezone # num of seconds to add to GMT based on current TimeZone ## fields = arcpy.ListFields(inputLayer) ## for field in fields: ## print("{0} is a type of {1} with a length of {2}" ## .format(field.name, field.type, field.length)) for copyField in copyFields: if len(copyField) == 3: dateExp = "import time\\nimport datetime\\nfrom time import mktime\\nfrom datetime import datetime\\ndef calc(dt):\\n return datetime.fromtimestamp(mktime(time.strptime(str(dt), '" + str( copyField[2]) + "')) + time.timezone)" exp = 'calc(!' + joinName + '.' + copyField[0] + '!)' arcpy.CalculateField_management(inputLayer, copyField[1], exp, 'PYTHON_9.3', dateExp) else: arcpy.CalculateField_management( inputLayer, copyField[1], '!' + joinName + '.' + copyField[0] + '!', "PYTHON_9.3", "") print copyField[0] + " Calculated from " + copyField[1] arcpy.RemoveJoin_management(inputLayer, joinName) except arcpy.ExecuteError: line, filename, synerror = trace() raise UtilitiesError({ "function": "JoinAndCalc", "line": line, "filename": filename, "synerror": synerror, "arcpyError": arcpy.GetMessages(2), }) except: line, filename, synerror = trace() raise UtilitiesError({ "function": "JoinAndCalc", "line": line, "filename": filename, "synerror": synerror, })
def aggregate_all_zonalTables(): # Initialize local variables merge_list =[] # Only if entering the number of tables manually num_of_score_tables=16 for j in range(num_of_score_tables): merge_list.append("lts3_with_CII_scores_table"+ str(j+1)) print(merge_list) arcpy.Merge_management(merge_list, "merged_lts3_with_CII_scores_table") arcpy.AddJoin_management("lts3_top30pct", "EDGE", "merged_lts3_with_CII_scores_table", "EDGE", "KEEP_ALL") arcpy.CopyFeatures_management("lts3_top30pct", "aggregated_lts3_top30pct_with_cii_scores") # Remove the join and delete lts3_unprocessed arcpy.RemoveJoin_management("lts3_top30pct")
def join_node_summary(lyrInputSegments, node_type, lyrNodesToSegments, LineOID, tempWorkspace): NODES = "NODES_{0}".format(node_type) tblNodeSummary = gis_tools.newGISDataset(tempWorkspace, "tblNode{0}Summary".format(node_type)) viewNodeSummary = "viewNode{0}Summary".format(node_type) arcpy.SelectLayerByAttribute_management(lyrNodesToSegments, "NEW_SELECTION", """"NODE_TYPE" = '{0}'""".format(node_type)) arcpy.Statistics_analysis(lyrNodesToSegments, tblNodeSummary, [["NODE_TYPE", "COUNT"]], LineOID) arcpy.SelectLayerByAttribute_management(lyrNodesToSegments, "CLEAR_SELECTION") arcpy.AddField_management(lyrInputSegments, NODES, "TEXT") arcpy.MakeTableView_management(tblNodeSummary, viewNodeSummary) arcpy.AddJoin_management(lyrInputSegments, LineOID, viewNodeSummary, LineOID, "KEEP_COMMON") arcpy.CalculateField_management(lyrInputSegments, NODES, '"!COUNT_NODE_TYPE!"', "PYTHON_9.3") arcpy.RemoveJoin_management(lyrInputSegments) return
def copy_vaa_values(fc, vaa_table_location, vaa_fields): vaa_table_name = vaa_table_location[vaa_table_location.rfind('/') + 1::] arcpy.AddJoin_management(in_layer_or_view=fc, in_field="NHDPlusID", join_table=vaa_table_location, join_field="NHDPlusID", join_type="KEEP_COMMON") for field in vaa_fields: fieldname = field[0] arcpy.CalculateField_management(in_table=fc, field=fieldname, expression='[' + vaa_table_name + '.{0}]'.format(field[0])) arcpy.AddMessage(field[0] + ' field added.') arcpy.RemoveJoin_management(in_layer_or_view=fc)