Xarray Integration (metpy.xarray)#

Provide accessors to enhance interoperability between xarray and MetPy.

MetPy relies upon the CF Conventions. to provide helpful attributes and methods on xarray DataArrays and Dataset for working with coordinate-related metadata. Also included are several attributes and methods for unit operations.

These accessors will be activated with any import of MetPy. Do not use the MetPyDataArrayAccessor or MetPyDatasetAccessor classes directly, instead, utilize the applicable properties and methods via the .metpy attribute on an xarray DataArray or Dataset.

See Also: xarray with MetPy Tutorial.

Accessors#

class metpy.xarray.MetPyDataArrayAccessor[source]#

Provide custom attributes and methods on xarray DataArrays for MetPy functionality.

This accessor provides several convenient attributes and methods through the .metpy attribute on a DataArray. For example, MetPy can identify the coordinate corresponding to a particular axis (given sufficient metadata):

>>> import xarray as xr
>>> from metpy.units import units
>>> temperature = xr.DataArray([[0, 1], [2, 3]] * units.degC, dims=('lat', 'lon'),
...                            coords={'lat': [40, 41], 'lon': [-105, -104]})
>>> temperature.metpy.x
<xarray.DataArray 'lon' (lon: 2)> Size: 16B
array([-105, -104])
Coordinates:
  * lon      (lon) int64 16B -105 -104
Attributes:
    _metpy_axis:  x,longitude
assign_coordinates(coordinates)[source]#

Return new DataArray with given coordinates assigned to the given MetPy axis types.

Parameters:

coordinates (dict or None) – Mapping from axis types (‘time’, ‘vertical’, ‘y’, ‘latitude’, ‘x’, ‘longitude’) to coordinates of this DataArray. Coordinates can either be specified directly or by their name. If None, clears the _metpy_axis attribute on all coordinates, which will trigger reparsing of all coordinates on next access.

assign_crs(cf_attributes=None, **kwargs)[source]#

Assign a CRS to this DataArray based on CF projection attributes.

Specify a coordinate reference system/grid mapping following the Climate and Forecasting (CF) conventions (see Appendix F: Grid Mappings ) and store in the metpy_crs coordinate.

This method is only required if your data do not come from a dataset that follows CF conventions with respect to grid mappings (in which case the .parse_cf method will parse for the CRS metadata automatically).

Parameters:
  • cf_attributes (dict, optional) – Dictionary of CF projection attributes

  • kwargs (optional) – CF projection attributes specified as keyword arguments

Returns:

xarray.DataArray – New xarray DataArray with CRS coordinate assigned

Notes

CF projection arguments should be supplied as a dictionary or collection of kwargs, but not both.

assign_latitude_longitude(force=False)[source]#

Assign 2D latitude and longitude coordinates derived from 1D y and x coordinates.

Parameters:

force (bool, optional) – If force is true, overwrite latitude and longitude coordinates if they exist, otherwise, raise a RuntimeError if such coordinates exist.

Returns:

xarray.DataArray – New xarray DataArray with latitude and longtiude auxiliary coordinates assigned.

Notes

A valid CRS coordinate must be present (as assigned by .parse_cf or .assign_crs). PyProj is used for the coordinate transformations.

assign_y_x(force=False, tolerance=None)[source]#

Assign 1D y and x dimension coordinates derived from 2D latitude and longitude.

Parameters:
  • force (bool, optional) – If force is true, overwrite y and x coordinates if they exist, otherwise, raise a RuntimeError if such coordinates exist.

  • tolerance (pint.Quantity) – Maximum range tolerated when collapsing projected y and x coordinates from 2D to 1D. Defaults to 1 meter.

Returns:

xarray.DataArray – New xarray DataArray with y and x dimension coordinates assigned.

Notes

A valid CRS coordinate must be present (as assigned by .parse_cf or .assign_crs) for the y/x projection space. PyProj is used for the coordinate transformations.

property cartopy_crs[source]#

Return the coordinate reference system (CRS) as a cartopy object.

property cartopy_geodetic[source]#

Return the cartopy Geodetic CRS associated with the native CRS globe.

property cartopy_globe[source]#

Return the globe belonging to the coordinate reference system (CRS).

convert_coordinate_units(coord, units)[source]#

