如需减少 FeatureCollection
中地图项的属性,请使用 featureCollection.reduceColumns()
。请考虑以下玩具示例:
// 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
# 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()
提供求和归约器参数并输出结果来获取它们的总和:
// 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
# 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
,表示根据指定的 reducer 汇总的属性:
sum: [85579,36245]
请注意,上述示例使用 notNull()
过滤器,仅包含被缩减集合中所选属性的非 null 条目的地图项。最好检查是否有 null 条目,以捕获意外缺失的数据,并避免因包含 null 值的计算而导致错误。
另请注意,与 imageCollection.reduce()
不同(其中会自动针对每个波段重复 reducer),FeatureCollection
上的 reducer 必须使用 repeat()
显式重复。具体而言,对于 m 个输入,重复 m 次 reducer。由于未重复 reducer,系统可能会抛出以下错误: