1

I want to calculate the mean value in the field z which has Type Zero and write it in Ground field.

How can I do that with arcpy?

enter image description here

arcpy.MakeFeatureLayer_management(Shapefile, "layer")
arcpy.SelectLayerByAttribute_management("layer", "NEW_SELECTION","Type = 0")
arcpy.CalculateField_management("layer", "Ground", "mean(!{0}!)".format("Z"), "PYTHON_9.3")

I have got error for this code.

3

In this example, a Search Cursor is used within a list comprehension to collect all of the Z values if Type == 0. np.mean() is used to find the mean value within the list.

Once the mean value is determined, use an Update Cursor to write the mean value to the Ground field if Type == 0.

import arcpy
import numpy as np

fc = r'C:\temp\temp.gdb\some_featureclass'

# Find the mean value for the "Z" field if "Z" == 0
val = np.mean([x[0] for x in arcpy.da.SearchCursor(fc, ("Z", "Type")) if x[1] == 0])

# Write the value to the "Ground" field if "Type" == 0
with arcpy.da.UpdateCursor(fc, ["Type", "Ground"]) as cursor:
    for row in cursor:
        if row[0] == 0:
            row[1] = val
        cursor.updateRow(row) 

enter image description here

2

Your approach won't work, as you are trying to apply a mean over a set of selected records to a each of the selected rows. but you need to have computed the mean prior to this calculation. A better way is to run your data through the Summary statistics tool grouping by your type field. You can then join the resulting table to your original layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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