Return new DataArray with specified coordinate converted to different units.

This operation differs from .convert_units since xarray coordinate indexes do not yet support unit-aware arrays (even though unit-aware data arrays are).

See also

convert_units

Notes

Any cached/lazy-loaded coordinate data (except that in a Dask array) will be loaded into memory by this operation.

convert_to_base_units()[source]#

Return new DataArray with values converted to base units.

See also

convert_units

Notes

Any cached/lazy-loaded data (except that in a Dask array) will be loaded into memory by this operation. Do not utilize on moderate- to large-sized remote datasets before subsetting!

convert_units(units)[source]#

Return new DataArray with values converted to different units.

Notes

Any cached/lazy-loaded data (except that in a Dask array) will be loaded into memory by this operation. Do not utilize on moderate- to large-sized remote datasets before subsetting!

coordinates(*args)[source]#

Return the coordinate variables corresponding to the given axes types.

Parameters:

args (str) – Strings describing the axes type(s) to obtain. Currently understood types are ‘time’, ‘vertical’, ‘y’, ‘latitude’, ‘x’, and ‘longitude’.

Notes

This method is designed for use with multiple coordinates; it returns a generator. To access a single coordinate, use the appropriate attribute on the accessor, or use tuple unpacking.

If latitude and/or longitude are requested here, and yet are not present on the DataArray, an on-the-fly computation from the CRS and y/x dimension coordinates is attempted.

coordinates_identical(other)[source]#

Return whether the coordinates of other match this DataArray’s.

property crs[source]#

Return the coordinate reference system (CRS) as a CFProjection object.

dequantify()[source]#

Return a new DataArray with the data as magnitude and the units as an attribute.

find_axis_name(axis)[source]#

Return the name of the axis corresponding to the given identifier.

Parameters:

axis (str or int) – Identifier for an axis. Can be an axis number (integer), dimension coordinate name (string) or a standard axis type (string).

find_axis_number(axis)[source]#

Return the dimension number of the axis corresponding to the given identifier.

Parameters:

axis (str or int) – Identifier for an axis. Can be an axis number (integer), dimension coordinate name (string) or a standard axis type (string).

property grid_deltas[source]#

Return the horizontal dimensional grid deltas suitable for vector derivatives.

property latitude[source]#

Return the latitude coordinate (if it exists).

property loc[source]#

Wrap DataArray.loc with an indexer to handle units and coordinate types.

property longitude[source]#

Return the longitude coordinate (if it exists).

property magnitude[source]#

Return the magnitude of the data values of this DataArray (i.e., without units).

property pyproj_crs[source]#

Return the coordinate reference system (CRS) as a pyproj object.

property pyproj_proj[source]#

Return the Proj object corresponding to the coordinate reference system (CRS).

quantify()[source]#

Return a new DataArray with the data converted to a pint.Quantity.

Notes

Any cached/lazy-loaded data (except that in a Dask array) will be loaded into memory by this operation. Do not utilize on moderate- to large-sized remote datasets before subsetting!

sel(indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs)[source]#

Wrap DataArray.sel to handle units and coordinate types.

property time[source]#

Return the time coordinate.

property time_deltas[source]#

Return the time difference of the data in seconds (to microsecond precision).

property unit_array[source]#

Return the data values of this DataArray as a pint.Quantity.

Notes

If not already existing as a pint.Quantity or Dask array, the data of this DataArray will be loaded into memory by this operation. Do not utilize on moderate- to large-sized remote datasets before subsetting!

property units[source]#

Return the units of this DataArray as a pint.Unit.

property vertical[source]#

Return the vertical coordinate.

property x[source]#

Return the x coordinate.

property y[source]#

Return the y coordinate.

class metpy.xarray.MetPyDatasetAccessor[source]#

Provide custom attributes and methods on XArray Datasets for MetPy functionality.

This accessor provides parsing of CF grid mapping metadata, generating missing coordinate types, and unit-/coordinate-type-aware operations.

>>> import xarray as xr
>>> from metpy.cbook import get_test_data
>>> ds = xr.open_dataset(get_test_data('narr_example.nc', False)).metpy.parse_cf()
>>> print(ds['metpy_crs'].item())
Projection: lambert_conformal_conic
assign_crs(cf_attributes=None, **kwargs)[source]#

