Skip to content

Instantly share code, notes, and snippets.

@jdbcode
Last active January 13, 2022 17:19
Show Gist options
  • Save jdbcode/2117c512f2a8bd8c2a20555fba90a61b to your computer and use it in GitHub Desktop.
Save jdbcode/2117c512f2a8bd8c2a20555fba90a61b to your computer and use it in GitHub Desktop.
Demo for calculating raster zonal statistics for many zones in parallel using Google Earth Engine.
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "ee_zonal_stats_demo.ipynb",
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/jdbcode/2117c512f2a8bd8c2a20555fba90a61b/ee_zonal_stats_demo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"source": [
"# Earth Engine setup.\n",
"import ee\n",
"ee.Authenticate()\n",
"ee.Initialize()"
],
"metadata": {
"id": "3Cb8cjxESqO3"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0M6v43DjRI9p"
},
"outputs": [],
"source": [
"# Import raster image.\n",
"dem = ee.Image('NASA/NASADEM_HGT/001')\n",
"\n",
"# Import feature collection of watersheds (zones) (50 zones for demo).\n",
"zones = ee.FeatureCollection(\"WWF/HydroSHEDS/v1/Basins/hybas_9\").limit(50)\n",
"\n",
"# Calculate zonal stats (mean and median).\n",
"stats = dem.reduceRegions(**{\n",
" \"collection\": zones,\n",
" \"reducer\": ee.Reducer.mean().combine(ee.Reducer.median(), None, True),\n",
" \"scale\": 30\n",
"})\n",
"\n",
"# Export the result as a CSV file to Google Drive.\n",
"task = ee.batch.Export.table.toDrive(**{\n",
" \"collection\": stats,\n",
" \"description\": \"ee_demo_zonal_stats\",\n",
" \"folder\": \"ee_demo\",\n",
" \"fileNamePrefix\": \"ee_demo_zonal_stats\",\n",
" \"fileFormat\": \"CSV\",\n",
" \"selectors\": [\"HYBAS_ID\", \"elevation_mean\", \"elevation_median\"]\n",
"})\n",
"task.start()"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment