Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

The attached script is my stalled attempt to perform the following workflow:

  1. Create a table and create fields
  2. Loop through a folder of point shapefiles and perform average nearest neighbor analysis
  3. Create a row and write "nn_values[]" to the corresponding fields
  4. move to the next shapefile and repeat

The script successfully produces a table, runs the aNN analysis for a shapefile and adds an empty row to the table. As an end-product, I would like a table with all of the values from the statistical analysis. How can I write the associated aNN statistical output (i.e. "nn_values[]") to the corresponding fields for each iteration in the for loop? Many thanks for the guidance.

# Import system modules
import arcpy, os
from arcpy import env

# Set over write
env.overwriteOutput = 1

# Local variables...
env.workspace = r"C:\temp"
Dir = env.workspace
out_name = "NNtable.dbf"

### Execute CreateTable
arcpy.CreateTable_management(Dir, out_name)

### Add fields
arcpy.AddField_management(Dir + "\\" + out_name, "index", "FLOAT")
arcpy.AddField_management(Dir + "\\" + out_name, "z_score", "FLOAT")
arcpy.AddField_management(Dir + "\\" + out_name, "p_value", "FLOAT")
arcpy.AddField_management(Dir + "\\" + out_name, "expected", "FLOAT")
arcpy.AddField_management(Dir + "\\" + out_name, "observed", "FLOAT")
arcpy.AddField_management(Dir + "\\" + out_name, "pathway", "TEXT")

# List FCs

fclist = arcpy.ListFeatureClasses()

for fc in fclist:
    try:

        # Obtain Nearest Neighbor Ratio and z-score
        # Process: Average Nearest Neighbor...
        nn_output = arcpy.AverageNearestNeighbor_stats(fc, "EUCLIDEAN_DISTANCE", "NO_REPORT", "#")

        # Create list of Average Nearest Neighbor output values by splitting the result object
        nn_values = nn_output.split(";")
        print "The nearest neighbor index is: " + nn_values[0]
        print "The z-score of the nearest neighbor index is: " + nn_values[1]
        print "The p-value of the nearest neighbor index is: " + nn_values[2]
        print "The expected mean distance is: " + nn_values[3]
        print "The observed mean distance is: " + nn_values[4]
        print "The path of the HTML report: " + nn_values[5]

    except:
        # If an error occurred when running the tool, print out the error message.
        print arcpy.GetMessages()

    # Create insert cursor for table 
    # 
    rows = arcpy.InsertCursor(Dir + "\\" + out_name) 
    row = rows.newRow() 
    rows.insertRow(row) 

    # Delete cursor and row objects to remove locks on the data  
    del row 
    del rows
share|improve this question

1 Answer 1

up vote 2 down vote accepted

NOTE:

The ESRI documentation does not seem to accurately represent a way to get information out of the Average Nearest Neighbor tool. Some changes were made below to reflect what values can be derived from the results.

You basically just need to make a few attribute assignments that correspond to your newly created fields in your loop. See below:

# Create insert cursor for table 
rows = arcpy.InsertCursor(Dir + "\\" + out_name) 
for fc in fclist:
    try:

        # Obtain Nearest Neighbor Ratio and z-score
        # Process: Average Nearest Neighbor...
        nn_output = arcpy.AverageNearestNeighbor_stats(fc, "EUCLIDEAN_DISTANCE", "NO_REPORT", "#")

        row = rows.newRow()
        row.nn_ratio = float(nn_output.getOutput(0))
        row.z_score = float(nn_output.getOutput(1))
        row.p_value = float(nn_output.getOutput(2))
        row.expected = float(nn_output.getOutput(3))
        row.observed = float(nn_output.getOutput(4))
        rows.insertRow(row) 

    except:
        # If an error occurred when running the tool, print out the error message.
        print arcpy.GetMessages()

del row, rows

Note that I moved your calling of the insert cursor to before the loop. This will keep it open until it has run through each feature. This will populate your table with the statistical analysis results from each featureclass. You should consider adding an additional field to your table to act as an identifier for which featureclass the results pertain to (add a "feature_name" column for example).

You can get more specifics on how to populate tables with an insert cursor here.

UPDATE:

Interesting results... I ran some test after I was getting failure, and it appears as though, despite the documentation stating otherwise, the nn_output variable does not return a semicolon delimited list, but instead it returns a single value representing the nearest neighbor ratio. To get the other outputs, you have to dig them out using nn_output.getOutput(n). Here is what I got, the first bit is the messages returned from running the tool and the second is my getOutput calls:

Observed Mean Distance:  41.780370  
Expected Mean Distance:  408.133786 
Nearest Neighbor Ratio:  0.102369   
z-score:                 -137.421360
p-value:                 0.000000  

>>> nn_output.getOutput(0)
u'0.102369'
>>> nn_output.getOutput(1)
u'-137.42136'
>>> nn_output.getOutput(2)
u'0'
>>> nn_output.getOutput(3)
u'408.133786'
>>> nn_output.getOutput(4)
u'41.78037'

As you can see, the order of the getOutputs do not follow the order of the messages. Also, I couldn't see a way to get the HTML report or nearest neighbor index. Make sure you run a test to ensure that you are populating the proper values in the right fields. I've edited my above code to reflect these findings.

share|improve this answer
    
+1 This looks good, I'll test it... –  Aaron Dec 21 '12 at 16:21
    
I'm testing it right now on 10.1 and I'm running into some issues... It appears as though the nn_ouput result doesn't return a ';' delimited list, but instead it returns one value. Let me see if I can figure out what's going on here. –  egdetti Dec 21 '12 at 16:32
    
Very interesting twist. Apparently the ESRI documentation has this one wrong. See above for my findings. –  egdetti Dec 21 '12 at 16:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.