POST
|
My code loops through layers in multiple projects and prints the highest values for a specific field. I want to then append those values to an empty dictionary, but when I try and print the dictionary at the end of the code it is still empty. I've been trying to figure this out for a couple days now, but can't seem to figure it out myself or find a solution online. Any help or suggestions would be greatly appreciated. Thanks. import arcpy
from arcpy import env
markets = [3000]
### Declare variables
fc = 'OpenCenters'
fields = ['USER_market_id','USER_ID','USER_Center_Name','USER_Opening_Date']
fieldname = 'USER_market_id'
sqlclause = (None, 'Order By USER_market_id, USER_ID')
for market in markets:
print(market)
results_dict = {}
env.workspace = r"E:\arcGIS_Shared\Python\HeatMaps_{0}\HeatMaps_{0}.gdb".format(market)
## Define WHERE clause statement
whereclause = """{} = """.format(arcpy.AddFieldDelimiters(fc, fieldname)) + str(market)
### Cursor to create list of centers to loop through
with arcpy.da.SearchCursor(in_table = fc, field_names = fields, where_clause=whereclause, sql_clause=sqlclause) as cursor:
###Loop to run SummarizeWithin by center
for row in (cursor):
p = arcpy.mp.ArcGISProject(r'E:\arcGIS_Shared\Python\HeatMaps_{0}\DiscreteHeatMaps{0}_{1}.aprx'.format(market, row[2]))
m = p.listMaps()[0]
Layers = m.listLayers("DiscreteVisitsSumWithin{0}_{1}*".format(market, row[2]))
fields = ['SUM_USER_VisitCount']
for Layer in Layers:
try:
sqlClause = (None, 'ORDER BY ' + 'SUM_USER_VisitCount')
with arcpy.da.SearchCursor(in_table = Layer, field_names = fields,
sql_clause = sqlClause) as searchCursor:
print(max(searchCursor))
results_dict[Layer] = max(searchCursor)
except:
pass
print(results_dict)
... View more
04-19-2019
09:09 AM
|
0
|
4
|
974
|
POST
|
I was looking for an arcpy function related to Symbology, but if that doesn't exist then I may just need to symbolize my feature classes by hand and then save them as a layer file. That way I could use my apply symbology from layer script for future projects where I need to use the picture marker symbols.
... View more
09-21-2018
04:48 AM
|
0
|
1
|
785
|
POST
|
Hi, I've been looking for python code that would be able to assign a PNG image as the logo/symbol for an ArcGIS Pro feature class; but I have been unable to find any examples of this being done. Is this possible using python/arcpy? If so, could someone please share the documentation/code with me?
... View more
09-20-2018
10:46 AM
|
0
|
4
|
1157
|
POST
|
Hey Dan, Thanks for responding. I added some print statement like you suggested, and it looks like the script runs fine until line 41. I also got the following error: I think the reason why my code was being "skipped" earlier was because it is meant to be run an a FC with single symbol symbology, and I had forgotten to reset it to that when I was testing.
... View more
09-13-2018
10:19 AM
|
0
|
1
|
703
|
POST
|
I have a python script that finds the feature class with the highest count for a field called 'SUM_USER_VisitCount' and then creates the symbology I specify. What I then want to do is save this feature class as a lyrx file, but the code I have for this seems to get skipped over. Can someone help me figure out what I'm doing wrong? Here is a section of my code (let me know if you need to see the whole code): ### get key for dictionary item with the highest value
highest_count_layer = max(results_dict, key=results_dict.get)
print(highest_count_layer)
print(results_dict[highest_count_layer])
#print(results_dict)
for row in searchCursor:
Symbology_Layer = highest_count_layer
sym = Symbology_Layer.symbology
if hasattr(sym, 'renderer'):
if sym.renderer.type == 'SimpleRenderer':
sym.updateRenderer('GraduatedColorsRenderer')
sym.renderer.classificationField = 'SUM_USER_VisitCount'
sym.renderer.breakCount = 5
sym.renderer.colorRamp = p5.listColorRamps('Orange-Red (Continuous)')[0]
### Remove decimal places from labels
if sym.renderer == "GraduatedColorsRenderer":
breaks = sym.renderer.classBreaks
for b in breaks:
b_int = b.label[0:-7]
b.label = b_int
### Thousands Separators in labels
def FindLabel (b):
return "{:,}".format(float(b))
Symbology_Layer.symbology = sym
p5.save()
### Where lyrx will be saved
arcpy.env.workspace = r"E:\arcGIS_Shared\Python\Symbology Layers"
### Set local variables
in_layer = Symbology_Layer
out_layer_file = r"E:\arcGIS_Shared\Python\Symbology Layers\SGF_CumulativeSymbology.lyrx"
arcpy.management.SaveToLayerFile(in_layer, out_layer_file, "ABSOLUTE")
print('Lyrx file saved')
... View more
09-13-2018
08:13 AM
|
0
|
3
|
964
|
POST
|
Hi, I have a Feature Class to Feature Class script that is supposed to take a Feature Class (FC) of locations and create a separate FC for each location. However, it keeps giving me the following two errors. ERROR 000210: Cannot create output E:\arcGIS_Shared\Business Analyst\PotentialCitePackages.gdb\NorthEdmond
ERROR 000354: The name contains invalid characters
Failed to execute (FeatureClassToFeatureClass) Here is the FC to FC script: inFeatures = "PythonTest_Geocoded"
fields = ['ObjectID', 'Shape','USER_Center']
with arcpy.da.SearchCursor(inFeatures, fields) as cursor:
for row in cursor:
outLocation = r"E:\arcGIS_Shared\Business Analyst\PotentialCitePackages.gdb"
outFeatureClass = "{0}".format(row[2])
delimitedField = arcpy.AddFieldDelimiters(env.workspace, "USER_Center")
expression = delimitedField + " = '{0}'".format(row[2])
print(expression)
## Execute FeatureClassToFeatureClass
arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, outFeatureClass, expression) The output FCs are supposed to be named after their corresponding locations ('USER_Center"). This field contains no invalid characters, as you can see below (I was testing this code on a table with only 3 rows). Could someone help me figure out what I'm doing wrong/missing? Thanks.
... View more
08-03-2018
08:34 AM
|
0
|
3
|
2424
|
POST
|
Hi, I have a map that shows the location of one of my stores, as well as points representing customer addresses. My question is. Is there a way to create a buffer around a certain percentage of the customers that are closest to the store? For example, a buffer that encompasses 80% of the customers that are closest to the store. Here is a screenshot of what my map looks like right now: - Blue Dots = customers - Orange/White/Blue image = store If this is not possible with points, could something similar be done with polygons? For example, only show the Block Groups that contain 80% of customers that are closest to the store? It may be helpful to know that I'm working in ArcMap and have access to Business Analyst, Spatial Analyst, and Network Analyst. Any help/advice would be greatly appreciated. Thanks
... View more
05-17-2018
08:35 AM
|
0
|
1
|
512
|
POST
|
Hi Jake, Thanks for responding. I have posted a script I use for creating and exporting PDFs. Towards the bottom of the script I try and use the arcpy.Delete_management and the garbage collector.
... View more
04-25-2018
12:10 PM
|
0
|
1
|
2571
|
POST
|
Some of the Python scripts I run can take 24 - 78 hours to complete. During the beginning stages, these scripts consume a reasonable amount of Memory (about 16% - 20%). But the longer they run the more Memory they consume, until Task Manager says that 99% of the Memory is being used. (Just to clarify, this is Memory not CPU). I recently learned about garbage collection in Python, but that has not seemed to fix the problem. I have also tried arcpy.Delete_management but that has not solved the problem either. Does anyone know how to keep the Memory from continuously building up? Here is an example of some code where I incorporated garbage collection and arcpy.Delete_management: import arcpy
import time
import datetime
from datetime import timedelta
import gc
#Document Start Time in-order to calculate Run Time
time1 = time.clock()
#project location
p = arcpy.mp.ArcGISProject(r'C:\arcGIS_Shared\Python\CenterHeatMaps4.aprx')
#Name of layout that the PDFs will be based on
lyt = p.listLayouts("Layout_King")[0]
#second object is the name of the mapframe in the project
mf = lyt.listElements("MAPFRAME_ELEMENT", "Map*")[0]
bkmks = mf.map.listBookmarks()
m = p.listMaps()[0]
#layers to be used in the PDFs
OnLyrList = m.listLayers('Topographic')
OnNxtList = m.listLayers('OpenCenters')
OnList = m.listLayers('SumWithin1000*')
####Loop through all bookmarks until finding a match for the active center
for bkmk in bkmks:
#Turn off all layers
lyrList = m.listLayers()
for lyr in lyrList:
lyr.visible = False
#Turn on desired layers
for lyr in OnLyrList:
lyr.visible = True
for lyr in OnNxtList:
lyr.visible = True
for lyr in OnList:
lyr.visible = True
#Zoom to active bookmark
mf.zoomToBookmark(bkmk)
### Zoom in or out further from bookmark
mf.camera.scale = mf.camera.scale * 1.50
#Change Layout Title
for elm in lyt.listElements("TEXT_ELEMENT"):
elm.text = "Zip Code Out 50 Percent - " + bkmk.name #[22:]
#Export to PDF
lyt.exportToPDF(r"C:\arcGIS_Shared\Python\Export\Geographic_Boundaries" + "\\Zip Code Out 50 Percent " + bkmk.name + ".pdf") #+ "\\NY"
print(bkmk.name)
### Clear Memory
arcpy.Delete_management(r"C:\arcGIS_Shared\Python\Export\CensusTracts")
del lyrList, OnList, OnLyrList, OnNxtList
gc.collect()
#Document End Time
time2 = time.clock()
#Run Time in seconds
runtime = (time2-time1)
#Print total run time for the job
print (str(timedelta(seconds=runtime)))
... View more
04-25-2018
10:56 AM
|
0
|
3
|
5336
|
POST
|
Hi, The following code takes PDFs and appends them to a title page, creating a PDF MapBook. However, I can't figure out how to get the PDFs in the right order. I want the PDFs to be ordered by the month and year specified in the files (last 6 characters), rather than just alphabetical order of the whole file name. I am specifying the month using its numeric value (Example: CTDiscreteSumWithin4000_Avon_2017_5), I don't know whether than makes things easier or harder. import arcpy
import os
arcpy.env.workspace = r"C:\arcGIS_Shared\Python\Export\Discrete_CT"
path = r"C:\arcGIS_Shared\Python\Export\Discrete_CT"
### Create the PDF MapBook file
CTpdfPath = os.path.join(path, 'Avon_DiscreteHeatMaps.pdf')
CTpdfDoc = arcpy.mp.PDFDocumentCreate(CTpdfPath)
###List all files to be added to MapBook
CTpdfList = arcpy.ListFiles("CTDiscreteSumWithin4000_Avon*")
### Add market title page to the newly created PDF document
CTpdfDoc.appendPages(os.path.join(path, "CTTitlePage.pdf"))
### Append market specific pages to the PDF
for CTpdf in CTpdfList:
CTpdfDoc.appendPages(r"C:\arcGIS_Shared\Python\Export\Discrete_CT\%s"%CTpdf)
print(CTpdf)
CTpdfDoc.saveAndClose() Any help/advice would be appreciated. Thanks.
... View more
04-06-2018
06:11 AM
|
0
|
1
|
423
|
POST
|
Thanks for the quick response Blake. I'm not sure this is exactly what I'm looking for though. Maybe I should explain a little more. Ideally, it would be great if after I run my summarize within script, it takes the output feature class and adds it to the contents pane. For example: # import system modules
import arcpy
# Set environment settings
arcpy.env.workspace = 'C:/data/city.gdb'
# Set local variables
polys = 'neighborhoods'
points = 'crimes'
outFeatureClass = 'crimes_aggregated'
keepAll = 'KEEP_ALL'
sumFields = [['Damages', 'SUM'], ['VICTIM_AGE', 'MEAN']]
addShapeSum = 'ADD_SHAPE_SUM'
groupField = 'Crime_type'
addMinMaj = 'ADD_MIN_MAJ'
addPercents = 'ADD_PERCENT'
outTable = 'crimes_aggregated_groups'
arcpy.SummarizeWithin_analysis(polys, points, outFeatureClass, keepAll,
sumFields, addShapeSum, '', groupField,
addMinMaj, addPercents, outTable) So after the "arcpy.SummarizeWithin_analysis()" I would like to add a piece of code that would take that feature class that was just created and move it to the contents pane.
... View more
02-26-2018
07:50 AM
|
0
|
1
|
671
|
POST
|
I have a need for some ArcPy code that will allow me to move feature classes in my File Geodatabase to the Table of Contents in my ArcGIS Pro project. However, I have no idea how to do this and I can not find any examples of this online. Is this possible? Could someone please show me how to do this?
... View more
02-26-2018
07:21 AM
|
0
|
3
|
863
|
Title | Kudos | Posted |
---|---|---|
1 | 12-18-2017 07:43 AM | |
1 | 11-20-2017 07:14 AM | |
2 | 12-22-2017 05:12 AM | |
1 | 12-18-2017 01:04 PM | |
1 | 01-04-2018 12:15 PM |
Online Status |
Offline
|
Date Last Visited |
07-15-2022
02:04 PM
|