NetCDF Reader
Since: netcdf_gbx v0.4.1
Read CF-convention NetCDF into GeoBrix's existing schemas — no new downstream contracts.
netcdf_gbx is pure Python (rasterio/netcdf4-backed) and needs no JAR. It runs on Serverless,
standard (shared), and ARM clusters. It has a raster and a vector mode.
A NetCDF file is a bag of labelled N-D arrays. Only some layouts are maps. The modes split along that grain: gridded variables use raster mode, and feature or point data uses vector mode.
For a large cube, or one that many jobs read slices of or write results back to, use Zarr instead of NetCDF. Zarr is read a chunk at a time and written transactionally. See the Zarr Reader.
Selecting variables — the unified contract
Both modes share one rule: variable / variables is an optional
filter, not a required selector.
- A bare
load(novariable/variables) processes all readable variables — in raster mode, one(source, tile)row per grid variable; in vector mode, all DSG / curvilinear features. - Passing
variable(one) orvariables(a comma-separated list) filters to exactly those variables.
The source column in raster mode is the GDAL subdataset selector,
NETCDF:"{path}":{var}, which identifies the originating variable per row.
Earlier netcdf_gbx required a variable / variables option — a bare load
raised. It is now an optional filter, so a bare load returns every readable
variable. Explicit-variable calls are unchanged.
Modes
The reader has two modes, chosen by the mode option:
raster(default) — a regular lat/lon or projected grid is transcoded to the shared(source, tile)GeoTIFF schema, exactly like the other raster readers. Everything downstream (rst_h3_tessellate, band math, tiling) works unchanged. ERA5 reanalysis grids read this way.vector— point (discrete-sampling) data, or any 2-D field including a curvilinear/swath grid, is emitted as one point per cell (cell-centre lon/lat + values). This reads swath products losslessly, with no regridding or interpolation choices baked in. Sentinel-5P TROPOMI CH4 (a netCDF-4 swath) reads this way.
The reader never resamples and never applies quality thresholds. In vector mode
every variable — including a quality flag such as Sentinel-5P
qa_value — travels through as its own column, so you decide how to filter.
Raw sensor-geometry products (no per-pixel lon/lat) are rejected with an
actionable error rather than silently guessed at.
NetCDF raster reads are multidimensional per-variable reads that materialize tile
bytes directly into each row. Virtual-tile support (virtualTiles) for the NetCDF
readers is not part of this release.
Options
| Option | Default | Description |
|---|---|---|
mode | "raster" | raster (CF grid → tile) or vector (points / per-cell points). |
variable / variables | — (all) | Optional filter. Absent → all readable variables. variable takes one; variables takes a comma-separated list (vector-mode attribute columns). |
group | — | HDF5 group path for grouped NetCDF-4 files (e.g. Sentinel-5P "/PRODUCT"). |
dimIndex | — | Raster mode: pin one or more leading (non-spatial) dimensions to a specific integer index. Format: "dim=index" or "dim1=i1,dim2=i2". Example: "time=2,level=1". Absent dims fall back to index 0 (with a warning when the dim has more than one slice). An out-of-range index raises ValueError. |
fanout | — | Raster mode: expand one or more leading dimensions across all their indices. Format: "dim" or "dim1,dim2". Each index combination becomes a separate (source, tile) row. A variable that lacks any of the named dims emits a single row (no expansion). Dims not listed are pinned by dimIndex or default to index 0. A dim that appears in both dimIndex and fanout raises ValueError. |
bandDim | — | Raster mode: stack one leading dimension's slices as bands in a single multi-band tile. Format: "dim" (one dim only). bandDim="time" on a variable with (time=3, lat, lon) produces one 3-band tile. Composes with dimIndex (pins other dims) and fanout (one multi-band tile per fanout combination). A dim named in bandDim cannot also appear in dimIndex or fanout — this raises ValueError. Estimated decoded bytes > ~256 MiB emits a UserWarning and suggests fanout instead. |
bbox / bboxCrs | — | Area-of-interest filter ("minx,miny,maxx,maxy"). |
filterRegex | ".*" | When loading a directory, keep files whose full path matches. |
sizeInMB | "-1" | Raster mode: <= 0 = one whole tile per variable. |
Register the *_gbx DataSources once per session:
# Register the lightweight DataSources (once per session)
from databricks.labs.gbx import register
register(spark)
Raster mode — CF grids → tiles
# Raster mode (default): a CF regular lat/lon grid -> (source, tile).
# e.g. ERA5 2m-temperature on a regular grid.
df = (spark.read.format("netcdf_gbx")
.option("variable", "t2m")
.load("/Volumes/main/geobrix_samples/netcdf/era5_sample.nc"))
df.show()
The output is the standard (source, tile) schema — see
Tile Structure. Only regular lat/lon or projected
(CF grid_mapping) grids are accepted in raster mode; a curvilinear/swath
variable raises an error steering you to mode=vector.
A cell that holds the variable's fill value stays that fill value in the tile, and the tile's NoData is the same value. This matches what GDAL reads from the file.
Multi-dimensional variables (time / level)
Climate reanalysis, forecast, and model-output files commonly have a
(time, level, lat, lon) shape. By default the reader emits one row per
variable and takes the first (index 0) slice of every non-spatial leading
dimension. It logs a warning for any dimension with more than one slice.
dimIndex selects a specific slice without expanding the result set:
# Read the slice at time index 2 and level index 1 (one row).
df = (
spark.read.format("netcdf_gbx")
.option("variable", "temp")
.option("dimIndex", "time=2,level=1")
.load("/Volumes/main/geobrix_samples/netcdf/era5_sample.nc")
)
df.show()
fanout expands one or more dimensions across all their indices, emitting
one (source, tile) row per combination:
# Emit one row per (time, level) combination — 3 times × 4 levels = 12 rows.
df = (
spark.read.format("netcdf_gbx")
.option("variable", "temp")
.option("fanout", "time,level")
.load("/Volumes/main/geobrix_samples/netcdf/era5_sample.nc")
)
df.show()
Both options can be combined: fanout expands the listed dims while dimIndex
pins any remaining leading dims. A dim in both options raises a ValueError.
The source column for a specific slice includes a bracketed suffix,
NETCDF:"path":var[level=1,time=2], so each row is uniquely identifiable. The
tile metadata map carries a sliceDims key (e.g. "level=1,time=2") and, for
dims that have coordinate values, a sliceCoord_<dim> key with the coordinate
value as a string.
Multi-band stacking (bandDim)
bandDim stacks a leading dimension's slices as bands in one tile. Use it for
per-pixel cross-slice math (e.g. anomaly detection, temporal differencing)
that needs all time steps in a single raster.
# Stack all 3 time slices as bands in one tile.
df = (
spark.read.format("netcdf_gbx")
.option("variable", "temp")
.option("bandDim", "time")
.load("/Volumes/main/geobrix_samples/netcdf/era5_sample.nc")
)
df.show()
bandDim composes with dimIndex and fanout on distinct dimensions:
# One 3-band tile per level (time stacked as bands, level fanned out).
df = (
spark.read.format("netcdf_gbx")
.option("variable", "temp")
.option("bandDim", "time")
.option("fanout", "level")
.load("/Volumes/main/geobrix_samples/netcdf/era5_sample.nc")
)
Band provenance is recorded in the tile metadata: bandDim (the stacked
dimension name), bandCoords (comma-separated coordinate values for each
band), and bandDescriptions (GDAL-style descriptions such as
"time=0.0,time=1.0,time=2.0"). The tile's source column includes a
bandDim=<dim> marker to identify the row.
bandDim is for a modest number of slices you intend to work across together
in one tile. Examples are per-pixel aggregations, temporal differencing, or deriving an index
from multiple time steps. Peak decoded RAM ≈ 1 slice, but the full N-band GTiff
is held in the executor while downstream processes it.
fanout is memory-safe at scale. Each row is one bounded 2-D slice. Any
number of time steps can therefore be processed in parallel without accumulating a large
multi-band buffer per task.
If bandDim would produce a tile larger than ~256 MiB of decoded data, the
reader emits a UserWarning and suggests fanout instead.
Vector mode — points & swath → per-cell points
# Vector mode: swath / point NetCDF -> one point per cell (lossless,
# no regridding). e.g. Sentinel-5P TROPOMI CH4 (netCDF-4 swath); the quality
# flag rides along as its own column so you filter downstream.
df = (spark.read.format("netcdf_gbx")
.option("mode", "vector")
.option("group", "/PRODUCT")
.option("variables", "methane_mixing_ratio_bias_corrected,qa_value")
.load("/Volumes/main/geobrix_samples/netcdf/s5p_ch4_sample.nc"))
# columns: <vars...>, geom_0 (WKB), geom_0_srid, geom_0_srid_proj
Vector mode emits attribute columns (one per variable) followed by a
geom_0 WKB point column and geom_0_srid / geom_0_srid_proj string columns.
This is the same shape as the other *_gbx vector readers, so the GeoBrix built-in
gbx_st_* functions, native Databricks ST, and H3 binning compose directly. A
curvilinear/swath cell carries its own lon/lat, so each becomes an exact point;
no target grid or resampling method is chosen for you.
CF discrete sampling geometries
A file with a featureType of point, profile or trajectory gives one point per observation.
The columns are the id variable (cf_role), then the other variables by name.
A variable stored once per profile, such as its time, repeats on each of its observations.
The vertical coordinate of a profile is the point's Z, not a column.
It is the variable with axis = "Z", a standard_name of altitude or depth, or a positive attribute.
A depth keeps its stored sign (positive down), as the GDAL netCDF driver gives it.
A time variable in these files is a TIMESTAMP, as in the other vector files, and the CRS is EPSG:4326.
# Vector mode reads a CF discrete sampling geometry (featureType "profile"):
# one point per observation. The altitude is the point's Z; the profile id and
# the time, stored once per profile, repeat on each of its observations.
df = (spark.read.format("netcdf_gbx")
.option("mode", "vector")
.load("/Volumes/main/geobrix_samples/netcdf/ocean_profiles.nc"))
# columns: profile, temp, time, geom_0 (WKB, POINT Z), geom_0_srid, geom_0_srid_proj
# A trajectory file (featureType "trajectory") gives one point per observation,
# with its trajectory id, time and measurements as columns.
df = (spark.read.format("netcdf_gbx")
.option("mode", "vector")
.load("/Volumes/main/geobrix_samples/netcdf/ship_tracks.nc"))
# columns: trajectory, temp, time, geom_0 (WKB, POINT), geom_0_srid, geom_0_srid_proj
A profile file stores its observations flat or as a ragged array. In an indexed ragged array, a variable on the
observation dimension with an instance_dimension attribute says which profile each belongs to. In a contiguous ragged
array, a variable with a sample_dimension attribute counts the observations of each profile.
The latitude and longitude may sit on the profile (or trajectory) dimension or on the observation dimension.
An index outside the profiles, a missing index, or counts that do not add up to the observations are refused with an error.
Attribute columns take their type from the variable's CF attributes. A time variable
is a TIMESTAMP (read as UTC), except an integer count of whole days (days since …, a
midnight base, no scale_factor or add_offset), which is a DATE. A
variable that flags 0 and 1 as flag_meanings = "false true" is a BOOLEAN
(NULL where the file has a fill value). These are the types the netcdf_gbx writer
gives a TIMESTAMP, DATE or BOOLEAN column. Any other variable keeps its numeric type.
netcdf_gbx writer
netcdf_gbx is also a writer — the inverse of the reader.
df.write.format("netcdf_gbx") writes CF-compliant .nc files from raster tile
DataFrames (the default raster mode) or from point DataFrames (vector mode), with
singleFile / merge consolidation. See the NetCDF Writer
page for the full write options, single-file/merge semantics, and round-trip
guarantees.
Compressed netCDF-4 variables (zstd, blosc, bzip2)
NetCDF-4 files can compress a variable with zstd, blosc or bzip2 as well as the built-in deflate. Those three are HDF5 filter plugins, loaded at run time, and the GeoBrix env wheels ship them (with szip, shuffle and fletcher32) beside their GDAL.
Nothing to set up. The first time GeoBrix's netCDF4, rasterio or GDAL bindings are imported,
the plugins are registered with GeoBrix's own netCDF and HDF5 libraries. The HDF5_PLUGIN_PATH environment variable
is not set, so other HDF5 libraries in the same process (for example h5py's) and child processes are not
affected. If you set HDF5_PLUGIN_PATH yourself, your directories are searched first and GeoBrix's plugins fill in the
filters yours lack. GBX_NATIVE_DISABLE=1 turns the env wheel's native payload, plugins included, off.
netcdf_gbx reads the CRS from CF crs_wkt (or crs_canonical) grid-mapping attributes and stores it as a canonical string in tile.metadata and tile.crs. The spatial_epsg attribute is also read. For a non-EPSG CRS, prefer crs_canonical: spatial_epsg may carry an ESRI code, although its name implies EPSG. ESRI and OGC authorities are preserved. See Coordinate reference systems for the full CRS model.
Next Steps
- GeoTIFF Reader — for COG/GeoTIFF rasters (e.g. Sentinel-2, EMIT CH4).
- Raster Functions — tessellation, band math, tiling.
- Ingestion Pipelines — ingest new and changed files incrementally
Common functions: used vs excluded
See GBX Common Functions for the full catalog of shared file-access primitives. The table below shows which are active in this reader and which are not, and why.
| Common capability | Used here? | How / why |
|---|---|---|
list_local_files (session-free enumeration) | Used | All directory reads — recursive, include_hidden, extensions, path_glob_filter options are routed through this shared predicate. |
enumerate_files (FILE-tier enumeration) | Not in the DataSource | The DataSource is session-less on Connect and does not call enumerate_files; FILE-tier enumeration is only available through gbx_file_read at the function layer. |
gbx_file_read / gbx_file_write (FILE tier) | Not in the DataSource | The DataSource is FUSE-only (session-less on Connect); FILE reads go through gbx_file_read → rst_fromfile at the function layer. |
The *_gbx readers use the shared file_gbx file-access base for FILE / FUSE routing and enumeration — capability tiers, the no-gating rule, and layout options are described there.