Skip to main content

Multidimensional Data and Time Series

So far we have worked with vectors and rasters. These data were usually two- or three-dimensional, sometimes spectral images with more than one band. But when we talk about data cubes, much of remote sensing data and, above all, climate reanalyses (ERA5, CMIP, numerical weather prediction) have several dimensions at once: time, latitude, longitude and sometimes a vertical level (altitude/pressure).

xarray extends numpy and pandas to this N-dimensional world, letting us aggregate spatial coordinates into a time series, search along the time axis and coordinate multiple variables.

Data Cubes

Data Cubes

Colab link

Open In Colab
Code
# only run this if you are on Colab! 
# git clone https://github.com/ftl-brazil-2026/ebook.git
# pip install -r requirements.txt
Code
import os
import numpy as np
import pandas as pd
import xarray as xr
import rioxarray  
import matplotlib.pyplot as plt
import seaborn as sns
import hvplot.xarray  ## acessor of hvplot within xarray
import holoviews as hv
from dotenv import load_dotenv

load_dotenv()
sns.set_theme(style="whitegrid")

xarray fundamentals

Why xarray?

  • numpy gives you N-dimensional arrays, but data[3, 12, 40] says nothing about what axis 0, 1 or 2 is.
  • pandas gives you labels (index/columns), but it is essentially 1D/2D, which is unnatural for time × latitude × longitude × level.
  • xarray brings together the best of both worlds: N-D arrays with named dimensions, labeled coordinates and metadata, and it is backed by Dask, allowing distributed computing. It is the standard format in Python for climate/geospatial data in NetCDF and Zarr (ERA5, CMIP6, MODIS, numerical weather prediction).

2. Core structures: DataArray and Dataset

  • DataArray: an N-D array + dims (axis names) + coords (the values along each axis: dates, latitudes…) + attrs (free-form metadata: units, long name, etc).
  • Dataset: a dictionary of DataArrays that share the same coordinates, for example temperature and precipitation living on the same time/lat/lon grid.

Let’s create synthetic data (not ERA5 yet) just to explore how xarray works without depending on the network.

Code
rng = np.random.default_rng(42)

time = pd.date_range("2015-01-01", periods=24, freq="MS")
lat = np.linspace(-9.6, -9.2, 5)
lon = np.linspace(-40.7, -40.3, 5)

ciclo_sazonal = np.sin(2 * np.pi * (np.arange(24) / 12))[:, None, None]
temp_valores = 27 + 3 * ciclo_sazonal + rng.normal(0, 0.5, (24, 5, 5))

temp = xr.DataArray(
    temp_valores,
    dims=["time", "lat", "lon"],
    coords={"time": time, "lat": lat, "lon": lon},
    name="t2m",
    attrs={"units": "degC", "long_name": "2m air temperature (synthetic)"},
)
temp
<xarray.DataArray 't2m' (time: 24, lat: 5, lon: 5)> Size: 5kB
array([[[27.15235854, 26.48000795, 27.3752256 , 27.47028236,
         26.02448241],
        [26.34891025, 27.0639202 , 26.8418787 , 26.99159942,
         26.57347804],
        [27.43969899, 27.38889597, 27.03301535, 27.5636206 ,
         27.23375467],
        [26.57035377, 27.18437539, 26.5205587 , 27.43922515,
         26.97503704],
        [26.90756882, 26.65953523, 27.61127067, 26.92273526,
         26.78583609]],

       [[28.32393322, 28.76615459, 28.68272203, 28.70636631,
         28.7154105 ],
        [29.5708238 , 28.29679249, 28.24387864, 28.09311364,
         28.80798971],
        [29.06448615, 28.44302627, 28.07992176, 28.08775939,
         28.82529639],
        [28.87162709, 28.77157713, 28.16724515, 28.61608066,
         28.5583429 ],
        [28.6093443 , 28.93571439, 28.61179777, 28.83945678,
...
         24.3583767 ],
        [24.24838218, 24.02516   , 23.88579245, 23.77968789,
         23.95752513],
        [24.3665836 , 24.56907135, 24.42749482, 24.01915615,
         24.85201607],
        [24.77163012, 24.32209963, 24.07546572, 24.67613775,
         24.49591058],
        [23.67786016, 24.36793366, 24.53294169, 23.9520764 ,
         24.49684549]],

       [[24.77258876, 26.16809305, 26.12397499, 25.37374133,
         25.68172717],
        [24.29503902, 24.92182617, 25.35311054, 24.96393349,
         25.85719824],
        [26.49864827, 24.91169264, 25.0812683 , 25.61772418,
         26.30555807],
        [24.88881284, 25.62451806, 26.41064943, 24.67412043,
         24.8594654 ],
        [25.2881967 , 25.23970579, 25.90630064, 25.62082986,
         24.61251897]]])
Coordinates:
  * time     (time) datetime64[us] 192B 2015-01-01 2015-02-01 ... 2016-12-01
  * lat      (lat) float64 40B -9.6 -9.5 -9.4 -9.3 -9.2
  * lon      (lon) float64 40B -40.7 -40.6 -40.5 -40.4 -40.3
