Cheat Sheets
Quick reference for Python, geospatial libraries and Earth Engine
Overview
Quick reference for the tools and libraries used throughout the course, most heavily on Day 1. Bookmark this page for the hands-on exercises.
Python Basics Cheat Sheet
Data Types
# Numbers
integer = 42
float_num = 3.14
# Strings
text = "Hello EO"
multiline = """Multiple
lines"""
# Lists (mutable)
coords = [14.5995, 120.9842] # Manila lat/lon
sensors = ["Sentinel-1", "Sentinel-2", "Landsat-8"]
# Tuples (immutable)
bbox = (120.0, 14.0, 121.0, 15.0)
# Dictionaries
metadata = {
"satellite": "Sentinel-2",
"date": "2025-01-15", # ISO 8601 date string
"cloud_cover": 12.5
}Control Flow
# If statements
cloud_cover = metadata["cloud_cover"]
if cloud_cover < 20:
print("Good quality image")
elif cloud_cover < 50:
print("Moderate quality")
else:
print("Too cloudy")
# For loops
for sensor in sensors:
print(f"Processing {sensor} data")
# List comprehension
scenes = [{"id": "A", "cloud": 5}, {"id": "B", "cloud": 40}]
clear_ids = [s["id"] for s in scenes if s["cloud"] < 20] # ['A']
# While loop
count = 0
while count < 10:
count += 1Functions
# Basic function
def calculate_ndvi(nir, red):
"""Calculate Normalized Difference Vegetation Index."""
return (nir - red) / (nir + red)
# Function with default arguments
def scale_reflectance(dn, scale_factor=10000):
"""Convert Sentinel-2 L2A digital numbers to surface reflectance (0-1)."""
return dn / scale_factor
# Lambda function
square = lambda x: x ** 2NumPy Cheat Sheet
Array Creation
import numpy as np
# From lists
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2], [3, 4]])
# Special arrays
zeros = np.zeros((3, 3)) # 3x3 array of zeros
ones = np.ones((2, 4)) # 2x4 array of ones
identity = np.eye(4) # 4x4 identity matrix
random = np.random.rand(3, 3) # 3x3 random [0, 1)
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = np.linspace(0, 1, 5) # 5 values from 0 to 1Array Operations
# Arithmetic (element-wise)
a + b # Addition
a - b # Subtraction
a * b # Multiplication
a / b # Division
a ** 2 # Power
# Statistics
arr.mean() # Mean
arr.std() # Standard deviation
arr.min() # Minimum
arr.max() # Maximum
arr.sum() # Sum
# Indexing
arr[0] # First element
arr[-1] # Last element
arr[1:4] # Slice indices 1-3
matrix[0, :] # First row
matrix[:, 1] # Second column
# Boolean indexing
arr[arr > 5] # Elements greater than 5Array Manipulation
# Shape operations
arr.reshape(3, 2) # Reshape to 3x2
arr.flatten() # Flatten to 1D
arr.transpose() # Transpose
# Stacking
np.vstack([a, b]) # Vertical stack
np.hstack([a, b]) # Horizontal stack
np.stack([a, b], axis=0) # Stack along axis
# Concatenation
np.concatenate([a, b])GeoPandas Cheat Sheet
Reading/Writing Vector Data
import geopandas as gpd
# Read files
gdf = gpd.read_file("data.shp")
gdf = gpd.read_file("data.geojson")
gdf = gpd.read_file("data.gpkg")
# Write files (driver is inferred from the extension)
gdf.to_file("output.gpkg") # GeoPackage (recommended)
gdf.to_file("output.geojson")
gdf.to_file("output.shp")
# GeoParquet: fast, compact, keeps the CRS
gdf.to_parquet("output.parquet")
gdf = gpd.read_parquet("output.parquet")GeoDataFrame Operations
# Inspect data
gdf.head() # First 5 rows
gdf.info() # Column info
gdf.describe() # Statistics
gdf.crs # Coordinate Reference System
gdf.geometry # Geometry column
gdf.total_bounds # Bounding box [minx, miny, maxx, maxy]
# Filtering
metro_manila = gdf[gdf["region"] == "NCR"]
large_areas = gdf[gdf.to_crs("EPSG:32651").area > 1_000_000] # > 1 km²
# Sorting
gdf.sort_values("population", ascending=False)Spatial Operations
# Coordinate Reference System
gdf.to_crs("EPSG:4326") # Reproject to WGS84
gdf.to_crs("EPSG:32651") # Reproject to UTM Zone 51N
# Geometric properties (use a projected CRS such as UTM for metres)
gdf.area # Area
gdf.length # Perimeter/length
gdf.centroid # Centroids
gdf.bounds # Bounding boxes
# Spatial relationships
gdf1.intersects(gdf2) # Intersection check
gdf1.contains(point) # Containment check
gdf1.within(polygon) # Within check
# Spatial joins
gpd.sjoin(points, polygons, how="inner", predicate="within")
# Overlay operations
gpd.overlay(gdf1, gdf2, how="intersection")
gpd.overlay(gdf1, gdf2, how="union")
gpd.overlay(gdf1, gdf2, how="difference")Visualization
# Basic plot
gdf.plot()
# Styled plot
gdf.plot(column="population",
cmap="YlOrRd",
legend=True,
figsize=(10, 8))
# Multiple layers
ax = gdf1.plot(color="blue", alpha=0.5)
gdf2.plot(ax=ax, color="red", alpha=0.5)Rasterio Cheat Sheet
Reading Raster Data
import rasterio
from rasterio.plot import show
# Open raster
with rasterio.open("image.tif") as src:
# Metadata
print(src.crs) # CRS
print(src.bounds) # Bounding box
print(src.shape) # (height, width)
print(src.count) # Number of bands
print(src.transform) # Affine transform
# Read data
band1 = src.read(1) # Read band 1
all_bands = src.read() # Read all bands
# Windowed read
window = rasterio.windows.Window(0, 0, 512, 512)
subset = src.read(1, window=window)Writing Raster Data
# Write single band
with rasterio.open(
"output.tif",
"w",
driver="GTiff",
height=data.shape[0],
width=data.shape[1],
count=1,
dtype=data.dtype,
crs="EPSG:32651",
transform=transform
) as dst:
dst.write(data, 1)
# Write multiple bands
with rasterio.open("output.tif", "w", ...) as dst:
for i, band in enumerate(bands, start=1):
dst.write(band, i)Raster Operations
# Reproject
from rasterio.warp import reproject, Resampling
reproject(
source=src_array,
destination=dst_array,
src_transform=src.transform,
src_crs=src.crs,
dst_transform=dst_transform,
dst_crs="EPSG:4326",
resampling=Resampling.bilinear
)
# Masking
from rasterio.mask import mask
with rasterio.open("image.tif") as src:
clipped, transform = mask(src, shapes, crop=True)
# Calculate indices (band numbers depend on how the file was stacked!)
with rasterio.open("sentinel2.tif") as src:
print(src.descriptions) # check band order first
red = src.read(3).astype("float32") # e.g. stack order B2, B3, B4, B8
nir = src.read(4).astype("float32")
ndvi = (nir - red) / (nir + red + 1e-10)Visualization
from rasterio.plot import show
# Single band
with rasterio.open("image.tif") as src:
show(src, cmap="gray")
# RGB composite (stack of B2, B3, B4, B8 -> R=3, G=2, B=1)
import numpy as np
with rasterio.open("image.tif") as src:
rgb = src.read([3, 2, 1]).astype("float32")
rgb = np.clip(rgb / 3000, 0, 1) # simple stretch for L2A reflectance x 10000
show(rgb)Google Earth Engine (Python API) Cheat Sheet
Initialization
import ee
# Authenticate (stores credentials; Colab shows a sign-in pop-up)
ee.Authenticate()
# Initialize with YOUR registered Cloud project (required)
ee.Initialize(project="your-cloud-project-id")See the Setup Guide for registering a noncommercial Cloud project.
Image Operations
# Load from collection
collection = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
image = collection.filterBounds(ee.Geometry.Point([121.0, 14.6])).first()
# Load a single image by ID (IDs look like DATE_DATE_TILE)
image = ee.Image(f"COPERNICUS/S2_SR_HARMONIZED/{image.get('system:index').getInfo()}")
# Select bands
rgb = image.select(["B4", "B3", "B2"])
nir = image.select("B8")
# Band math
ndvi = image.normalizedDifference(["B8", "B4"]).rename("NDVI")
# Or manually
nir = image.select("B8")
red = image.select("B4")
ndvi = nir.subtract(red).divide(nir.add(red))ImageCollection Filtering
# Spatial filter
roi = ee.Geometry.Rectangle([120.0, 14.0, 121.0, 15.0])
filtered = collection.filterBounds(roi)
# Temporal filter
filtered = collection.filterDate("2024-01-01", "2024-12-31")
# Metadata filter
low_cloud = collection.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 20))
# Combined
filtered = (collection
.filterBounds(roi)
.filterDate("2024-01-01", "2024-12-31")
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 20)))Cloud Masking
# Sentinel-2 cloud masking with Cloud Score+ (recommended)
csp = ee.ImageCollection("GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED")
def mask_s2_clouds(image):
return image.updateMask(image.select("cs_cdf").gte(0.6)) # 1 = clear
masked = (collection
.linkCollection(csp, ["cs_cdf"])
.map(mask_s2_clouds))
# Alternative for S2_SR_HARMONIZED: Scene Classification Layer
def mask_scl(image):
scl = image.select("SCL")
clear = scl.neq(3).And(scl.neq(8)).And(scl.neq(9)).And(scl.neq(10))
return image.updateMask(clear)Avoid the legacy QA60 band: in Earth Engine it is masked out for images from 25 Jan 2022 to 28 Feb 2024.
Reducers
# Temporal reduction
median = collection.median()
mean = collection.mean()
max_val = collection.max()
# Spatial reduction
mean_value = image.reduceRegion(
reducer=ee.Reducer.mean(),
geometry=roi,
scale=10
).getInfo()
# Percentile
percentile_90 = collection.reduce(ee.Reducer.percentile([90]))Compositing
# Median composite
composite = (collection
.filterBounds(roi)
.filterDate("2024-06-01", "2024-08-31")
.median())
# Quality mosaic: per pixel, take the image with the highest value of a band
# (e.g. greenest pixel by NDVI, or clearest pixel by Cloud Score+)
with_ndvi = collection.map(lambda img: img.addBands(img.normalizedDifference(["B8", "B4"]).rename("NDVI")))
greenest = with_ndvi.qualityMosaic("NDVI")Export
# Export to Drive
task = ee.batch.Export.image.toDrive(
image=ndvi,
description="NDVI_Export",
folder="EarthEngine",
fileNamePrefix="ndvi_palawan",
scale=10,
region=roi,
maxPixels=1e13
)
task.start()
# Check status
print(task.status())
# Export to Asset
task = ee.batch.Export.image.toAsset(
image=composite,
description="Composite_Export",
assetId="projects/your-cloud-project-id/assets/composite",
scale=10,
region=roi,
maxPixels=1e13
)
task.start()Visualization
# In Colab/Jupyter with geemap
import geemap
Map = geemap.Map()
Map.centerObject(roi, 10)
# Add image
vis_params = {
"bands": ["B4", "B3", "B2"],
"min": 0,
"max": 3000,
"gamma": 1.4
}
Map.addLayer(image, vis_params, "Sentinel-2")
# Add NDVI
ndvi_vis = {
"min": 0,
"max": 1,
"palette": ["red", "yellow", "green"]
}
Map.addLayer(ndvi, ndvi_vis, "NDVI")
MapSentinel Mission Quick Reference
Sentinel-1 (SAR)
| Parameter | Value |
|---|---|
| Type | C-band SAR |
| Bands | VV, VH |
| Resolution | 10m (IW mode) |
| Swath | 250 km |
| Revisit | 12-day repeat per satellite; 6 days with two (Sentinel-1C + 1D since June 2026; Sentinel-1A ended operations 30 June 2026) |
| GEE Collection | COPERNICUS/S1_GRD |
Common Applications: - Flood mapping (water detection) - Ship detection - Crop monitoring - Land subsidence
Sentinel-2 (Optical)
| Band | Name | Wavelength (nm) | Resolution (m) |
|---|---|---|---|
| B1 | Coastal aerosol | 443 | 60 |
| B2 | Blue | 490 | 10 |
| B3 | Green | 560 | 10 |
| B4 | Red | 665 | 10 |
| B5 | Red edge 1 | 705 | 20 |
| B6 | Red edge 2 | 740 | 20 |
| B7 | Red edge 3 | 783 | 20 |
| B8 | NIR | 842 | 10 |
| B8A | Narrow NIR | 865 | 20 |
| B9 | Water vapor | 945 | 60 |
| B11 | SWIR 1 | 1610 | 20 |
| B12 | SWIR 2 | 2190 | 20 |
Revisit time: 5 days at the equator with two satellites (Sentinel-2B + 2C; Sentinel-2C replaced 2A in routine operations on 21 January 2025)
GEE Collections: - COPERNICUS/S2_SR_HARMONIZED (Surface Reflectance) - COPERNICUS/S2_HARMONIZED (Top of Atmosphere)
Common Spectral Indices
NDVI (Vegetation)
# Google Earth Engine
ndvi = image.normalizedDifference(["B8", "B4"])
# NumPy/Rasterio
ndvi = (nir - red) / (nir + red)NDWI (Water)
# Green - NIR (McFeeters)
ndwi = image.normalizedDifference(["B3", "B8"])
# NIR - SWIR (Gao): vegetation water content
ndwi_gao = image.normalizedDifference(["B8", "B11"])
# Green - SWIR (Xu): modified NDWI, better for open water near built-up areas
mndwi = image.normalizedDifference(["B3", "B11"])NDBI (Built-up)
ndbi = image.normalizedDifference(["B11", "B8"])EVI (Enhanced Vegetation Index)
# EVI needs reflectance in 0-1, so scale S2 L2A values (x 10000) first
sr = image.select(["B2", "B4", "B8"]).divide(10000)
evi = sr.expression(
"2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
{
"NIR": sr.select("B8"),
"RED": sr.select("B4"),
"BLUE": sr.select("B2")
}
)Philippine Regions & Provinces
Administrative Levels
- Region (18) → Province (82) → Municipality/City → Barangay
Useful Bounding Boxes (WGS84)
| Area | Bounds [W, S, E, N] |
|---|---|
| Philippines | [116.0, 4.0, 127.0, 21.0] |
| Luzon | [119.5, 12.0, 122.5, 19.0] |
| Metro Manila | [120.9, 14.4, 121.15, 14.8] |
| Palawan | [117.0, 7.5, 120.0, 12.0] |
| Mindanao | [121.0, 5.0, 127.0, 10.0] |
Keyboard Shortcuts
Google Colab
- Run cell:
Shift + Enter - Insert cell above:
Ctrl/Cmd + M A - Insert cell below:
Ctrl/Cmd + M B - Delete cell:
Ctrl/Cmd + M D - Interrupt execution:
Ctrl/Cmd + M I - Comment/uncomment:
Ctrl/Cmd + /
Jupyter Notebook
- Run cell:
Shift + Enter - Insert cell below:
B - Insert cell above:
A - Delete cell:
D D(press D twice) - Change to markdown:
M - Change to code:
Y
Common Error Messages
“NameError: name ‘ee’ is not defined”
# Solution: import and initialise Earth Engine
import ee
ee.Initialize(project="your-cloud-project-id")“ModuleNotFoundError: No module named ‘contextily’”
# Solution: install the package into the running kernel
%pip install -q contextily“User memory limit exceeded”
# Solution: Reduce data scope
# - Use smaller region
# - Filter dates more strictly
# - Increase scale parameterOffline Copy
Use your browser’s Print → Save as PDF to keep an offline copy of this page.
Additional Resources
- Official Documentation:
- Community Cheat Sheets:
Last reviewed: November 2026.