Friday, 12 July 2019

arcpy - Performing table look-up using Python in ArcGIS Desktop?


Using ArcGIS 10.1 the arcpy module has a TableToNumPyArray command, which converts a table into an array.



Unfortunately I don't have access to 10.1 on my work PC. Is there a workaround which will accomplish this using ArcGIS 10.0?


Background


I'm iterating through features in a featureclass, and I need to look-up a price depending on an attribute value.


I need to find a price for multiple fields per feature, so I can't use a table join. I can't create a relationship class as I only have an ArcView license.


A messy workaround could be to load the table into a searchCursor and iterate through each record until I find the desired value. But this would be intensive as I'd need to work through the searchCursor for every feature in the featureclass.



Answer



A workaround for not having the TableToNumPyArray command would be this:



  • First, iterate through all features in your feature class, and store the price data in a Python dictionary.

  • Second, iterate again through all features in your feature class, and just lookup your price data from the dictionary.



Instead of the processing time for n features being n*n, it will just be n*2. Here's some code:


import arcpy

PriceDictionary = {}

MyCursor = arcpy.SearchCursor("MyLayer")
for Feature in MyCursor:
PriceDictionary[Feature.getValue("ID")] = Feature.getValue("Price")
del Feature

del MyCursor

LookupCursor = arcpy.UpdateCursor("MyLayer")
for Feature in LookupCursor:
Feature.setValue("NewPrice",PriceDictionary[Feature.getValue("LookupField")])
del Feature
del LookupCursor

If you're not familiar with dictionaries, check out this tutorial on dictionaries. For reference, using Python dictionaries and other data structures in clever ways is often much faster than using their arcpy counterparts. If your script is going slowly, try to remove as many arcpy commands as you can.


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...