Attributes:
    units:      degC
    long_name:  Temperatura do ar a 2m (sintético)

Look at the repr above. It shows the dimensions, the size of each, the coordinates and the attributes: much more informative than a bare array.shape.

Code
print("dims:", temp.dims)
print("shape:", temp.shape)
print("attributes:", temp.attrs)
temp.coords
dims: ('time', 'lat', 'lon')
shape: (24, 5, 5)
atributos: {'units': 'degC', 'long_name': 'Temperatura do ar a 2m (sintético)'}
Coordinates:
  * time     (time) datetime64[us] 192B 2015-01-01 2015-02-01 ... 2016-12-01
  * lat      (lat) float64 40B -9.6 -9.5 -9.4 -9.3 -9.2
  * lon      (lon) float64 40B -40.7 -40.6 -40.5 -40.4 -40.3

Dataset: how several variables are grouped together

If we want to analyze the climate regime of a biome, such as the Brazilian semi-arid region, we can look for correlations between variables like temperature and precipitation, and understand a bit of the regional climate that characterizes it.

For our first contact with xarray, let’s create synthetic precipitation (rain concentrated in a few months) and put everything together in a Dataset.

Code
(np.arange(24) - 8) / 12
array([-0.66666667, -0.58333333, -0.5       , -0.41666667, -0.33333333,
       -0.25      , -0.16666667, -0.08333333,  0.        ,  0.08333333,
        0.16666667,  0.25      ,  0.33333333,  0.41666667,  0.5       ,
        0.58333333,  0.66666667,  0.75      ,  0.83333333,  0.91666667,
        1.        ,  1.08333333,  1.16666667,  1.25      ])
Code
# imitating a rainy season
estacao_chuvosa = np.sin(2 * np.pi * ((np.arange(24) - 8) / 12))[:, None, None]
precip_valores = np.clip(50 + 120 * estacao_chuvosa + rng.normal(0, 15, (24, 5, 5)), 0, None)

# creating an xarray dataset
precip = xr.DataArray(
    precip_valores,
    dims=["time", "lat", "lon"],
    coords={"time": time, "lat": lat, "lon": lon},
    name="tp",
    attrs={"units": "mm", "long_name": "Monthly precipitation (synthetic)"},
)

ds_sintetico = xr.Dataset({"t2m": temp, "tp": precip})
ds_sintetico
<xarray.Dataset> Size: 10kB
Dimensions:  (time: 24, lat: 5, lon: 5)
Coordinates:
  * time     (time) datetime64[us] 192B 2015-01-01 2015-02-01 ... 2016-12-01
  * lat      (lat) float64 40B -9.6 -9.5 -9.4 -9.3 -9.2
  * lon      (lon) float64 40B -40.7 -40.6 -40.5 -40.4 -40.3
Data variables:
    t2m      (time, lat, lon) float64 5kB 27.15 26.48 27.38 ... 25.62 24.61
    tp       (time, lat, lon) float64 5kB 161.7 145.3 173.0 ... 192.3 154.1
Code
ds_sintetico.t2m.values.shape
(24, 5, 5)

From here on, real data

From here on we’ll use a small, real subset of ERA5-Land (daily) over Petrolina (PE) and Juazeiro (BA), the same pair of cities as our case study further down. The idea is to combine xarray’s mechanics with a climate dataset.

Authentication

To access Earth Data Hub, sign up at platform.destine.eu and generate a personal access token in the Quota & API Keys section. Store it in your .env as EARTH_HUB_API_KEY (the key is already listed in this repository’s .env_copy).

Mind the quota: the free account has a monthly request limit. Never call .load()/.compute() on the whole dataset. Subset with .sel() first (one city, a small bounding box, a date range) and only then materialize.

Code
edh_token = os.environ.get("EARTH_HUB_API_KEY")
assert edh_token, "Set EARTH_HUB_API_KEY in your .env (see earthdatahub.destine.eu)"

# Full catalog of available ERA5 datasets: https://earthdatahub.destine.eu/collections/era5/datasets
# Check there for the exact slug of the dataset you want (hourly, daily, monthly-means...) 
ERA5_LAND_DAILY = "era5-land-daily-utc-v1"

era5_url = f"https://edh:{edh_token}@data.earthdatahub.destine.eu/era5/{ERA5_LAND_DAILY}.zarr"
Code
# Lazy load 
ds_era5 = xr.open_dataset(era5_url, 
                          chunks={},
                            engine="zarr")
ds_era5
<xarray.Dataset> Size: 8TB
Dimensions:     (valid_time: 28002, latitude: 1472, longitude: 3600)
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 224kB 1950-01-01 ... 2026-08-31
  * latitude    (latitude) float64 12kB 90.0 89.9 89.8 ... -56.9 -57.0 -57.1
  * longitude   (longitude) float64 29kB 0.0 0.1 0.2 0.3 ... 359.7 359.8 359.9
