Reducciones agrupadas y estadísticas zonales

Puedes obtener estadísticas en cada zona de un Image o FeatureCollection con reducer.group() para agrupar el resultado de un reductor según el valor de una entrada especificada. Por ejemplo, para calcular la población y la cantidad de unidades de vivienda totales en cada estado, este ejemplo agrupa el resultado de una reducción de un bloque censal FeatureCollection de la siguiente manera:

Editor de código (JavaScript)

// Load a collection of US census blocks.
var blocks = ee.FeatureCollection('TIGER/2010/Blocks');

// Compute sums of the specified properties, grouped by state code.
var sums = blocks
  .filter(ee.Filter.and(
    ee.Filter.neq('pop10', null),
    ee.Filter.neq('housing10', null)))
  .reduceColumns({
    selectors: ['pop10', 'housing10', 'statefp10'],
    reducer: ee.Reducer.sum().repeat(2).group({
      groupField: 2,
      groupName: 'state-code',
    })
});

// Print the resultant Dictionary.
print(sums);

Configuración de Python

Consulta la página Entorno de Python para obtener información sobre la API de Python y el uso de geemap para el desarrollo interactivo.

import ee
import geemap.core as geemap

Colab (Python)

# Load a collection of US census blocks.
blocks = ee.FeatureCollection('TIGER/2010/Blocks')

# Compute sums of the specified properties, grouped by state code.
sums = blocks.filter(
    ee.Filter.And(
        ee.Filter.neq('pop10', None), ee.Filter.neq('housing10', None)
    )
).reduceColumns(
    selectors=['pop10', 'housing10', 'statefp10'],
    reducer=ee.Reducer.sum()
    .repeat(2)
    .group(groupField=2, groupName='state-code'),
)

# Print the resultant Dictionary.
display(sums)

El argumento groupField es el índice de la entrada en el array de selectores que contiene los códigos según los cuales se agrupan. El argumento groupName especifica el nombre de la propiedad para almacenar el valor de la variable de agrupación. Como el reducer no se repite automáticamente para cada entrada, se necesita la llamada a repeat(2).

Para agrupar el resultado de image.reduceRegions(), puedes especificar una banda de agrupación que defina los grupos por valores de píxeles enteros. A veces, este tipo de procesamiento se denomina "estadísticas zonales", en las que las zonas se especifican como la banda de agrupación y el reductor determina la estadística. En el siguiente ejemplo, el cambio en las luces nocturnas de Estados Unidos se agrupa por categoría de cobertura del suelo:

Editor de código (JavaScript)

// Load a region representing the United States
var region = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')
  .filter(ee.Filter.eq('country_na', 'United States'));

// Load MODIS land cover categories in 2001.
var landcover = ee.Image('MODIS/051/MCD12Q1/2001_01_01')
  // Select the IGBP classification band.
  .select('Land_Cover_Type_1');

// Load nightlights image inputs.
var nl2001 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F152001')
  .select('stable_lights');
var nl2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012')
  .select('stable_lights');

// Compute the nightlights decadal difference, add land cover codes.
var nlDiff = nl2012.subtract(nl2001).addBands(landcover);

// Grouped a mean reducer: change of nightlights by land cover category.
var means = nlDiff.reduceRegion({
  reducer: ee.Reducer.mean().group({
    groupField: 1,
    groupName: 'code',
  }),
  geometry: region.geometry(),
  scale: 1000,
  maxPixels: 1e8
});

// Print the resultant Dictionary.
print(means);

Configuración de Python

Consulta la página Entorno de Python para obtener información sobre la API de Python y el uso de geemap para el desarrollo interactivo.

import ee
import geemap.core as geemap

Colab (Python)

# Load a region representing the United States
region = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017').filter(
    ee.Filter.eq('country_na', 'United States')
)

# Load MODIS land cover categories in 2001.
landcover = ee.Image('MODIS/051/MCD12Q1/2001_01_01').select(
    # Select the IGBP classification band.
    'Land_Cover_Type_1'
)

# Load nightlights image inputs.
nl_2001 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F152001').select(
    'stable_lights'
)
nl_2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012').select(
    'stable_lights'
)

# Compute the nightlights decadal difference, add land cover codes.
nl_diff = nl_2012.subtract(nl_2001).addBands(landcover)

# Grouped a mean reducer: change of nightlights by land cover category.
means = nl_diff.reduceRegion(
    reducer=ee.Reducer.mean().group(groupField=1, groupName='code'),
    geometry=region.geometry(),
    scale=1000,
    maxPixels=1e8,
)

# Print the resultant Dictionary.
display(means)

Ten en cuenta que, en este ejemplo, groupField es el índice de la banda que contiene las zonas por las que se agrupará el resultado. La primera banda es el índice 0, la segunda es el índice 1, etcétera.