2012-08-08 24 views
4

使用arcpy,我的目的是將要素類存儲在列表中以供進一步處理。 每一行都將是{'field name': value}的字典,包括幾何圖形。使用arcpy在列表中加載要素類:SearchCursor的奇怪行爲

最Python的方式來實現這一任務應該是使用列表理解:

fc = '/path/to/fc' 
fields = [f.name for f in arcpy.ListFields(fc)] # get field list 
features = [[row.getValue(f) for f in fields] for row in arcpy.SearchCursor(fc)] 

此方法適用於列表中的數據,但幾何形狀都是相同的(最後在FC檢索到的幾何形狀)。 This behaviour of SearchCursor has already been commented on StackOverflow

我嘗試另一種方法:

fc = '/path/to/fc' 
shape_field = arcpy.Describe(fc).shapeFieldName 

# load geometry in a list 
geom = arcpy.Geometry() 
feat = [{shape_field: f} for f in arcpy.CopyFeatures_management(fc, geom)] # slow 

# load data in a list 
fields = [f.name for f in arcpy.ListFields(fc)] 
data = [dict([(f, row.getValue(f)) for f in fields if f != shape_field]) for row in arcpy.SearchCursor(fc)] # slow 

# merge 
merge = zip(feat, data) 
merge = [dict([(k, v) for adict in line for (k, v) in adict.items()]) for line in merge] # sorry for that... 

它與我的數據集,但:

  • 它是緩慢的。
  • 我不確定可以斷言數據和專長的順序相同是安全的。

對此有何意見?

回答

5

如果可能的話,遷移到使用10.1,您會得到arcpy.da,這是一個性能更高的遊標API。 I've written a log post on this very topic of getting dictionaries back。幾何圖形將全部相同,因爲它在內部使用循環遊標,因此在10.0中,您將想要抓取shape.__geo_interface__,並使用AsShape將其返回到幾何對象。

你行後面的順序是相當武斷,你可以期望在shape文件每次都以相同而不 WHERE子句和這差不多,所以你兩遍方法不會真的可靠。

這一切考慮,你可以做這樣的事情:

def cursor_to_dicts(cursor, field_names): 
    for row in cursor: 
     row_dict = {} 
     for field in field_names: 
      val = row.getValue(field) 
      row_dict[field] = getattr(val, '__geo_interface__', val) 
     yield row_dict 

fc = '/path/to/fc' 
fields = [f.name for f in arcpy.ListFields(fc)] # get field list 
features = list(cursor_to_dicts(arcpy.SearchCursor(fc), fields)) 

的法寶是getattr()呼叫 - 試圖抓住value.__geo_interface__如果它存在,否則只是默認爲value

由於這個問題並不是真的關於Python語言,而是一個特定於GIS的API(arcpy),所以在將來您可能會更好地在gis.stackexchange上提問。

+0

我並不知道arcpy.da對數據訪問來說似乎是一個很大的改進:http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000011000000。升級到10.3後,我會嘗試一下。謝謝你的提示@JasonShierer – outforawhile 2012-08-09 06:52:17

+0

...另一個選擇是使用arcpy.da.FeatureClassToNumPyArray:http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000015000000 – outforawhile 2012-08-09 07:36:18

+0

...上次編輯:我已經安裝了sp3,但在法國10.1還沒有爲我提供。我必須去'__geo_interface__'。 – outforawhile 2012-08-09 08:00:04