Data variables: (12/14)
    d2m         (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    e           (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    pev         (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    ro          (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    sp          (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    ssr         (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    ...          ...
    swvl1       (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    swvl2       (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    t2m         (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    tp          (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    u10         (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
    v10         (valid_time, latitude, longitude) float32 594GB dask.array<chunksize=(75, 150, 300), meta=np.ndarray>
Attributes:
    GRIB_edition:            1
    GRIB_centre:             ecmf
    GRIB_centreDescription:  European Centre for Medium-Range Weather Forecasts
    GRIB_subCentre:          0
    Conventions:             CF-1.7
    institution:             European Centre for Medium-Range Weather Forecasts
    history:                 2026-08-19T08:44 GRIB to CDM+CF via cfgrib-0.9.1...

ERA5 conventions

  1. Longitude convention: some ERA5 mirrors use 0°–360° instead of -180° to 180°.
  2. Latitude order: ERA5 usually comes with decreasing latitude (from 90° to -90°).

Let’s check both before subsetting.

Code
lon_name = "longitude" if "longitude" in ds_era5.coords else "lon"
lat_name = "latitude" if "latitude" in ds_era5.coords else "lat"

lon_min_raw = float(ds_era5[lon_name].min())
lon_max_raw = float(ds_era5[lon_name].max())
lat_descendente = float(ds_era5[lat_name][0]) > float(ds_era5[lat_name][-1])
usa_0_360 = lon_max_raw > 180

print(f"{lon_name}: [{lon_min_raw:.2f}, {lon_max_raw:.2f}]")
print(f"{lat_name}: descending? {lat_descendente}")
longitude: [0.00, 359.90]
latitude: descendente? True

Study area

Petrolina (PE) & Juazeiro (BA)

We’ll use a small bounding box around the two cities.

Code
import geobr
petrolina = geobr.read_municipality(code_muni=2611101, year=2020).to_crs(epsg=4326)
juazeiro  = geobr.read_municipality(code_muni=2918407, year=2020).to_crs(epsg=4326)
estados   = geobr.read_state(year=2020).to_crs(epsg=4326)
Code
union = petrolina.union(juazeiro).geometry.iloc[0]
minx, miny, maxx, maxy = union.bounds
Code
import folium
from shapely.geometry import box

bbox= union.bounds
bounds_polygon = box(*bbox)

centro_lat = (bbox[1] + bbox[3]) / 2
centro_lon = (bbox[0] + bbox[2]) / 2

m = folium.Map(location=[centro_lat, centro_lon], zoom_start=10)


folium.GeoJson(
    bounds_polygon.__geo_interface__,
    name="Bounds",
    style_function=lambda x: {
        'fillColor': 'none',
        'color': 'blue',
        'weight': 3,
        'fillOpacity': 0
    }
).add_to(m)

m
Make this Notebook Trusted to load map: File -> Trust Notebook
Code
lat_min, lat_max = miny, maxy
lon_min, lon_max = minx, maxx
ANO_INICIO, ANO_FIM = "2015-01-01", "2025-12-31"

def ajusta_lon(lon):
    return lon % 360 if float(ds_era5.longitude.max()) else lon

fatia_lat = slice(lat_max, lat_min) if lat_descendente else slice(lat_min, lat_max)
fatia_lon = slice(ajusta_lon(lon_min), ajusta_lon(lon_max))

# selecting
# 2m temperature
# total precipitation 
variaveis = ["t2m", "tp"]
Code
recorte = ds_era5[variaveis].sel(
    valid_time=slice(ANO_INICIO, ANO_FIM),
    **{lat_name: fatia_lat, lon_name: fatia_lon},
)
recorte
<xarray.Dataset> Size: 5MB
Dimensions:     (valid_time: 4018, latitude: 13, longitude: 11)
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 32kB 2015-01-01 ... 2025-12-31
  * latitude    (latitude) float64 104B -8.7 -8.8 -8.9 -9.0 ... -9.7 -9.8 -9.9
  * longitude   (longitude) float64 88B 319.1 319.2 319.3 ... 319.9 320.0 320.1
Data variables:
    t2m         (valid_time, latitude, longitude) float32 2MB dask.array<chunksize=(34, 13, 11), meta=np.ndarray>
    tp          (valid_time, latitude, longitude) float32 2MB dask.array<chunksize=(34, 13, 11), meta=np.ndarray>
Attributes:
    GRIB_edition:            1
    GRIB_centre:             ecmf
    GRIB_centreDescription:  European Centre for Medium-Range Weather Forecasts
    GRIB_subCentre:          0
    Conventions:             CF-1.7
    institution:             European Centre for Medium-Range Weather Forecasts
    history:                 2026-08-19T08:44 GRIB to CDM+CF via cfgrib-0.9.1...

Only now, with the small subset defined, do we actually materialize the data.

If it’s too big/slow on your connection, reduce ANO_INICIO/ANO_FIM (start/end year) first.

Code
%%time
# this may take a few minutes
recorte = recorte.load()
CPU times: user 6.58 s, sys: 1.17 s, total: 7.74 s
Wall time: 2min 18s

Unit conversion

ERA5 stores temperature in Kelvin and accumulated precipitation in meters. Converting to °C and mm:

Code
dados = xr.Dataset()

dados["t2m_celsius"] = recorte["t2m"] - 273.15
dados["t2m_celsius"].attrs = {"units": "degC", "long_name": "2m air temperature"}

dados["tp_mm"] = recorte["tp"] * 1000
dados["tp_mm"].attrs = {"units": "mm", "long_name": "Precipitation"}

dados
<xarray.Dataset> Size: 5MB
Dimensions:      (latitude: 13, longitude: 11, valid_time: 4018)
Coordinates:
  * latitude     (latitude) float64 104B -8.7 -8.8 -8.9 -9.0 ... -9.7 -9.8 -9.9
  * longitude    (longitude) float64 88B 319.1 319.2 319.3 ... 319.9 320.0 320.1
  * valid_time   (valid_time) datetime64[ns] 32kB 2015-01-01 ... 2025-12-31
Data variables:
    t2m_celsius  (valid_time, latitude, longitude) float32 2MB 26.76 ... 29.69
    tp_mm        (valid_time, latitude, longitude) float32 2MB 0.1642 ... 0.0...

Indexing and selection: .isel vs .sel

Just as pandas and geopandas have their own ways of indexing and selecting slices, xarray has its own tricks.

  • .isel() selects by position (like array[0]), just like numpy.
  • .sel() selects by label (a date, a coordinate), the way you actually think about the data.
  • method="nearest" finds the grid point closest to a coordinate that doesn’t match exactly. This is essential, since it lets you look up a point within the grid the xarray dataset is defined on.
Code
ajusta_lon(-40.502)
319.498
Code
primeiro_dia = dados.isel(valid_time=0)               # by position
janeiro_2020 = dados.sel(valid_time="2020-01")         # by label
ponto_petrolina = dados.sel(
    **{lat_name: -9.389, 
       lon_name: 
       ajusta_lon(-40.502)}, 
       method="nearest"
)  # nearest cell

ponto_petrolina["t2m_celsius"]
<xarray.DataArray 't2m_celsius' (valid_time: 4018)> Size: 16kB
array([27.748444, 27.670319, 28.467194, ..., 31.600006, 32.006256,
       30.787506], shape=(4018,), dtype=float32)
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 32kB 2015-01-01 ... 2025-12-31
    latitude    float64 8B -9.4
    longitude   float64 8B 319.5
Attributes:
    units:      degC
    long_name:  Temperatura do ar a 2m

Vectorized operations with broadcasting by dimension name

In plain numpy, adding two arrays requires their shapes to “match” in the right order. In xarray, alignment is done by dimension name and coordinate values

Code
temp_fahrenheit = dados["t2m_celsius"] * 9 / 5 + 32  # converting to Fahrenheit

# now things get interesting
# temperature range: difference between the hottest and coldest day of the period, cell by cell
amplitude_termica = dados["t2m_celsius"].max("valid_time") - dados["t2m_celsius"].min("valid_time")
amplitude_termica
<xarray.DataArray 't2m_celsius' (latitude: 13, longitude: 11)> Size: 572B
array([[11.21875  , 11.2578125, 11.1953125, 11.1484375, 11.1328125,
        11.03125  , 10.9140625, 10.984375 , 10.875    , 10.875    ,
        10.75     ],
       [11.21875  , 11.2265625, 11.25     , 11.1328125, 11.09375  ,
        11.0703125, 10.9296875, 10.9453125, 10.890625 , 10.8984375,
        10.8515625],
       [11.2578125, 11.25     , 11.2265625, 11.1796875, 11.1015625,
        11.1015625, 11.03125  , 11.       , 10.9453125, 10.9609375,
        11.0234375],
       [11.28125  , 11.2890625, 11.28125  , 11.25     , 11.2265625,
        11.2265625, 11.1796875, 11.1015625, 10.9453125, 11.       ,
        10.9921875],
       [11.3359375, 11.3671875, 11.3203125, 11.34375  , 11.3515625,
        11.3671875, 11.3203125, 11.21875  , 11.0625   , 11.       ,
        11.046875 ],
       [11.2890625, 11.4140625, 11.46875  , 11.5234375, 11.5390625,
        11.5      , 11.4609375, 11.375    , 11.2421875, 11.1015625,
        11.125    ],
       [11.0625   , 11.515625 , 11.5625   , 11.6015625, 11.75     ,
        11.71875  , 11.625    , 11.59375  , 11.4765625, 11.390625 ,
        11.4375   ],
       [11.03125  , 11.3203125, 11.75     , 11.75     , 11.9765625,
        12.03125  , 12.0078125, 11.9140625, 11.7578125, 11.671875 ,
        11.78125  ],
       [11.5078125, 11.6953125, 11.7890625, 11.9609375, 12.125    ,
        12.1171875, 12.15625  , 12.125    , 11.9921875, 11.8984375,
        11.9921875],
       [11.53125  , 11.703125 , 11.984375 , 12.078125 , 12.265625 ,
        12.2109375, 12.3125   , 12.296875 , 12.140625 , 12.1484375,
        12.109375 ],
       [11.7890625, 11.9609375, 12.       , 12.15625  , 12.390625 ,
        12.3515625, 12.40625  , 12.359375 , 12.3125   , 12.2734375,
        12.171875 ],
       [11.9765625, 11.8828125, 11.9609375, 12.125    , 12.34375  ,
        12.375    , 12.3828125, 12.4375   , 12.5      , 12.40625  ,
        12.21875  ],
       [11.90625  , 11.9765625, 12.1015625, 12.0625   , 12.3203125,
        12.3984375, 12.53125  , 12.4921875, 12.4921875, 12.5234375,
        12.28125  ]], dtype=float32)
Coordinates:
  * latitude   (latitude) float64 104B -8.7 -8.8 -8.9 -9.0 ... -9.7 -9.8 -9.9
  * longitude  (longitude) float64 88B 319.1 319.2 319.3 ... 319.9 320.0 320.1
Attributes:
    units:      degC
    long_name:  Temperatura do ar a 2m

Reduction and aggregation by named dimension

  • Reducing along ["lat", "lon"] gives a time series (1 value per time step).

  • Reducing along "time" gives a map (1 value per cell).

Code
media_espacial = dados.mean(dim=[lat_name, lon_name])  # time series
media_temporal = dados.mean(dim="valid_time")           # mean map


media_espacial["t2m_celsius"].plot(marker="o", figsize=(10, 3))
plt.title("Spatial mean temperature over time — ERA5-Land (Petrolina/Juazeiro)")
plt.tight_layout()
plt.show()

Code
# let's explore
#dados['tp_mm'].groupby("valid_time.month").max().
Code
# dados["t2m_celsius"].groupby("valid_time.month").min().mean(dim=[lat_name,lon_name]).hvplot.line(
#     x="month", marker="o", 
#     height=300, 
#     width=650,
#     title="Minimum air temperature. Monthly for the years 2015-2025 ",
#     xlabel="Month", 
#     ylabel="Temperature (°C)",
# )

groupby and resample: climatology and temporal aggregation

  • groupby("time.month") groups all Januaries together, all Februaries together, and so on. This is our basis for computing a climatology (the mean seasonal cycle).
  • resample("YE") (or "1D", "1MS"…) regroups the data from its temporal frequency into a new frequency that makes sense for our analysis.
Code
climatologia_fundamentos = dados.groupby("valid_time.month").mean()

climatologia_fundamentos["t2m_celsius"].mean(dim=[lat_name, lon_name]).hvplot.line(
    x="month", marker="o", height=300, width=650,
    title="Mean seasonal temperature cycle — ERA5-Land (Petrolina/Juazeiro)",
    xlabel="Month", ylabel="Temperature (°C)",
)

Using Dask and chunks

When we have data that doesn’t fit in memory (which is in fact the case for most geospatial data and for analyses of a continent-sized country), it’s impossible to load everything into your computer’s RAM. There are some very clever ways to deal with this, and one of them is chunks. When you open a dataset with chunks={...} (or chunks="auto"), xarray uses Dask under the hood, so operations become lazy and nothing is actually read until you call .load() or .compute(). GEE uses the same strategy. This lets you select (.sel) a small subset of a giant dataset and only then materialize it.

Zarr: the modern, cloud-native format

“Zarr is like parquet for arrays”

Zarr is an open-source protocol for storing multi-dimensional-array datasets, like measurements over time, space, or other variables, as N-dimensional arrays. Think of it as a lightweight, modular alternative to older formats like HDF5, designed to work especially well with cloud storage and large-scale computing.

Traditional NetCDF is a single binary file: to read a small piece, you often have to download the whole file. Zarr splits the array into chunks stored as separate objects, which fits perfectly with cloud storage (S3, Azure Blob) and HTTP access. In the end, it lets you read only the chunks you need. That’s why modern reanalysis providers, such as DestinE’s Earth Data Hub, distribute ERA5 as Zarr instead of NetCDF.

An Interactive Guide to Zarr

Other libraries in the xarray ecosystem

Xarray Ecosystem

Code
dados.rio.write_crs("EPSG:4326", inplace=True)
print("CRS:", dados.rio.crs)
CRS: EPSG:4326

alright, we’ve covered the xarray basics with real data. Let’s go deeper with the full case study.


Case study: ERA5-Land in Petrolina (PE) / Juazeiro (BA)

Petrolina and Juazeiro are twin cities separated by the São Francisco River, in the heart of Brazil’s northeastern semi-arid region. The climate is hot, with scarce and concentrated rainfall, and yet the region is one of Brazil’s largest hubs of irrigated export fruit farming (mango, grapes), thanks to irrigation from the São Francisco River. This tension between a semi-arid climate and irrigated agriculture is a great reason to look carefully at the region’s climate data.

We’ll use ERA5-Land (ECMWF reanalysis, ~9 km resolution), accessed through the DestinE platform’s Earth Data Hub (EDH), a cloud mirror of ERA5 in Zarr that lets us open the whole dataset lazily and download only the space-time subset we need.

Daily/monthly aggregation

In the Earth Data Hub Zarr mirror we chose, the data is already aggregated by day. We can make the plots at the daily level or regroup them to plot at the monthly level.

Code
dados_diarios = xr.Dataset()
dados_diarios["t2m_celsius"] = dados["t2m_celsius"]
dados_diarios["tp_mm"] = dados["tp_mm"]

dados_mensais = xr.Dataset()
dados_mensais["t2m_celsius"] = dados_diarios["t2m_celsius"].resample(valid_time="1MS").mean()
dados_mensais["tp_mm"] = dados_diarios["tp_mm"].resample(valid_time="1MS").sum()

dados_mensais
<xarray.Dataset> Size: 152kB
Dimensions:      (latitude: 13, longitude: 11, valid_time: 132)
Coordinates:
  * latitude     (latitude) float64 104B -8.7 -8.8 -8.9 -9.0 ... -9.7 -9.8 -9.9
  * longitude    (longitude) float64 88B 319.1 319.2 319.3 ... 319.9 320.0 320.1
  * valid_time   (valid_time) datetime64[ns] 1kB 2015-01-01 ... 2025-12-01
    spatial_ref  int64 8B 0
Data variables:
    t2m_celsius  (valid_time, latitude, longitude) float32 76kB 27.98 ... 27.87
    tp_mm        (valid_time, latitude, longitude) float32 76kB 14.81 ... 7.867

Seasonal climatology (2015–2023)

Mean monthly cycle, averaged spatially over the bbox. What can we learn about the Brazilian semi-arid region?

Code
# here we reduce space (x,y) to a single time dimension 
media_espacial_mensal = dados_mensais.mean(dim=[lat_name, lon_name])

# here we group all months, month by month, to compute each month's mean
# so each value holds the mean along the time axis, for 2015-2023
grupo = media_espacial_mensal["t2m_celsius"].groupby("valid_time.month")
clim_media = grupo.mean()
clim_max   = grupo.max()
clim_min   = grupo.min()

climatologia = media_espacial_mensal.groupby("valid_time.month").mean()

temp_plot = climatologia["t2m_celsius"].hvplot.line(
    x="month", color="firebrick", height=300, width=420,
    title="Mean monthly temperature", xlabel="Month", ylabel="°C",
)
precip_plot = climatologia["tp_mm"].hvplot.bar(
    x="month", color="steelblue", height=300, width=420,
    title="Mean monthly precipitation", xlabel="Month", ylabel="mm",
)

opts = dict(x="month", 
            height=300, 
            width=420)

temp_plot = (
    clim_max.hvplot.line(**opts, color="darkred", line_dash="dashed", label="Maximum")
    * clim_media.hvplot.line(**opts, color="firebrick", line_width=2.5, label="Mean")
    * clim_min.hvplot.line(**opts, color="darkorange", line_dash="dashed", label="Minimum")
).opts(title="Monthly temperature", xlabel="Month", ylabel="°C", legend_position="bottom_right")

precip_plot = climatologia["tp_mm"].hvplot.bar(
    x="month", color="steelblue", height=300, width=420,
    title="Mean monthly precipitation", xlabel="Month", ylabel="mm",
)


temp_plot + precip_plot

Time series and anomalies

An anomaly is how much each month deviates from its climatology (the expected normal for that month). Persistent negative rainfall anomalies indicate drought periods.

Code
climatologia
<xarray.Dataset> Size: 288B
Dimensions:      (month: 12)
Coordinates:
  * month        (month) int64 96B 1 2 3 4 5 6 7 8 9 10 11 12
    spatial_ref  (month) int64 96B 0 0 0 0 0 0 0 0 0 0 0 0
Data variables:
    t2m_celsius  (month) float32 48B 27.56 27.4 27.56 ... 27.91 28.25 28.28
    tp_mm        (month) float32 48B 68.14 57.23 63.67 ... 10.54 33.26 32.66
Code
anomalia = media_espacial_mensal.groupby("valid_time.month") - climatologia

linha_zero = hv.HLine(0).opts(color="black", line_width=0.8)

(
    anomalia["tp_mm"].hvplot.line(
        x="valid_time", color="steelblue", height=300, width=850,
        title="Monthly precipitation anomaly — Petrolina/Juazeiro",
        xlabel="Date", ylabel="Anomaly (mm)",
    )
    * linha_zero
)

Map of the study area

Code
t2m_media_simples = dados_mensais["t2m_celsius"].max(dim="valid_time")

# the usual 0-360 -> -180/180 conversion
t2m_media_simples = t2m_media_simples.assign_coords(
    **{lon_name: (((t2m_media_simples[lon_name] + 180) % 360) - 180)}
).sortby(lon_name)

t2m_media_simples.hvplot.image(
    x=lon_name, y=lat_name, cmap="YlOrRd", colorbar=True,
    title="Maximum temperature (2015-2025) Petrolina & Juazeiro",
    height=420, width=460,
)
Code
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

proj = ccrs.PlateCarree()

t2m_media = dados_mensais["t2m_celsius"].mean(dim="valid_time")

# the ERA5-Land grid here is still in the 0-360° convention (e.g. 319.9),
# as we saw in "ERA5 conventions". Converting to -180/180 first
t2m_media = t2m_media.assign_coords(
    **{lon_name: (((t2m_media[lon_name] + 180) % 360) - 180)}
).sortby(lon_name)

lon_vals = t2m_media[lon_name].values
lat_vals = t2m_media[lat_name].values

p = t2m_media.plot(
    subplot_kws=dict(projection=proj, 
                     facecolor="lightgray"),
                        transform=proj,
                        cmap="YlOrRd",
                        cbar_kwargs={"label": "Mean temperature 2015-2025 (°C)"},
                        figsize=(7, 6),
                    )
ax = p.axes

for cidade, cor, nome in [(petrolina, "black", "Petrolina"), (juazeiro, "black", "Juazeiro")]:
    ax.add_geometries(cidade.geometry, crs=proj, facecolor="none", edgecolor=cor, linewidth=1.5, label=nome)

# extent taken from the ERA5 grid itself
margem = 0.1
ax.set_extent(
    [lon_vals.min() - margem, lon_vals.max() + margem, lat_vals.min() - margem, lat_vals.max() + margem],
    crs=proj,
)

ax.set_title("Petrolina and Juazeiro. Mean temperature 2015-2025")
plt.show()

Facet grid

We can also create a facet grid plot to build a panel of maps, one per value of a dimension, just by passing col="month". For that we need the climatology per grid cell, not the spatially aggregated one we computed above (that one became 1 value per month; this one keeps latitude/longitude).

Code
# monthly climatology per grid cell (keeps latitude/longitude; the monthly mean)
climatologia_espacial = dados_mensais.groupby("valid_time.month").mean()

t2m_climatologia = climatologia_espacial["t2m_celsius"].assign_coords(
    **{lon_name: (((climatologia_espacial[lon_name] + 180) % 360) - 180)}
).sortby(lon_name)

fg = t2m_climatologia.plot(
    col="month",
    col_wrap=4,
    transform=proj, 
    subplot_kws={"projection": proj},
    cmap="YlOrRd",
    cbar_kwargs={"orientation": "horizontal", 
                 "shrink": 0.8, 
                 "aspect": 40, 
                 "label": "Mean temperature (°C)"},
    robust=True,
)

for ax in fg.axs.flat:
    for cidade, cor in [(petrolina, "black"), (juazeiro, "navy")]:
        ax.add_geometries(cidade.geometry, crs=proj, facecolor="none", edgecolor=cor, linewidth=1)
    ax.set_extent(
        [t2m_climatologia[lon_name].min() - 0.1, t2m_climatologia[lon_name].max() + 0.1,
         t2m_climatologia[lat_name].min() - 0.1, t2m_climatologia[lat_name].max() + 0.1],
        crs=proj,
    )

plt.show()

Analyzing how climate change is affecting sleep

Here I’ll use just 1 point instead of a grid, so we can analyze a longer time series without having to access a very large chunk of data. My idea is to understand how climate change is affecting extreme minimum temperatures. When a night stays above 25 °C, it counts as an extreme heat event, because a 25 °C night is excessively hot.

To get there, I’ll first pick a city in the state of Goiás, recompute the ERA5 data as daily minimums, count 1 whenever the daily minimum exceeds the threshold, and sum per year. The result is a bar chart over the years counting how many nights exceeded the threshold.

Code
edh_token = os.environ.get("EARTH_HUB_API_KEY")
assert edh_token, "Set EARTH_HUB_API_KEY in your .env (see earthdatahub.destine.eu)"

# Full catalog of available ERA5 datasets: https://earthdatahub.destine.eu/collections/era5/datasets
# Unlike the previous section, here we need HOURLY data (not the already aggregated
# daily data), because only hourly values let us compute each day's minimum.
ERA5_LAND_HOURLY = "era5-land-v0"

era5_url_horario = f"https://edh:{edh_token}@data.earthdatahub.destine.eu/era5/{ERA5_LAND_HOURLY}.zarr"

Hourly ERA5-Land

This is the hourly ERA5 mirror. Here the data volume is much larger, since the data is discretized by hour.

Let’s take the chance to check the same two conventions (longitude and latitude order) we saw before, since each EDH dataset can come with a different convention.

Code
ds_era5_horario = xr.open_dataset(era5_url_horario, chunks={}, engine="zarr")

lon_name_h = "longitude" if "longitude" in ds_era5_horario.coords else "lon"
lat_name_h = "latitude" if "latitude" in ds_era5_horario.coords else "lat"

usa_0_360_h = float(ds_era5_horario[lon_name_h].max()) > 180
lat_descendente_h = float(ds_era5_horario[lat_name_h][0]) > float(ds_era5_horario[lat_name_h][-1])

print(f"{lon_name_h}: uses 0-360? {usa_0_360_h}")
print(f"{lat_name_h}: descending? {lat_descendente_h}")
longitude: usa 0-360? True
latitude: descendente? True

Goiânia (GO)

Instead of a bounding box, here we take just a single point, unlike the area slice we fetched before.

Code
goiania = geobr.read_municipality(code_muni=5208707, year=2020).to_crs(epsg=4326)
centro_goiania = goiania.geometry.iloc[0].centroid
lat_goiania, lon_goiania = centro_goiania.y, centro_goiania.x

print(f"Goiânia (GO): lat={lat_goiania:.3f}, lon={lon_goiania:.3f}")
Goiânia (GO): lat=-16.643, lon=-49.274

Extracting the hourly series at the point (40 years)

Since it’s a single point (not a grid), even with decades of hourly data the final volume isn’t significant, so we can use a much longer window than in the grid analysis above. The same rule still applies: .sel() first (point + time range), lazily, and only then .load().

Code
def ajusta_lon_h(lon):
    return lon % 360 if usa_0_360_h else lon

ANO_INICIO_PONTO, ANO_FIM_PONTO = "1985-01-01", "2024-12-31"  # 40 years


ponto_goiania = (
    ds_era5_horario["t2m"]
    .sel(valid_time=slice(ANO_INICIO_PONTO, ANO_FIM_PONTO))
    .sel(
        latitude=lat_goiania,
        longitude=ajusta_lon_h(lon_goiania),
        method="nearest",
    )
)
ponto_goiania
<xarray.DataArray 't2m' (valid_time: 350640)> Size: 1MB
dask.array<getitem, shape=(350640,), dtype=float32, chunksize=(1440,), chunktype=numpy.ndarray>
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 3MB 1985-01-01 ... 2024-12-31T23:...
    latitude    float64 8B -16.6
    longitude   float64 8B 310.7
Attributes: (12/32)
    GRIB_paramId:                             167
    GRIB_dataType:                            fc
    GRIB_numberOfPoints:                      5299200
    GRIB_typeOfLevel:                         surface
    GRIB_stepUnits:                           1
    GRIB_stepType:                            instant
    ...                                       ...
    GRIB_totalNumber:                         0
    GRIB_units:                               K
    long_name:                                2 metre temperature
    units:                                    K
    standard_name:                            unknown
    last_ingested_valid_time_index:           672047
Code
%%time
ponto_goiania = ponto_goiania.load()

temperatura_celsius = ponto_goiania - 273.15
temperatura_celsius.attrs = {"units": "degC", "long_name": "2m air temperature in Goiânia"}
temperatura_celsius
CPU times: user 20.9 s, sys: 2.94 s, total: 23.8 s
Wall time: 6min 13s
<xarray.DataArray 't2m' (valid_time: 350640)> Size: 1MB
array([21.350006, 20.850006, 20.850006, ..., 23.350006, 22.975006,
       22.131256], shape=(350640,), dtype=float32)
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 3MB 1985-01-01 ... 2024-12-31T23:...
    latitude    float64 8B -16.6
    longitude   float64 8B 310.7
Attributes:
    units:      degC
    long_name:  Temperatura do ar a 2m em Goiânia

Daily minimum and hot nights (minimum > 24°C)

There is even a similar climate index already established in the literature: tropical nights, usually defined as days on which the minimum temperature doesn’t drop below 20°C. Here we use a stricter threshold, 24°C, to flag nights of truly extreme heat.

resample to 1 minimum value per day

Code
minima_diaria = temperatura_celsius.resample(valid_time="1D").min()

LIMITE_NOITE_QUENTE = 24.0  # °C
noite_quente = minima_diaria > LIMITE_NOITE_QUENTE

noites_quentes_por_ano = noite_quente.groupby("valid_time.year").sum()
noites_quentes_por_ano
<xarray.DataArray 't2m' (year: 40)> Size: 320B
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0, 2, 0, 1, 0, 0,
       4, 2, 0, 1, 0, 2, 0, 1, 2, 1, 3, 0, 5, 3, 2, 1, 6, 8])
Coordinates:
  * year       (year) int64 320B 1985 1986 1987 1988 ... 2021 2022 2023 2024
    latitude   float64 8B -16.6
    longitude  float64 8B 310.7
Attributes:
    units:      degC
    long_name:  Temperatura do ar a 2m em Goiânia
Code
noites_quentes_por_ano.hvplot.bar(
    x="year", color="firebrick", height=350, width=850,
    title=f"Nights with a minimum above {LIMITE_NOITE_QUENTE:.0f}°C, per year in Goiânia",
    xlabel="Year", 
    ylabel="Number of nights",
)

References

  • Xarray Documentation - (Xarray Doc)[https://docs.xarray.dev/en/latest/index.html]
  • Earth Data Hub courses - (Tutorials)[https://earthdatahub.destine.eu/tutorials]
  • EOPF courses - (EOPF)[https://eopf-toolkit.github.io/eopf-101/]
  • Course notes on Zarr - (NCEAS)[https://learning.nceas.ucsb.edu/2025-04-arctic/sections/zarr.html]
  • Guido’s Substack on climate data - Substack