Assign a CRS to this Dataset based on CF projection attributes.

Specify a coordinate reference system/grid mapping following the Climate and Forecasting (CF) conventions (see Appendix F: Grid Mappings ) and store in the metpy_crs coordinate.

This method is only required if your dataset does not already follow CF conventions with respect to grid mappings (in which case the .parse_cf method will parse for the CRS metadata automatically).

Parameters:
  • cf_attributes (dict, optional) – Dictionary of CF projection attributes

  • kwargs (optional) – CF projection attributes specified as keyword arguments

Returns:

xarray.Dataset – New xarray Dataset with CRS coordinate assigned

See also

parse_cf

Notes

CF projection arguments should be supplied as a dictionary or collection of kwargs, but not both.

assign_latitude_longitude(force=False)[source]#

Assign latitude and longitude coordinates derived from y and x coordinates.

Parameters:

force (bool, optional) – If force is true, overwrite latitude and longitude coordinates if they exist, otherwise, raise a RuntimeError if such coordinates exist.

Returns:

xarray.Dataset – New xarray Dataset with latitude and longitude coordinates assigned to all variables with y and x coordinates.

Notes

A valid CRS coordinate must be present (as assigned by .parse_cf or .assign_crs). PyProj is used for the coordinate transformations.

assign_y_x(force=False, tolerance=None)[source]#

Assign y and x dimension coordinates derived from 2D latitude and longitude.

Parameters:
  • force (bool, optional) – If force is true, overwrite y and x coordinates if they exist, otherwise, raise a RuntimeError if such coordinates exist.

  • tolerance (pint.Quantity) – Maximum range tolerated when collapsing projected y and x coordinates from 2D to 1D. Defaults to 1 meter.

Returns:

xarray.Dataset – New xarray Dataset with y and x dimension coordinates assigned to all variables with valid latitude and longitude coordinates.

Notes

A valid CRS coordinate must be present (as assigned by .parse_cf or .assign_crs). PyProj is used for the coordinate transformations.

dequantify()[source]#

Return new dataset with variables cast to magnitude and units on attribute.

property loc[source]#

Wrap Dataset.loc with an indexer to handle units and coordinate types.

parse_cf(varname=None, coordinates=None)[source]#

Parse dataset for coordinate system metadata according to CF conventions.

Interpret the grid mapping metadata in the dataset according to the Climate and Forecasting (CF) conventions (see Appendix F: Grid Mappings ) and store in the metpy_crs coordinate. Also, gives option to manually specify coordinate types with the coordinates keyword argument.

If your dataset does not follow the CF conventions, you can manually supply the grid mapping metadata with the .assign_crs method.

This method operates on individual data variables within the dataset, so do not be surprised if information not associated with individual data variables is not preserved.

Parameters:
  • varname (str or Sequence[str], optional) – Name of the variable(s) to extract from the dataset while parsing for CF metadata. Defaults to all variables.

  • coordinates (dict, optional) – Dictionary mapping CF axis types to coordinates of the variable(s). Only specify if you wish to override MetPy’s automatic parsing of some axis type(s).

Returns:

xarray.DataArray or xarray.Dataset – Parsed DataArray (if varname is a string) or Dataset

See also

assign_crs

quantify()[source]#

Return new dataset with all numeric variables quantified and cached data loaded.

Notes

Any cached/lazy-loaded data (except that in a Dask array) will be loaded into memory by this operation. Do not utilize on moderate- to large-sized remote datasets before subsetting!

sel(indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs)[source]#

Wrap Dataset.sel to handle units.

update_attribute(attribute, mapping)[source]#

Return new Dataset with specified attribute updated on all Dataset variables.

Parameters:
  • attribute (str,) – Name of attribute to update

  • mapping (dict or Callable) – Either a dict, with keys as variable names and values as attribute values to set, or a callable, which must accept one positional argument (variable name) and arbitrary keyword arguments (all existing variable attributes). If a variable name is not present/the callable returns None, the attribute will not be updated.

Returns:

xarray.Dataset – New Dataset with attribute updated

Functions#

grid_deltas_from_dataarray(f[, kind])

Calculate the horizontal deltas between grid points of a DataArray.