Google Earth Engine – Function to Compute Zonal Statistics in Python API

google-earth-enginegoogle-earth-engine-python-api

I am trying to create a zonal_statistics function in Google Earth Engine Python API.

The function should be applied to an object of type ee.Image and should receive two arguments: an ee.FeatureCollection and a reducer (e.g. ee.Reducer.mean()).

The function must return an object of type GeoDataFrame with the statistics of each polygon.

import ee
import geopandas as pd

# image -- is a ee.Image object
# features -- is a ee.FeatureCollection object

zone_stats = image.reduceRegions(collection=features, reducer=ee.Reducer.mean(), scale=10).getInfo()
zone_stats = gpd.GeoDataFrame.from_features(zone_stats, crs='epsg:4326')

How can I integrate this process in a single function?

Best Answer

Just put the code inside def statement

def zonal_stats(image,features, stats):
    if not isinstance(image, ee.Image):
        print("The input image must be an ee.Image.")
        return
    if not isinstance(features, ee.FeatureCollection):
        print("The input features must be an ee.FeatureCollection.")
        return
    reducers = {
        "COUNT": ee.Reducer.count(),
        "MEAN": ee.Reducer.mean(),
        "MAXIMUM": ee.Reducer.max(),
        "MEDIAN": ee.Reducer.median(),
        "MINIMUM": ee.Reducer.min(),
        "MODE": ee.Reducer.mode(),
        "STD": ee.Reducer.stdDev(),
        "SUM": ee.Reducer.sum(),
        "VARIANCE": ee.Reducer.variance()}
    zone_stats = image.reduceRegions(collection=features, reducer=reducers[stats.upper()], scale=10).getInfo()
    zone_stats = gpd.GeoDataFrame.from_features(zone_stats, crs='epsg:4326')
    return zone_stats
Related Question