如要減少 FeatureCollection
中功能的屬性,請使用 featureCollection.reduceColumns()
。請參考以下玩具範例:
程式碼編輯器 (JavaScript)
// Make a toy FeatureCollection. var aFeatureCollection = ee.FeatureCollection([ ee.Feature(null, {foo: 1, weight: 1}), ee.Feature(null, {foo: 2, weight: 2}), ee.Feature(null, {foo: 3, weight: 3}), ]); // Compute a weighted mean and display it. print(aFeatureCollection.reduceColumns({ reducer: ee.Reducer.mean(), selectors: ['foo'], weightSelectors: ['weight'] }));
import ee import geemap.core as geemap
Colab (Python)
# Make a toy FeatureCollection. a_feature_collection = ee.FeatureCollection([ ee.Feature(None, {'foo': 1, 'weight': 1}), ee.Feature(None, {'foo': 2, 'weight': 2}), ee.Feature(None, {'foo': 3, 'weight': 3}), ]) # Compute a weighted mean and display it. display( a_feature_collection.reduceColumns( reducer=ee.Reducer.mean(), selectors=['foo'], weightSelectors=['weight'] ) )
請注意,系統會根據指定的 weight
屬性為輸入內容加權。因此結果如下:
mean: 2.333333333333333
舉例來說,假設您有一個 FeatureCollection
的美國人口普查區塊,並將人口普查資料做為屬性。我們要分析的變項是總人口和總住宅單位。您可以將加總縮減器引數提供給 reduceColumns()
,然後列印結果,藉此取得加總值:
程式碼編輯器 (JavaScript)
// Load US census data as a FeatureCollection. var census = ee.FeatureCollection('TIGER/2010/Blocks'); // Filter the collection to include only Benton County, OR. var benton = census.filter( ee.Filter.and( ee.Filter.eq('statefp10', '41'), ee.Filter.eq('countyfp10', '003') ) ); // Display Benton County census blocks. Map.setCenter(-123.27, 44.57, 13); Map.addLayer(benton); // Compute sums of the specified properties. var properties = ['pop10', 'housing10']; var sums = benton .filter(ee.Filter.notNull(properties)) .reduceColumns({ reducer: ee.Reducer.sum().repeat(2), selectors: properties }); // Print the resultant Dictionary. print(sums);
import ee import geemap.core as geemap
Colab (Python)
# Load US census data as a FeatureCollection. census = ee.FeatureCollection('TIGER/2010/Blocks') # Filter the collection to include only Benton County, OR. benton = census.filter( ee.Filter.And( ee.Filter.eq('statefp10', '41'), ee.Filter.eq('countyfp10', '003') ) ) # Display Benton County census blocks. m = geemap.Map() m.set_center(-123.27, 44.57, 13) m.add_layer(benton) display(m) # Compute sums of the specified properties. properties = ['pop10', 'housing10'] sums = benton.filter(ee.Filter.notNull(properties)).reduceColumns( reducer=ee.Reducer.sum().repeat(2), selectors=properties ) # Print the resultant Dictionary. display(sums)
輸出內容是 Dictionary
,代表根據指定的縮減器匯總的屬性:
sum: [85579,36245]
請注意,上述範例使用 notNull()
篩選器,只納入集合中所選屬性非空值的項目,以便減少特徵數量。建議您檢查空值項目,以便找出意外遺漏的資料,並避免因包含空值的計算作業而導致的錯誤。
另請注意,與 imageCollection.reduce()
不同的是,imageCollection.reduce()
會自動針對每個頻帶重複執行 reducer,但 FeatureCollection
上的 reducer 必須使用 repeat()
明確重複。具體來說,針對 m 輸入,重複執行縮減器 m 次。由於未重複使用 reducer,因此可能會擲回以下錯誤: