API reference¶
This page provides an auto-generated summary of xarray’s API. For more details and examples, refer to the relevant chapters in the main part of the documentation.
See also: What parts of xarray are considered public API?
Top-level functions¶
|
Apply a vectorized function for unlabeled arrays on xarray objects. |
|
Given any number of Dataset and/or DataArray objects, returns new objects with aligned indexes and dimension sizes. |
|
Explicitly broadcast any number of DataArray or Dataset objects against one another. |
|
Concatenate xarray objects along a new or existing dimension. |
|
Merge any number of xarray objects into a single Dataset as variables. |
|
Attempt to auto-magically combine the given datasets into one by using dimension coordinates. |
|
Explicitly combine an N-dimensional grid of datasets into one by using a succession of concat and merge operations along each dimension of the grid. |
|
Return elements from x or y depending on cond. |
|
Set options for xarray in a controlled context. |
|
Infer the most likely frequency given the input index. |
|
Return a new object with the same shape and type as a given object. |
|
Return a new object of zeros with the same shape and type as a given dataarray or dataset. |
|
Return a new object of ones with the same shape and type as a given dataarray or dataset. |
|
Compute covariance between two DataArray objects along a shared dimension. |
|
Compute the Pearson correlation coefficient between two DataArray objects along a shared dimension. |
|
Generalized dot product for xarray objects. |
|
Evaluate a polynomial at specific values |
|
Apply a function to each block of a DataArray or Dataset. |
|
print the versions of xarray and its dependencies |
|
Set options for xarray in a controlled context. |
Dataset¶
Creating a dataset¶
|
A multi-dimensional, in memory, array database. |
|
Decode the given Dataset or Datastore according to CF conventions into a new Dataset. |
Attributes¶
Mapping from dimension names to lengths. |
|
Mapping from dimension names to lengths. |
|
Dictionary of DataArray objects corresponding to data variables |
|
Dictionary of xarray.DataArray objects corresponding to coordinate variables |
|
Dictionary of global attributes on this dataset |
|
Dictionary of global encoding attributes on this dataset |
|
Mapping of pandas.Index objects used for label based indexing |
|
|
Get an index for a dimension, with fall-back to a default RangeIndex |
Block dimensions for this dataset’s data or None if it’s not a dask array. |
|
Dictionary interface¶
Datasets implement the mapping interface with keys given by variable names
and values given by DataArray
objects.
Access variables or coordinates this dataset as a |
|
|
Add an array to this dataset. |
|
Remove a variable from this dataset. |
|
Update this dataset’s variables with those from another dataset. |
|
|
Dataset contents¶
|
Returns a copy of this dataset. |
|
Assign new data variables to a Dataset, returning a new object with all the original variables in addition to the new ones. |
|
Assign new coordinates to this object. |
|
Assign new attrs to this object. |
|
Apply |
|
Merge the arrays of two datasets into a single dataset. |
|
Returns a new object with renamed variables and dimensions. |
|
Returns a new object with renamed variables including coordinates |
|
Returns a new object with renamed dimensions only. |
|
Returns a new object with swapped dimensions. |
|
Return a new object with an additional axis (or axes) inserted at the corresponding position in the array shape. |
|
Drop variables from this dataset. |
|
Drop dimensions and associated variables from this dataset. |
|
Given names of one or more variables, set them as coordinates |
|
Given names of coordinates, reset them to become variables |
Comparisons¶
|
Two Datasets are equal if they have matching variables and coordinates, all of which are equal. |
|
Like equals, but also checks all dataset attributes and the attributes on all variables and coordinates. |
|
Two Datasets are broadcast equal if they are equal after broadcasting all variables against each other. |
Indexing¶
Attribute for location based indexing. |
|
|
Returns a new dataset with each array indexed along the specified dimension(s). |
|
Returns a new dataset with each array indexed by tick labels along the specified dimension(s). |
|
Drop index labels from this dataset. |
|
Returns a new dataset with the first n values of each array for the specified dimension(s). |
|
Returns a new dataset with the last n values of each array for the specified dimension(s). |
|
Returns a new dataset with each array indexed along every n-th value for the specified dimension(s) |
|
Return a new object with squeezed data. |
|
Multidimensional interpolation of Dataset. |
|
Interpolate this object onto the coordinates of another object, filling the out of range values with NaN. |
|
Conform this object onto a new set of indexes, filling in missing values with |
|
Conform this object onto the indexes of another object, filling in missing values with |
|
Set Dataset (multi-)indexes using one or more existing coordinates or variables. |
|
Reset the specified index(es) or multi-index level(s). |
|
Rearrange index levels using input order. |
Missing value handling¶
|
|
|
|
|
Combine two Datasets, default to data_vars of self. |
|
Reduce this Dataset’s data by applying count along some dimension(s). |
|
Returns a new dataset with dropped labels for missing values along the provided dimension. |
|
Fill missing values in this object. |
|
Fill NaN values by propogating values forward |
|
Fill NaN values by propogating values backward |
|
Fill in NaNs by interpolating according to different methods. |
|
Filter elements from this object according to a condition. |
|
Tests each value in the array for whether it is in test elements. |
Computation¶
|
Apply a function to each variable in this dataset |
|
Reduce this dataset by applying func along some dimension(s). |
|
Returns a GroupBy object for performing grouped operations. |
|
Returns a GroupBy object for performing grouped operations. |
|
Rolling window object. |
|
Exponentially-weighted moving window. |
|
Weighted operations. |
|
Coarsen object. |
|
Returns a Resample object for performing resampling operations. |
|
Calculate the n-th order discrete difference along given axis. |
|
Compute the qth quantile of the data along the specified dimension. |
|
Differentiate with the second order accurate central differences. |
|
integrate the array with the trapezoidal rule. |
|
Apply a function to each block of this Dataset. |
|
Least squares polynomial fit. |
Aggregation:
all
any
argmax
argmin
idxmax
idxmin
max
mean
median
min
prod
sum
std
var
ndarray methods:
astype
argsort
clip
conj
conjugate
imag
round
real
cumsum
cumprod
rank
Grouped operations:
assign
assign_coords
first
last
fillna
where
quantile
Reshaping and reorganizing¶
|
Return a new Dataset object with all array dimensions transposed. |
|
Stack any number of existing dimensions into a single new dimension. |
|
Unstack existing dimensions corresponding to MultiIndexes into multiple new dimensions. |
|
Combine variables of differing dimensionality into a DataArray without broadcasting. |
|
Shift this dataset by an offset along one or more dimensions. |
|
Roll this dataset by an offset along one or more dimensions. |
|
Pad this dataset along one or more dimensions. |
|
Sort object by labels or values (along an axis). |
|
Broadcast this DataArray against another Dataset or DataArray. |
Plotting¶
|
Scatter Dataset data variables against each other. |
DataArray¶
|
N-dimensional array with labeled coordinates and dimensions. |
Attributes¶
The array’s data as a numpy.ndarray |
|
The array’s data as a dask or numpy array |
|
Dictionary-like container of coordinate arrays. |
|
Tuple of dimension names associated with this array. |
|
Ordered mapping from dimension names to lengths. |
|
The name of this array. |
|
Dictionary storing arbitrary metadata with this array. |
|
Dictionary of format-specific settings for how this array should be serialized. |
|
Mapping of pandas.Index objects used for label based indexing |
|
|
Get an index for a dimension, with fall-back to a default RangeIndex |
DataArray contents¶
|
Assign new coordinates to this object. |
|
Assign new attrs to this object. |
|
Apply |
|
Returns a new DataArray with renamed coordinates or a new name. |
|
Returns a new DataArray with swapped dimensions. |
|
Return a new object with an additional axis (or axes) inserted at the corresponding position in the array shape. |
|
Drop variables from this DataArray. |
|
Given names of coordinates, reset them to become variables. |
|
Returns a copy of this array. |
Indexing¶
|
|
Attribute for location based indexing like pandas. |
|
|
Return a new DataArray whose data is given by integer indexing along the specified dimension(s). |
|
Return a new DataArray whose data is given by selecting index labels along the specified dimension(s). |
|
Drop index labels from this DataArray. |
|
Return a new DataArray whose data is given by the the first n values along the specified dimension(s). |
|
Return a new DataArray whose data is given by the the last n values along the specified dimension(s). |
|
Return a new DataArray whose data is given by each n value along the specified dimension(s). |
|
Return a new object with squeezed data. |
|
Multidimensional interpolation of variables. |
|
Interpolate this object onto the coordinates of another object, filling out of range values with NaN. |
|
Conform this object onto the indexes of another object, filling in missing values with |
|
Conform this object onto the indexes of another object, filling in missing values with |
|
Set DataArray (multi-)indexes using one or more existing coordinates. |
|
Reset the specified index(es) or multi-index level(s). |
|
Rearrange index levels using input order. |
Missing value handling¶
|
|
|
|
|
Combine two DataArray objects, with union of coordinates. |
|
Reduce this DataArray’s data by applying count along some dimension(s). |
|
Returns a new array with dropped labels for missing values along the provided dimension. |
|
Fill missing values in this object. |
|
Fill NaN values by propogating values forward |
|
Fill NaN values by propogating values backward |
|
Fill in NaNs by interpolating according to different methods. |
|
Filter elements from this object according to a condition. |
|
Tests each value in the array for whether it is in test elements. |
Comparisons¶
|
True if two DataArrays have the same dimensions, coordinates and values; otherwise False. |
|
Like equals, but also checks the array name and attributes, and attributes on all coordinates. |
|
Two DataArrays are broadcast equal if they are equal after broadcasting them against each other such that they have the same dimensions. |
Computation¶
|
Reduce this array by applying func along some dimension(s). |
|
Returns a GroupBy object for performing grouped operations. |
|
Returns a GroupBy object for performing grouped operations. |
|
Rolling window object. |
|
Exponentially-weighted moving window. |
|
Weighted operations. |
|
Coarsen object. |
|
Returns a Resample object for performing resampling operations. |
Return axis number(s) corresponding to dimension(s) in this array. |
|
|
Calculate the n-th order discrete difference along given axis. |
|
Perform dot product of two DataArrays along their shared dims. |
|
Compute the qth quantile of the data along the specified dimension. |
|
Differentiate the array with the second order accurate central differences. |
|
integrate the array with the trapezoidal rule. |
|
Least squares polynomial fit. |
|
Apply a function to each block of this DataArray. |
Aggregation:
all
any
argmax
argmin
idxmax
idxmin
max
mean
median
min
prod
sum
std
var
ndarray methods:
argsort
clip
conj
conjugate
imag
searchsorted
round
real
T
cumsum
cumprod
rank
Grouped operations:
assign_coords
first
last
fillna
where
quantile
String manipulation¶
Convert strings in the array to be capitalized. |
|
|
Filling left and right side of strings in the array with an additional character. |
|
Test if pattern or regex is contained within a string of the array. |
|
Count occurrences of pattern in each string of the array. |
|
Decode character string in the array using indicated encoding. |
|
Encode character string in the array using indicated encoding. |
Test if the end of each string element matches a pattern. |
|
|
Return lowest or highest indexes in each strings in the array where the substring is fully contained between [start:end]. |
Extract element from indexable in each element in the array. |
|
|
Return lowest or highest indexes in each strings where the substring is fully contained between [start:end]. |
Check whether all characters in each string are alphanumeric. |
|
Check whether all characters in each string are alphabetic. |
|
Check whether all characters in each string are decimal. |
|
Check whether all characters in each string are digits. |
|
Check whether all characters in each string are numeric. |
|
Check whether all characters in each string are spaces. |
|
Check whether all characters in each string are titlecase. |
|
Check whether all characters in each string are uppercase. |
|
Compute the length of each element in the array. |
|
|
Filling right side of strings in the array with an additional character. |
Convert strings in the array to lowercase. |
|
|
Remove leading and trailing characters. |
|
Determine if each string matches a regular expression. |
|
Pad strings in the array up to width. |
|
Duplicate each string in the array. |
|
Replace occurrences of pattern/regex in the array with some string. |
|
Return highest indexes in each strings in the array where the substring is fully contained between [start:end]. |
|
Return highest indexes in each strings where the substring is fully contained between [start:end]. |
|
Filling left side of strings in the array with an additional character. |
|
Remove leading and trailing characters. |
|
Slice substrings from each element in the array. |
|
Replace a positional slice of a string with another value. |
Test if the start of each string element matches a pattern. |
|
|
Remove leading and trailing characters. |
Convert strings in the array to be swapcased. |
|
Convert strings in the array to titlecase. |
|
|
Map all characters in the string through the given mapping table. |
Convert strings in the array to uppercase. |
|
|
Wrap long strings in the array to be formatted in paragraphs with length less than a given width. |
|
Pad strings in the array by prepending ‘0’ characters. |
Datetimelike properties¶
Datetime properties:
The year of the datetime |
|
The month as January=1, December=12 |
|
The days of the datetime |
|
The hours of the datetime |
|
The minutes of the datetime |
|
The seconds of the datetime |
|
The microseconds of the datetime |
|
The nanoseconds of the datetime |
|
The week ordinal of the year |
|
The week ordinal of the year |
|
The day of the week with Monday=0, Sunday=6 |
|
The day of the week with Monday=0, Sunday=6 |
|
The name of day in a week |
|
The ordinal day of the year |
|
The quarter of the date |
|
The number of days in the month |
|
The number of days in the month |
|
Season of the year |
|
Timestamps corresponding to datetimes |
|
Indicates whether the date is the first day of the month. |
|
Indicates whether the date is the last day of the month. |
|
Indicator for whether the date is the last day of a quarter. |
|
Indicate whether the date is the first day of a year. |
|
Boolean indicator if the date belongs to a leap year. |
Datetime methods:
|
Round timestamps downward to specified frequency resolution. |
|
Round timestamps upward to specified frequency resolution. |
|
Round timestamps to specified frequency resolution. |
|
Return an array of formatted strings specified by date_format, which supports the same string format as the python standard library. |
Timedelta properties:
Number of days for each element. |
|
Number of seconds (>= 0 and less than 1 day) for each element. |
|
Number of microseconds (>= 0 and less than 1 second) for each element. |
|
Number of nanoseconds (>= 0 and less than 1 microsecond) for each element. |
Timedelta methods:
|
Round timestamps downward to specified frequency resolution. |
|
Round timestamps upward to specified frequency resolution. |
|
Round timestamps to specified frequency resolution. |
Reshaping and reorganizing¶
|
Return a new DataArray object with transposed dimensions. |
|
Stack any number of existing dimensions into a single new dimension. |
|
Unstack existing dimensions corresponding to MultiIndexes into multiple new dimensions. |
|
Unstack DataArray expanding to Dataset along a given level of a stacked coordinate. |
|
Shift this array by an offset along one or more dimensions. |
|
Roll this array by an offset along one or more dimensions. |
|
Pad this array along one or more dimensions. |
|
Sort object by labels or values (along an axis). |
|
Broadcast this DataArray against another Dataset or DataArray. |
Plotting¶
alias of |
|
Filled contour plot of 2d DataArray |
|
Contour plot of 2d DataArray |
|
Histogram of DataArray |
|
Image plot of 2d DataArray using matplotlib.pyplot |
|
Line plot of DataArray index against values |
|
Pseudocolor plot of 2d DataArray |
|
Step plot of DataArray index against values |
Universal functions¶
Warning
With recent versions of numpy, dask and xarray, NumPy ufuncs are now
supported directly on all xarray and dask objects. This obviates the need
for the xarray.ufuncs
module, which should not be used for new code
unless compatibility with versions of NumPy prior to v1.13 is required.
These functions are copied from NumPy, but extended to work on NumPy arrays,
dask arrays and all xarray objects. You can find them in the xarray.ufuncs
module:
angle
arccos
arccosh
arcsin
arcsinh
arctan
arctan2
arctanh
ceil
conj
copysign
cos
cosh
deg2rad
degrees
exp
expm1
fabs
fix
floor
fmax
fmin
fmod
fmod
frexp
hypot
imag
iscomplex
isfinite
isinf
isnan
isreal
ldexp
log
log10
log1p
log2
logaddexp
logaddexp2
logical_and
logical_not
logical_or
logical_xor
maximum
minimum
nextafter
rad2deg
radians
real
rint
sign
signbit
sin
sinh
sqrt
square
tan
tanh
trunc
IO / Conversion¶
Dataset methods¶
|
Open and decode a dataset from a file or file-like object. |
|
Open, load into memory, and close a Dataset from a file or file-like object. |
|
Open multiple files as a single dataset. |
|
Open a file with rasterio (experimental). |
|
Load and decode a dataset from a Zarr store. |
|
Write dataset contents to a netCDF file. |
|
Write dataset contents to a zarr group. |
|
Write multiple datasets to disk as netCDF files simultaneously. |
|
Convert this dataset into an xarray.DataArray |
Convert this dataset into a pandas.DataFrame. |
|
|
Convert this dataset into a dask.dataframe.DataFrame. |
|
Convert this dataset to a dictionary following xarray naming conventions. |
|
Convert a pandas.DataFrame into an xarray.Dataset |
Convert a dictionary into an xarray.Dataset. |
|
Close any files linked to this object |
|
|
Manually trigger loading and/or computation of this dataset’s data from disk or a remote source into memory and return a new dataset. |
|
Trigger computation, keeping data as dask arrays |
|
Manually trigger loading and/or computation of this dataset’s data from disk or a remote source into memory and return this dataset. |
|
Coerce all arrays in this dataset into dask arrays with the given chunks. |
Unify chunk size along all chunked dimensions of this Dataset. |
|
|
Returns a |
|
Concise summary of a Dataset variables and attributes. |
DataArray methods¶
|
Open an DataArray from a file or file-like object containing a single data variable. |
|
Open, load into memory, and close a DataArray from a file or file-like object containing a single data variable. |
|
Convert a DataArray to a Dataset. |
|
Write DataArray contents to a netCDF file. |
Convert this array into a pandas object with the same shape. |
|
Convert this array into a pandas.Series. |
|
|
Convert this array and its coordinates into a tidy pandas.DataFrame. |
Convert this variable to a pandas.Index. |
|
|
Convert this array into a numpy.ma.MaskedArray |
Convert this array into a cdms2.Variable |
|
Convert this array into a iris.cube.Cube |
|
|
Convert a iris.cube.Cube into an xarray.DataArray |
|
Convert this xarray.DataArray into a dictionary following xarray naming conventions. |
|
Convert a pandas.Series into an xarray.DataArray. |
|
Convert a cdms2.Variable into an xarray.DataArray |
Convert a dictionary into an xarray.DataArray |
|
Close any files linked to this object |
|
|
Manually trigger loading of this array’s data from disk or a remote source into memory and return a new array. |
|
Trigger computation in constituent dask arrays |
|
Manually trigger loading of this array’s data from disk or a remote source into memory and return this array. |
|
Coerce this array’s data into a dask arrays with the given chunks. |
Unify chunk size along all chunked dimensions of this DataArray. |
Coordinates objects¶
|
Dictionary like container for DataArray coordinates. |
|
Dictionary like container for Dataset coordinates. |
GroupBy objects¶
|
GroupBy object specialized to grouping DataArray objects |
|
Apply a function to each array in the group and concatenate them together into a new array. |
|
Reduce the items in this group by applying func along some dimension(s). |
|
|
|
Apply a function to each Dataset in the group and concatenate them together into a new Dataset. |
|
Reduce the items in this group by applying func along some dimension(s). |
Rolling objects¶
|
|
Convert this rolling object to xr.DataArray, where the window dimension is stacked as a new dimension |
|
|
Reduce the items in this group by applying func along some dimension(s). |
|
|
|
Convert this rolling object to xr.Dataset, where the window dimension is stacked as a new dimension |
|
Reduce the items in this group by applying func along some dimension(s). |
|
Exponentially-weighted moving window object. |
Weighted objects¶
|
|
|
Reduce this Dataset’s data by a weighted |
|
Reduce this Dataset’s data by a weighted |
Calculate the sum of weights, accounting for missing values in the data |
|
|
|
|
Reduce this Dataset’s data by a weighted |
|
Reduce this Dataset’s data by a weighted |
Calculate the sum of weights, accounting for missing values in the data |
Coarsen objects¶
|
|
|
Resample objects¶
Resample objects also implement the GroupBy interface
(methods like map()
, reduce()
, mean()
, sum()
, etc.).
|
DataArrayGroupBy object specialized to time resampling operations over a specified dimension |
Return values of original object at the new up-sampling frequency; essentially a re-index with new times set to NaN. |
|
Backward fill new values at up-sampled frequency. |
|
Interpolate up-sampled data using the original data as knots. |
|
Take new values from nearest original coordinate to up-sampled frequency coordinates. |
|
|
Forward fill new values at up-sampled frequency. |
|
DatasetGroupBy object specialized to resampling a specified dimension |
Return values of original object at the new up-sampling frequency; essentially a re-index with new times set to NaN. |
|
Backward fill new values at up-sampled frequency. |
|
Interpolate up-sampled data using the original data as knots. |
|
Take new values from nearest original coordinate to up-sampled frequency coordinates. |
|
|
Forward fill new values at up-sampled frequency. |
Accessors¶
Access datetime fields for DataArrays with datetime-like dtypes. |
|
Access Timedelta fields for DataArrays with Timedelta-like dtypes. |
|
Vectorized string functions for string-like arrays. |
Custom Indexes¶
|
Custom Index for working with CF calendars and dates |
Creating custom indexes¶
|
Return a fixed frequency CFTimeIndex. |
Faceting¶
|
Initialize the matplotlib figure and FacetGrid object. |
|
Draw a colorbar |
|
|
|
Apply a plotting function to each facet’s subset of the data. |
|
Apply a plotting function to a 2d facet’s subset of the data. |
|
|
|
|
|
Set axis labels on the left column and bottom row of the grid. |
|
Set and control tick behavior |
|
Draw titles either above each facet or on the grid margins. |
|
Label the x axis on the bottom row of the grid. |
|
Label the y axis on the left column of the grid. |
Tutorial¶
|
Open a dataset from the online repository (requires internet). |
|
Open, load into memory, and close a dataset from the online repository (requires internet). |
Testing¶
|
Like |
|
Like |
|
Like |
Assert that chunksizes along chunked dimensions are equal. |
Exceptions¶
Error class for merge failures due to incompatible arguments. |
|
Warnings about encoding/decoding issues in serialization. |
Advanced API¶
Low level interface to Dataset contents as dict of Variable objects. |
|
Low level interface to the Variable object for this DataArray. |
|
|
A netcdf-like variable consisting of dimensions, data and attributes which describe a single Array. |
|
Wrapper for accommodating a pandas.Index in an xarray.Variable. |
|
Convert an object into a Variable. |
Register a custom property on xarray.Dataset objects. |
|
Register a custom accessor on xarray.DataArray objects. |
These backends provide a low-level interface for lazily loading data from
external file-formats or protocols, and can be manually invoked to create
arguments for the load_store
and dump_to_store
Dataset methods:
|
Store for reading and writing data via the Python-NetCDF4 library. |
|
Store for reading and writing data via h5netcdf |
Store for accessing OpenDAP datasets with pydap. |
|
|
Store for reading and writing data via scipy.io.netcdf. |
Manager for acquiring and closing a file object. |
|
|
Wrapper for automatically opening and closing file objects. |
|
FileManager that simply wraps an open file in the FileManager interface. |
Deprecated / Pending Deprecation¶
|
Backward compatible method based on drop_vars and drop_sel |
|
Backward compatible method based on drop_vars and drop_sel |
|
Backward compatible implementation of |
|
Backward compatible implementation of |
|
Backward compatible implementation of |