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.
MetPyDataArrayAccessor
MetPyDatasetAccessor
.metpy
See Also: xarray with MetPy Tutorial.
metpy.xarray.
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 sufficent metadata):
metpy
>>> 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)> array([-105, -104]) Coordinates: * lon (lon) int64 -105 -104 Attributes: _metpy_axis: x,longitude
assign_coordinates
Return new DataArray with given coordinates assigned to the given MetPy axis types.
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.
None
assign_crs
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.
metpy_crs
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).
.parse_cf
cf_attributes (dict, optional) – Dictionary of CF projection attributes
kwargs (optional) – CF projection attributes specified as keyword arguments
xarray.DataArray – New xarray DataArray with CRS coordinate assigned
xarray.DataArray
Notes
CF projection arguments should be supplied as a dictionary or collection of kwargs, but not both.
assign_latitude_longitude
Assign 2D latitude and longitude coordinates derived from 1D y and x coordinates.
force (bool, optional) – If force is true, overwrite latitude and longitude coordinates if they exist, otherwise, raise a RuntimeError if such coordinates exist.
xarray.DataArray – New xarray DataArray with latitude and longtiude auxilary coordinates assigned.
A valid CRS coordinate must be present (as assigned by .parse_cf or .assign_crs). PyProj is used for the coordinate transformations.
.assign_crs
assign_y_x
Assign 1D y and x dimension coordinates derived from 2D latitude and longitude.
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.
pint.Quantity
xarray.DataArray – New xarray DataArray with y and x dimension coordinates assigned.
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.
cartopy_crs
Return the coordinate reference system (CRS) as a cartopy object.
cartopy_geodetic
Return the cartopy Geodetic CRS associated with the native CRS globe.
cartopy_globe
Return the globe belonging to the coordinate reference system (CRS).
convert_coordinate_units
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).
.convert_units
Any cached/lazy-loaded coordinate data (except that in a Dask array) will be loaded into memory by this operation.
See also
convert_units
Return new DataArray with values converted to different units.
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
Return the coordinate variables corresponding to the given axes types.
args (str) – Strings describing the axes type(s) to obtain. Currently understood types are ‘time’, ‘vertical’, ‘y’, ‘latitude’, ‘x’, and ‘longitude’.
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.
coordinates_identical
Return whether or not the coordinates of other match this DataArray’s.
crs
Return the coordinate reference system (CRS) as a CFProjection object.
dequantify
Return a new DataArray with the data as magnitude and the units as an attribute.
find_axis_name
Return the name of the axis corresponding to the given identifier.
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
Return the dimension number of the axis corresponding to the given identifier.
latitude
Return the latitude coordinate (if it exists).
loc
Wrap DataArray.loc with an indexer to handle units and coordinate types.
longitude
Return the longitude coordinate (if it exists).
magnitude
Return the magnitude of the data values of this DataArray (i.e., without units).
pyproj_crs
Return the coordinate reference system (CRS) as a pyproj object.
quantify
Return a new DataArray with the data converted to a pint.Quantity.
sel
Wrap DataArray.sel to handle units and coordinate types.
time
Return the time coordinate.
time_deltas
Return the time difference of the data in seconds (to microsecond precision).
unit_array
Return the data values of this DataArray as a pint.Quantity.
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!
units
Return the units of this DataArray as a pint.Unit.
pint.Unit
vertical
Return the vertical coordinate.
x
Return the x coordinate.
y
Return the y coordinate.
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 a CRS to this Datatset based on CF projection attributes.
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).
xarray.Dataset – New xarray Dataset with CRS coordinate assigned
xarray.Dataset
parse_cf
Assign latitude and longitude coordinates derived from y and x coordinates.
xarray.Dataset – New xarray Dataset with latitude and longitude coordinates assigned to all variables with y and x coordinates.
Assign y and x dimension coordinates derived from 2D latitude and longitude.
xarray.Dataset – New xarray Dataset with y and x dimension coordinates assigned to all variables with valid latitude and longitude coordinates.
Return new dataset with variables cast to magnitude and units on attribute.
Wrap Dataset.loc with an indexer to handle units and coordinate types.
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 suprised if information not associated with individual data variables is not preserved.
varname (str or iterable of 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).
xarray.DataArray or xarray.Dataset – Parsed DataArray (if varname is a string) or Dataset
Return new dataset with all numeric variables quantified and cached data loaded.
Wrap Dataset.sel to handle units.
update_attribute
Return new Dataset with specified attribute updated on all Dataset variables.
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.
xarray.Dataset – New Dataset with attribute updated
grid_deltas_from_dataarray(f[, kind]) Calculate the horizontal deltas between grid points of a DataArray.
grid_deltas_from_dataarray(f[, kind])
grid_deltas_from_dataarray
Calculate the horizontal deltas between grid points of a DataArray.