使用ArcPy Statistics_analysis计算平均值,in_memory

时间:2015-09-04 16:51:09

标签: python arcgis arcpy

因此,在所选值中要计算中值。

arcpy.env.workspace = r"Database Connections\local.sde"
pLoc = "local.DBO.Parcels"
luLoc = "local.DBO.Land_Use"
luFields = ["MedYrBlt","MedVal","OCCount"]
arcpy.MakeFeatureLayer_management(pLoc,"cities_lyr")
arcpy.SelectLayerByAttribute_management("cities_lyr", "NEW_SELECTION", "YrBlt > 1000")
来自所选cities_lyr的

想要从YrBlt计算平均值字段

with arcpy.da.SearchCursor(luLoc, ["OID@", "SHAPE@", luFields[0], luFields[1], luFields[2]]) as cursor:
   for row in cursor:
      if arcpy.Exists('in_memory/stats'):
        arcpy.Delete_management(r'in_memory/stats')
      arcpy.SelectLayerByLocation_management('cities_lyr', select_features = row[1])
      arcpy.Statistics_analysis('cities_lyr', 'in_memory/stats','YrBlt MEAN','OBJECTID')

这是一个问题: 我只是想看看平均值,我该怎么做?

luFields = ["MedYrBlt","MedVal","OCCount"] 

以后会用到现在不重要的。

1 个答案:

答案 0 :(得分:1)

将值附加到空数组,然后计算该数组的平均值。例如:

# Create array & cycle through years, append values to array
yrArray =[]
for row in cursor:
    val = getValue("yrBlt")
    yrArray.append(val)

#get sum of all values in array
x = 0
for i in yrArray: 
    x += i

#get average by dividing above sum by the length of the array. 
meanYrBlt = x / len(yrArray)

另一方面,将这些流程分成各自的类可能是有益的。例如:

class arrayAvg: 
    def __init__(self,array):
        x = 0
        for i in array:
            x += 1
        arrayLength = len(array)
        arrayAvg = x/arrayLength
        self.avg = arrayAvg
        self.count = arrayLength

这样您可以通过调用:

重用代码
yrBltAvg = arrayAvg(yrArray)
avg = yrBltAvg.avg #returns average
count = yrBltAvg.count #returns count

第二部分是不必要的,但允许您利用面向对象的编程,并且您可以在整个程序中进行扩展。