xarray-coordinate-alignment
Diagnose xarray coordinate mismatches and choose explicit alignment before comparing or merging labeled scientific datasets, including weather and climate grids.
Try your first task
A source-grounded starter task has not been verified for this skill yet.
SKILL.md
name: xarray-coordinate-alignmentdescription: "Diagnose xarray coordinate mismatches and choose explicit alignment before comparing or merging labeled scientific datasets, including weather and climate grids."category: datarisk: safesource: selfsource_type: selfdate_added: "2026-11-30"author: ShianMiketags: [xarray, scientific-data, coordinates, weather, netcdf]Xarray Coordinate Alignment
When to Use
- An xarray comparison unexpectedly loses timestamps, yields missing values, or broadcasts across unfamiliar dimensions.
- Two already-open datasets need to be checked for shared coordinates before arithmetic or merging.
- A forecast, observation, or simulation must be compared over a defined set of times or grid cells.
Use weather-model-data-fetching to obtain model inputs and weather-data-reproducibility to record provenance. This workflow starts with loaded or lazily opened xarray objects.
Inspect the coordinates
- Identify the variables, intended calculation, and dimensions that should match. Check
.dims,.sizes,.coords, and.xindexeson each input. Confirm that names such astime,valid_time, andsteprepresent the intended axes before renaming. Different dimension names can broadcast and create extra axes. - For each intended shared index, check uniqueness, label order, and the labels present on only one side. An unlabeled dimension needs an independently verified positional mapping. Equal dimension lengths alone are insufficient.
- Check value units and coordinate semantics. For time, verify the reference time, calendar, and whether a label denotes an instant or interval. For a grid, verify coordinate units, longitude convention, CRS, and any auxiliary latitude and longitude arrays. On a curvilinear grid, identical
yandxindexes can still correspond to different locations.
Choose the alignment policy
| Intended coverage | Operation | What to verify |
|---|---|---|
| Same indexed labels in the same order | xr.align(a, b, join="exact", copy=False) | Inspect the mismatch if alignment raises. |
| Shared labels only | xr.align(a, b, join="inner", copy=False) | Count labels dropped from each input and flag an empty overlap. |
| All labels from both inputs | xr.align(a, b, join="outer", copy=False) | Count introduced gaps and retain missing values unless the calculation defines a fill. |
| One input supplies the target labels | xr.align(a, b, join="left", copy=False) for a | Identify any target labels missing from the other input. |
Use explicit alignment before arithmetic. For adding variables from same-grid datasets, pass join="exact" to xr.merge and choose compat and combine_attrs explicitly. Use compat="no_conflicts" for complementary missing values only after confirming that overlapping variables have the same meaning and units. Conflicting nonmissing values require a resolution supported by the source data.
For different grids or sampling times, establish the intended interpolation, regridding, or calendar conversion method before proceeding. Record the target, tolerance or method, and resulting coverage.
Example
Compare two synthetic daily series. The requested result retains all days from both inputs and calculates simulated minus observed only where both values exist.
import numpy as np
import xarray as xr
observed = xr.DataArray(
[10.0, 12.0], dims="time",
coords={"time": np.array(["2026-01-01", "2026-01-02"], dtype="datetime64[D]")},
)
simulated = xr.DataArray(
[11.0, 13.0], dims="time",
coords={"time": np.array(["2026-01-02", "2026-01-03"], dtype="datetime64[D]")},
)
observed, simulated = xr.align(observed, simulated, join="outer", copy=False)
difference = simulated - observed
np.testing.assert_array_equal(
difference["time"].values.astype("datetime64[D]"),
np.array(["2026-01-01", "2026-01-02", "2026-01-03"], dtype="datetime64[D]"),
)
np.testing.assert_allclose(difference.values, [np.nan, -1.0, np.nan])
Verify and report
- Check output dimension names, sizes, coordinate labels, and a known overlap against the inputs.
- Report the join, coverage before and after, and unmatched labels or gap counts on each side. Distinguish gaps introduced by alignment from missing values already present.
- Inspect a representative slice before computing large results. Record the xarray version and any explicit conversions that affect the comparison.
Limitations
- Index alignment does not validate physical units, coordinate systems, or calendar equivalence.
- An outer join can expand several dimensions at once. Estimate the result size before materializing a lazy or large dataset.
- This workflow covers coordinate checks and labeled alignment. It leaves file retrieval, regridding, and exports to the surrounding workflow.
Safety and side effects
Use xarray in the existing Python environment with authorized inputs. The example uses NumPy and xarray in memory, with no accounts, network calls, or file writes. Accessing lazy values can read from the original backend, so use a bounded slice from the authorized source.