Cheat Sheets

Quick Reference Guides for Day 1

Date

November 17, 2025

Overview

Quick reference guides for the tools, libraries, and concepts covered in Day 1. Bookmark this page for easy access during 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",
    "cloud_cover": 12.5
}

Control Flow

# If statements
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
valid_images = [img for img in images if img.cloud_cover < 20]

# While loop
count = 0
while count < 10:
    count += 1

Functions

# Basic function
def calculate_ndvi(nir, red):
    """Calculate Normalized Difference Vegetation Index."""
    return (nir - red) / (nir + red)

# Function with default arguments
def load_image(path, band="B04", scale=10):
    return ee.Image(path).select(band).reproject(scale=scale)

# Lambda function
square = lambda x: x ** 2

NumPy 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 1

Array 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 5

Array 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
gdf.to_file("output.shp")
gdf.to_file("output.geojson", driver="GeoJSON")
gdf.to_file("output.gpkg", driver="GPKG")

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.area > 1000000]

# 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
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
with rasterio.open("sentinel2.tif") as src:
    red = src.read(4).astype(float)
    nir = src.read(8).astype(float)
    ndvi = (nir - red) / (nir + red)

Visualization

from rasterio.plot import show

# Single band
with rasterio.open("image.tif") as src:
    show(src, cmap="gray")

# RGB composite
with rasterio.open("image.tif") as src:
    show((src, [4, 3, 2]))  # True color (R, G, B)

Google Earth Engine (Python API) Cheat Sheet

Initialization

import ee

# Authenticate (first time only)
ee.Authenticate()

# Initialize
ee.Initialize()

Image Operations

# Load single image
image = ee.Image("COPERNICUS/S2/20250115T012345_20250115T012345_T51PTS")

# Load from collection
collection = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
image = collection.first()

# 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
def mask_s2_clouds(image):
    qa = image.select("QA60")
    cloud_mask = qa.bitwiseAnd(1 << 10).eq(0).And(
                 qa.bitwiseAnd(1 << 11).eq(0))
    return image.updateMask(cloud_mask)

# Apply to collection
masked = collection.map(mask_s2_clouds)

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 (least cloudy pixels)
composite = collection.qualityMosaic("B8")

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="users/yourname/composite",
    scale=10,
    region=roi
)

Visualization

# In 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")

Map

Sentinel Mission Quick Reference

Sentinel-1 (SAR)

Parameter Value
Type C-band SAR
Bands VV, VH
Resolution 10m (IW mode)
Swath 250 km
Revisit 6 days (2 satellites)
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 (3 satellites: 2A, 2B, 2C)

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)
mndwi = image.normalizedDifference(["B8", "B11"])

NDBI (Built-up)

ndbi = image.normalizedDifference(["B11", "B8"])

EVI (Enhanced Vegetation Index)

evi = image.expression(
    "2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
    {
        "NIR": image.select("B8"),
        "RED": image.select("B4"),
        "BLUE": image.select("B2")
    }
)

Philippine Regions & Provinces

Administrative Levels

  • Region (17) → Province (81) → 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

“ee is not defined”

# Solution: Initialize Earth Engine
import ee
ee.Initialize()

“ModuleNotFoundError: No module named ‘geopandas’”

# Solution: Install the package
!pip install geopandas

“RuntimeError: rasterio is not installed”

# Solution: Install rasterio
!pip install rasterio

“User memory limit exceeded”

# Solution: Reduce data scope
# - Use smaller region
# - Filter dates more strictly
# - Increase scale parameter

Downloadable PDFs

NotePrint-Friendly Versions

Download PDF versions of these cheat sheets for offline reference:

PDFs will be available in the Downloads section.


Additional Resources


Bookmark this page for quick access during training exercises!