Saturday, 18 April 2015

arcgis 10.1 - Map automation to iterate through attribute table using ArcPy?


I have a python code which iterates through all attribute fields and creates a map for each field automatically. However, in the code I have to specify each attribute manually which was fine so far. Now I have an attribute table with many fields and I need a way to do the same without specifying the attributes manually (as done with "Attrlist" in the code. Any suggestions?



This is the code I am using so far:


outPath = "D:\\Atlas\\test\MxdMaps\\Mxd_MapAutomation\\"   
# list of attributes with the same datatype
attrlist = ["EthnicGroups_totnumberoffarmhh_txt_WNHDeAA01",
"EthnicGroups_totnumberoffarmhh_txt_WNHDeAA02",
"EthnicGroups_totnumberoffarmhh_txt_WNHDeAA03"]
# layer which has to change the attribute field
featurelayer = arcpy.mapping.ListLayers(mxd, "EthnicGroups_totnroffarmhh")[0]
# text element that has to change (e.g. title...)
title = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "map_title")[0]

for attr in attrlist:
#if featurelayer.symbologyType == "GRADUATED_COLORS":
#print attr
# change value field
featurelayer.symbology.valueField = attr
#featurelayer.symbology.addAllValues()
featurelayer.symbology.reclassify()
#print "Break values: %s" % featurelayer.symbology.classBreakValues
# change tilte
title.text = attr

# update view
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
# export as jpeg
outJPEG = os.path.join(outPath, attr + ".jpg")
arcpy.mapping.ExportToJPEG(mxd, outJPEG, "PAGE_LAYOUT", 200, 200, 300, False, "24-BIT_TRUE_COLOR", 90, False)
# export as AdobeIllustrator .ai
#outAI = os.path.join(outPath, attr + ".ai")
#arcpy.mapping.ExportToAI(mxd, outAI, "PAGE_LAYOUT", 200, 200, 300, "BEST", "RGB", "VECTORIZE_BITMAP", False)
del mxd


Answer



arcpy.ListFields() will give you a list of objects. You just need to get the names from those objects.


field_names = [f.name for f in arcpy.ListFields(lyr)]

Another round about way of getting them would be via a search cursor but that also includes the shape field.


field_names = []
with arcpy.da.SearchCursor(lyr,"*") as cursor:
field_names = cursor.fields

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...