INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Roll date forward to nearest end of year
def rollforward(self, date): """Roll date forward to nearest end of year""" if self.onOffset(date): return date else: return date + YearEnd(month=self.month)
Roll date backward to nearest end of year
def rollback(self, date): """Roll date backward to nearest end of year""" if self.onOffset(date): return date else: return date - YearEnd(month=self.month)
Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary
def pretty_print(x, numchars): """Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary """ s = maybe_truncate(x, numchars) return s + ' ' * max(numchars - len(s), 0)
Returns the first n_desired items of an array
def first_n_items(array, n_desired): """Returns the first n_desired items of an array""" # Unfortunately, we can't just do array.flat[:n_desired] here because it # might not be a numpy.ndarray. Moreover, access to elements of the array # could be very expensive (e.g. if it's only available over DAP), so...
Returns the last n_desired items of an array
def last_n_items(array, n_desired): """Returns the last n_desired items of an array""" # Unfortunately, we can't just do array.flat[-n_desired:] here because it # might not be a numpy.ndarray. Moreover, access to elements of the array # could be very expensive (e.g. if it's only available over DAP), so ...
Returns the last item of an array in a list or an empty list.
def last_item(array): """Returns the last item of an array in a list or an empty list.""" if array.size == 0: # work around for https://github.com/numpy/numpy/issues/5195 return [] indexer = (slice(-1, None),) * array.ndim return np.ravel(array[indexer]).tolist()
Cast given object to a Timestamp and return a nicely formatted string
def format_timestamp(t): """Cast given object to a Timestamp and return a nicely formatted string""" # Timestamp is only valid for 1678 to 2262 try: datetime_str = str(pd.Timestamp(t)) except OutOfBoundsDatetime: datetime_str = str(t) try: date_str, time_str = datetime_str.s...
Cast given object to a Timestamp and return a nicely formatted string
def format_timedelta(t, timedelta_format=None): """Cast given object to a Timestamp and return a nicely formatted string""" timedelta_str = str(pd.Timedelta(t)) try: days_str, time_str = timedelta_str.split(' days ') except ValueError: # catch NaT and others that don't split nicely ...
Returns a succinct summary of an object as a string
def format_item(x, timedelta_format=None, quote_strings=True): """Returns a succinct summary of an object as a string""" if isinstance(x, (np.datetime64, datetime)): return format_timestamp(x) if isinstance(x, (np.timedelta64, timedelta)): return format_timedelta(x, timedelta_format=timedelt...
Returns a succinct summaries of all items in a sequence as strings
def format_items(x): """Returns a succinct summaries of all items in a sequence as strings""" x = np.asarray(x) timedelta_format = 'datetime' if np.issubdtype(x.dtype, np.timedelta64): x = np.asarray(x, dtype='timedelta64[ns]') day_part = (x[~pd.isnull(x)] .astype('ti...
Return a formatted string for as many items in the flattened version of array that will fit within max_width characters.
def format_array_flat(array, max_width): """Return a formatted string for as many items in the flattened version of array that will fit within max_width characters. """ # every item will take up at least two characters, but we always want to # print at least first and last items max_possibly_rel...
Summary for __repr__ - use ``X.attrs[key]`` for full value.
def summarize_attr(key, value, col_width=None): """Summary for __repr__ - use ``X.attrs[key]`` for full value.""" # Indent key and add ':', then right-pad if col_width is not None k_str = ' {}:'.format(key) if col_width is not None: k_str = pretty_print(k_str, col_width) # Replace tabs an...
Get all column items to format, including both keys of `mapping` and MultiIndex levels if any.
def _get_col_items(mapping): """Get all column items to format, including both keys of `mapping` and MultiIndex levels if any. """ from .variable import IndexVariable col_items = [] for k, v in mapping.items(): col_items.append(k) var = getattr(v, 'variable', v) if isins...
Similar to dask.array.DataArray.__repr__, but without redundant information that's already printed by the repr function of the xarray wrapper.
def short_dask_repr(array, show_dtype=True): """Similar to dask.array.DataArray.__repr__, but without redundant information that's already printed by the repr function of the xarray wrapper. """ chunksize = tuple(c[0] for c in array.chunks) if show_dtype: return 'dask.array<shape={}, dty...
Dispatch function to call appropriate up-sampling methods on data. This method should not be called directly; instead, use one of the wrapper functions supplied by `Resample`. Parameters ---------- method : str {'asfreq', 'pad', 'ffill', 'backfill', 'bfill', 'nearest', ...
def _upsample(self, method, *args, **kwargs): """Dispatch function to call appropriate up-sampling methods on data. This method should not be called directly; instead, use one of the wrapper functions supplied by `Resample`. Parameters ---------- method : str {'...
Apply scipy.interpolate.interp1d along resampling dimension.
def _interpolate(self, kind='linear'): """Apply scipy.interpolate.interp1d along resampling dimension.""" # drop any existing non-dimension coordinates along the resampling # dimension dummy = self._obj.copy() for k, v in self._obj.coords.items(): if k != self._dim an...
Apply a function over each array in the group and concatenate them together into a new array. `func` is called like `func(ar, *args, **kwargs)` for each array `ar` in this group. Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how to stack together the array. ...
def apply(self, func, shortcut=False, args=(), **kwargs): """Apply a function over each array in the group and concatenate them together into a new array. `func` is called like `func(ar, *args, **kwargs)` for each array `ar` in this group. Apply uses heuristics (like `pandas.Gr...
Apply a function over each Dataset in the groups generated for resampling and concatenate them together into a new Dataset. `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds` in this group. Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how ...
def apply(self, func, args=(), **kwargs): """Apply a function over each Dataset in the groups generated for resampling and concatenate them together into a new Dataset. `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds` in this group. Apply uses heuristics...
Reduce the items in this group by applying `func` along the pre-defined resampling dimension. Parameters ---------- func : function Function which can be called in the form `func(x, axis=axis, **kwargs)` to return the result of collapsing an np.ndarra...
def reduce(self, func, dim=None, keep_attrs=None, **kwargs): """Reduce the items in this group by applying `func` along the pre-defined resampling dimension. Parameters ---------- func : function Function which can be called in the form `func(x, axis=axis...
Default indexes for a Dataset/DataArray. Parameters ---------- coords : Mapping[Any, xarray.Variable] Coordinate variables from which to draw default indexes. dims : iterable Iterable of dimension names. Returns ------- Mapping from indexing keys (levels/dimension names) to ...
def default_indexes( coords: Mapping[Any, Variable], dims: Iterable, ) -> 'OrderedDict[Any, pd.Index]': """Default indexes for a Dataset/DataArray. Parameters ---------- coords : Mapping[Any, xarray.Variable] Coordinate variables from which to draw default indexes. dims : iterable ...
Index a Variable and pandas.Index together.
def isel_variable_and_index( name: Hashable, variable: Variable, index: pd.Index, indexers: Mapping[Any, Union[slice, Variable]], ) -> Tuple[Variable, Optional[pd.Index]]: """Index a Variable and pandas.Index together.""" if not indexers: # nothing to index return variable.copy(d...
Build output coordinates for an operation. Parameters ---------- args : list List of raw operation arguments. Any valid types for xarray operations are OK, e.g., scalars, Variable, DataArray, Dataset. signature : _UfuncSignature Core dimensions signature for the operation. e...
def build_output_coords( args: list, signature: _UFuncSignature, exclude_dims: AbstractSet = frozenset(), ) -> 'List[OrderedDict[Any, Variable]]': """Build output coordinates for an operation. Parameters ---------- args : list List of raw operation arguments. Any valid types for xar...
Apply a variable level function over DataArray, Variable and/or ndarray objects.
def apply_dataarray_vfunc( func, *args, signature, join='inner', exclude_dims=frozenset(), keep_attrs=False ): """Apply a variable level function over DataArray, Variable and/or ndarray objects. """ from .dataarray import DataArray if len(args) > 1: args = deep_align...
Apply a variable level function over dicts of DataArray, DataArray, Variable and ndarray objects.
def apply_dict_of_variables_vfunc( func, *args, signature, join='inner', fill_value=None ): """Apply a variable level function over dicts of DataArray, DataArray, Variable and ndarray objects. """ args = [_as_variables_or_variable(arg) for arg in args] names = join_dict_keys(args, how=join) ...
Create a dataset as quickly as possible. Beware: the `variables` OrderedDict is modified INPLACE.
def _fast_dataset( variables: 'OrderedDict[Any, Variable]', coord_variables: Mapping[Any, Variable], ) -> 'Dataset': """Create a dataset as quickly as possible. Beware: the `variables` OrderedDict is modified INPLACE. """ from .dataset import Dataset variables.update(coord_variables) co...
Apply a variable level function over Dataset, dict of DataArray, DataArray, Variable and/or ndarray objects.
def apply_dataset_vfunc( func, *args, signature, join='inner', dataset_join='exact', fill_value=_NO_FILL_VALUE, exclude_dims=frozenset(), keep_attrs=False ): """Apply a variable level function over Dataset, dict of DataArray, DataArray, Variable and/or ndarray objects. """ ...
Iterate over selections of an xarray object in the provided order.
def _iter_over_selections(obj, dim, values): """Iterate over selections of an xarray object in the provided order.""" from .groupby import _dummy_copy dummy = None for value in values: try: obj_sel = obj.sel(**{dim: value}) except (KeyError, IndexError): if dummy...
Apply a dataset or datarray level function over GroupBy, Dataset, DataArray, Variable and/or ndarray objects.
def apply_groupby_func(func, *args): """Apply a dataset or datarray level function over GroupBy, Dataset, DataArray, Variable and/or ndarray objects. """ from .groupby import GroupBy, peek_at from .variable import Variable groupbys = [arg for arg in args if isinstance(arg, GroupBy)] assert ...
Apply a ndarray level function over Variable and/or ndarray objects.
def apply_variable_ufunc( func, *args, signature, exclude_dims=frozenset(), dask='forbidden', output_dtypes=None, output_sizes=None, keep_attrs=False ): """Apply a ndarray level function over Variable and/or ndarray objects. """ from .variable import Variable, as_compatible_d...
Apply a ndarray level function over ndarray objects.
def apply_array_ufunc(func, *args, dask='forbidden'): """Apply a ndarray level function over ndarray objects.""" if any(isinstance(arg, dask_array_type) for arg in args): if dask == 'forbidden': raise ValueError('apply_ufunc encountered a dask array on an ' 'argu...
Apply a vectorized function for unlabeled arrays on xarray objects. The function will be mapped over the data variable(s) of the input arguments using xarray's standard rules for labeled computation, including alignment, broadcasting, looping over GroupBy/Dataset variables, and merging of coordinates. ...
def apply_ufunc( func: Callable, *args: Any, input_core_dims: Optional[Sequence[Sequence]] = None, output_core_dims: Optional[Sequence[Sequence]] = ((),), exclude_dims: AbstractSet = frozenset(), vectorize: bool = False, join: str = 'exact', dataset_join: str = 'exact', dataset_fill_...
Generalized dot product for xarray objects. Like np.einsum, but provides a simpler interface based on array dimensions. Parameters ---------- arrays: DataArray (or Variable) objects Arrays to compute. dims: str or tuple of strings, optional Which dimensions to sum over. If n...
def dot(*arrays, dims=None, **kwargs): """Generalized dot product for xarray objects. Like np.einsum, but provides a simpler interface based on array dimensions. Parameters ---------- arrays: DataArray (or Variable) objects Arrays to compute. dims: str or tuple of strings, optional ...
Return elements from `x` or `y` depending on `cond`. Performs xarray-like broadcasting across input arguments. Parameters ---------- cond : scalar, array, Variable, DataArray or Dataset with boolean dtype When True, return values from `x`, otherwise returns values from `y`. x, y : scalar, ...
def where(cond, x, y): """Return elements from `x` or `y` depending on `cond`. Performs xarray-like broadcasting across input arguments. Parameters ---------- cond : scalar, array, Variable, DataArray or Dataset with boolean dtype When True, return values from `x`, otherwise returns values...
Create an equivalent signature string for a NumPy gufunc. Unlike __str__, handles dimensions that don't map to Python identifiers.
def to_gufunc_string(self): """Create an equivalent signature string for a NumPy gufunc. Unlike __str__, handles dimensions that don't map to Python identifiers. """ all_dims = self.all_core_dims dims_map = dict(zip(sorted(all_dims), range(len(all_dims)))) input_...
Return indices for an inverse permutation. Parameters ---------- indices : 1D np.ndarray with dtype=int Integer positions to assign elements to. Returns ------- inverse_permutation : 1D np.ndarray with dtype=int Integer indices to take from the original array to create the ...
def inverse_permutation(indices): """Return indices for an inverse permutation. Parameters ---------- indices : 1D np.ndarray with dtype=int Integer positions to assign elements to. Returns ------- inverse_permutation : 1D np.ndarray with dtype=int Integer indices to take f...
Given a non-empty list, does it consist of contiguous integers?
def _is_contiguous(positions): """Given a non-empty list, does it consist of contiguous integers?""" previous = positions[0] for current in positions[1:]: if current != previous + 1: return False previous = current return True
Indices of the advanced indexes subspaces for mixed indexing and vindex.
def _advanced_indexer_subspaces(key): """Indices of the advanced indexes subspaces for mixed indexing and vindex. """ if not isinstance(key, tuple): key = (key,) advanced_index_positions = [i for i, k in enumerate(key) if not isinstance(k, slice)] if (not adv...
rolling window with padding.
def rolling_window(a, axis, window, center, fill_value): """ rolling window with padding. """ pads = [(0, 0) for s in a.shape] if center: start = int(window / 2) # 10 -> 5, 9 -> 4 end = window - 1 - start pads[axis] = (start, end) else: pads[axis] = (window - 1, 0) ...
Make an ndarray with a rolling window along axis. Parameters ---------- a : array_like Array to add rolling window to axis: int axis position along which rolling window will be applied. window : int Size of rolling window Returns ------- Array that is a view of ...
def _rolling_window(a, window, axis=-1): """ Make an ndarray with a rolling window along axis. Parameters ---------- a : array_like Array to add rolling window to axis: int axis position along which rolling window will be applied. window : int Size of rolling window ...
Get a virtual variable (e.g., 'time.year' or a MultiIndex level) from a dict of xarray.Variable objects (if possible)
def _get_virtual_variable(variables, key, level_vars=None, dim_sizes=None): """Get a virtual variable (e.g., 'time.year' or a MultiIndex level) from a dict of xarray.Variable objects (if possible) """ if level_vars is None: level_vars = {} if dim_sizes is None: dim_sizes = {} if...
Calculate the dimensions corresponding to a set of variables. Returns dictionary mapping from dimension names to sizes. Raises ValueError if any of the dimension sizes conflict.
def calculate_dimensions(variables): """Calculate the dimensions corresponding to a set of variables. Returns dictionary mapping from dimension names to sizes. Raises ValueError if any of the dimension sizes conflict. """ dims = OrderedDict() last_used = {} scalar_vars = set(k for k, v in v...
Merge variables into multi-indexes. Not public API. Used in Dataset and DataArray set_index methods.
def merge_indexes( indexes, # type: Dict[Any, Union[Any, List[Any]]] variables, # type: Dict[Any, Variable] coord_names, # type: Set append=False, # type: bool ): # type: (...) -> Tuple[OrderedDict[Any, Variable], Set] """Merge variables into multi-indexes. Not public AP...
Extract (multi-)indexes (levels) as variables. Not public API. Used in Dataset and DataArray reset_index methods.
def split_indexes( dims_or_levels, # type: Union[Any, List[Any]] variables, # type: OrderedDict[Any, Variable] coord_names, # type: Set level_coords, # type: Dict[Any, Any] drop=False, # type: bool ): # type: (...) -> Tuple[OrderedDict[Any, Variable], Set] """Extract (multi-)indexes (le...
Cast the given object to a Dataset. Handles Datasets, DataArrays and dictionaries of variables. A new Dataset object is only created if the provided object is not already one.
def as_dataset(obj): """Cast the given object to a Dataset. Handles Datasets, DataArrays and dictionaries of variables. A new Dataset object is only created if the provided object is not already one. """ if hasattr(obj, 'to_dataset'): obj = obj.to_dataset() if not isinstance(obj, Datase...
Provide method for the key-autocompletions in IPython.
def _ipython_key_completions_(self): """Provide method for the key-autocompletions in IPython. """ return [key for key in self._dataset._ipython_key_completions_() if key not in self._dataset._coord_names]
Set the initial value of Dataset variables and dimensions
def _set_init_vars_and_dims(self, data_vars, coords, compat): """Set the initial value of Dataset variables and dimensions """ both_data_and_coords = [k for k in data_vars if k in coords] if both_data_and_coords: raise ValueError('variables %r are found in both data_vars and ...
Create a new dataset from the contents of a backends.*DataStore object
def load_store(cls, store, decoder=None): """Create a new dataset from the contents of a backends.*DataStore object """ variables, attributes = store.load() if decoder: variables, attributes = decoder(variables, attributes) obj = cls(variables, attrs=attribute...
Dictionary of global attributes on this dataset
def attrs(self) -> Mapping: """Dictionary of global attributes on this dataset """ if self._attrs is None: self._attrs = OrderedDict() return self._attrs
Manually trigger loading of this dataset's data from disk or a remote source into memory and return this dataset. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data or load data automatically. However, ...
def load(self: T, **kwargs) -> T: """Manually trigger loading of this dataset's data from disk or a remote source into memory and return this dataset. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data ...
Manually trigger loading of this dataset's data from disk or a remote source into memory and return a new dataset. The original is left unaltered. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data or ...
def compute(self: T, **kwargs) -> T: """Manually trigger loading of this dataset's data from disk or a remote source into memory and return a new dataset. The original is left unaltered. Normally, it should not be necessary to call this method in user code, because all xarray fu...
Persist all Dask arrays in memory
def _persist_inplace(self, **kwargs): """ Persist all Dask arrays in memory """ # access .data to coerce everything to numpy or dask arrays lazy_data = {k: v._data for k, v in self.variables.items() if isinstance(v._data, dask_array_type)} if lazy_data: i...
Trigger computation, keeping data as dask arrays This operation can be used to trigger computation on underlying dask arrays, similar to ``.compute()``. However this operation keeps the data as dask arrays. This is particularly useful when using the dask.distributed scheduler and you ...
def persist(self: T, **kwargs) -> T: """ Trigger computation, keeping data as dask arrays This operation can be used to trigger computation on underlying dask arrays, similar to ``.compute()``. However this operation keeps the data as dask arrays. This is particularly useful when usin...
Shortcut around __init__ for internal use when we want to skip costly validation
def _construct_direct(cls, variables, coord_names, dims, attrs=None, indexes=None, encoding=None, file_obj=None): """Shortcut around __init__ for internal use when we want to skip costly validation """ obj = object.__new__(cls) obj._variables = variables...
Fastpath constructor for internal use. Returns an object with optionally with replaced attributes. Explicitly passed arguments are *not* copied when placed on the new dataset. It is up to the caller to ensure that they have the right type and are not used elsewhere.
def _replace( # type: ignore self: T, variables: 'OrderedDict[Any, Variable]' = None, coord_names: set = None, dims: Dict[Any, int] = None, attrs: 'Optional[OrderedDict]' = __default, indexes: 'Optional[OrderedDict[Any, pd.Index]]' = __default, encoding: Optional...
Replace variables with recalculated dimensions.
def _replace_with_new_dims( # type: ignore self: T, variables: 'OrderedDict[Any, Variable]' = None, coord_names: set = None, attrs: 'Optional[OrderedDict]' = __default, indexes: 'Optional[OrderedDict[Any, pd.Index]]' = __default, inplace: bool = False, ) -> T: ...
Returns a copy of this dataset. If `deep=True`, a deep copy is made of each of the component variables. Otherwise, a shallow copy of each of the component variable is made, so that the underlying memory region of the new dataset is the same as in the original dataset. Use `data...
def copy(self: T, deep: bool = False, data: Mapping = None) -> T: """Returns a copy of this dataset. If `deep=True`, a deep copy is made of each of the component variables. Otherwise, a shallow copy of each of the component variable is made, so that the underlying memory region of the n...
Return a mapping of all MultiIndex levels and their corresponding coordinate name.
def _level_coords(self): """Return a mapping of all MultiIndex levels and their corresponding coordinate name. """ level_coords = OrderedDict() for name, index in self.indexes.items(): if isinstance(index, pd.MultiIndex): level_names = index.names ...
Create a new Dataset with the listed variables from this dataset and the all relevant coordinates. Skips all validation.
def _copy_listed(self: T, names) -> T: """Create a new Dataset with the listed variables from this dataset and the all relevant coordinates. Skips all validation. """ variables = OrderedDict() # type: OrderedDict[Any, Variable] coord_names = set() indexes = OrderedDict()...
Construct a DataArray by indexing this dataset
def _construct_dataarray(self, name) -> 'DataArray': """Construct a DataArray by indexing this dataset """ from .dataarray import DataArray try: variable = self._variables[name] except KeyError: _, name, variable = _get_virtual_variable( s...
List of places to look-up items for key-completion
def _item_sources(self): """List of places to look-up items for key-completion""" return [self.data_vars, self.coords, {d: self[d] for d in self.dims}, LevelCoordinatesSource(self)]
Helper function for equals and identical
def _all_compat(self, other, compat_str): """Helper function for equals and identical""" # some stores (e.g., scipy) do not seem to preserve order, so don't # require matching order for equality def compat(x, y): return getattr(x, compat_str)(y) return (self._coord_...
Mapping of pandas.Index objects used for label based indexing
def indexes(self) -> 'Mapping[Any, pd.Index]': """Mapping of pandas.Index objects used for label based indexing """ if self._indexes is None: self._indexes = default_indexes(self._variables, self._dims) return Indexes(self._indexes)
Given names of one or more variables, set them as coordinates Parameters ---------- names : str or list of str Name(s) of variables in this dataset to convert into coordinates. inplace : bool, optional If True, modify this dataset inplace. Otherwise, create a new...
def set_coords(self, names, inplace=None): """Given names of one or more variables, set them as coordinates Parameters ---------- names : str or list of str Name(s) of variables in this dataset to convert into coordinates. inplace : bool, optional If True...
Given names of coordinates, reset them to become variables Parameters ---------- names : str or list of str, optional Name(s) of non-index coordinates in this dataset to reset into variables. By default, all non-index coordinates are reset. drop : bool, optional ...
def reset_coords(self, names=None, drop=False, inplace=None): """Given names of coordinates, reset them to become variables Parameters ---------- names : str or list of str, optional Name(s) of non-index coordinates in this dataset to reset into variables. By def...
Store dataset contents to a backends.*DataStore object.
def dump_to_store(self, store, **kwargs): """Store dataset contents to a backends.*DataStore object.""" from ..backends.api import dump_to_store # TODO: rename and/or cleanup this method to make it more consistent # with to_netcdf() return dump_to_store(self, store, **kwargs)
Write dataset contents to a netCDF file. Parameters ---------- path : str, Path or file-like object, optional Path to which to save this dataset. File-like objects are only supported by the scipy engine. If no path is provided, this function returns the resul...
def to_netcdf(self, path=None, mode='w', format=None, group=None, engine=None, encoding=None, unlimited_dims=None, compute=True): """Write dataset contents to a netCDF file. Parameters ---------- path : str, Path or file-like object, optional ...
Write dataset contents to a zarr group. .. note:: Experimental The Zarr backend is new and experimental. Please report any unexpected behavior via github issues. Parameters ---------- store : MutableMapping or str, optional Store or path ...
def to_zarr(self, store=None, mode='w-', synchronizer=None, group=None, encoding=None, compute=True, consolidated=False): """Write dataset contents to a zarr group. .. note:: Experimental The Zarr backend is new and experimental. Please report any une...
Concise summary of a Dataset variables and attributes. Parameters ---------- buf : writable buffer, defaults to sys.stdout See Also -------- pandas.DataFrame.assign netCDF's ncdump
def info(self, buf=None): """ Concise summary of a Dataset variables and attributes. Parameters ---------- buf : writable buffer, defaults to sys.stdout See Also -------- pandas.DataFrame.assign netCDF's ncdump """ if buf is None...
Block dimensions for this dataset's data or None if it's not a dask array.
def chunks(self): """Block dimensions for this dataset's data or None if it's not a dask array. """ chunks = {} for v in self.variables.values(): if v.chunks is not None: for dim, c in zip(v.dims, v.chunks): if dim in chunks and c !...
Coerce all arrays in this dataset into dask arrays with the given chunks. Non-dask arrays in this dataset will be converted to dask arrays. Dask arrays will be rechunked to the given chunk sizes. If neither chunks is not provided for one or more dimensions, chunk sizes along th...
def chunk(self, chunks=None, name_prefix='xarray-', token=None, lock=False): """Coerce all arrays in this dataset into dask arrays with the given chunks. Non-dask arrays in this dataset will be converted to dask arrays. Dask arrays will be rechunked to the given chunk size...
Here we make sure + indexer has a valid keys + indexer is in a valid data type + string indexers are cast to the appropriate date type if the associated index is a DatetimeIndex or CFTimeIndex
def _validate_indexers( self, indexers: Mapping, ) -> List[Tuple[Any, Union[slice, Variable]]]: """ Here we make sure + indexer has a valid keys + indexer is in a valid data type + string indexers are cast to the appropriate date type if the associated index is a Da...
Extract coordinates from indexers. Returns an OrderedDict mapping from coordinate name to the coordinate variable. Only coordinate with a name different from any of self.variables will be attached.
def _get_indexers_coords_and_indexes(self, indexers): """ Extract coordinates from indexers. Returns an OrderedDict mapping from coordinate name to the coordinate variable. Only coordinate with a name different from any of self.variables will be attached. """ fr...
Returns a new dataset with each array indexed along the specified dimension(s). This method selects values from each array using its `__getitem__` method, except this method does not require knowing the order of each array's dimensions. Parameters ---------- ind...
def isel(self, indexers=None, drop=False, **indexers_kwargs): """Returns a new dataset with each array indexed along the specified dimension(s). This method selects values from each array using its `__getitem__` method, except this method does not require knowing the order of ea...
Returns a new dataset with each array indexed by tick labels along the specified dimension(s). In contrast to `Dataset.isel`, indexers for this method should use labels instead of integers. Under the hood, this method is powered by using pandas's powerful Index objects. This ma...
def sel(self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs): """Returns a new dataset with each array indexed by tick labels along the specified dimension(s). In contrast to `Dataset.isel`, indexers for this method should use labels instead of in...
Returns a new dataset with each array indexed pointwise along the specified dimension(s). This method selects pointwise values from each array and is akin to the NumPy indexing behavior of `arr[[0, 1], [0, 1]]`, except this method does not require knowing the order of each array's dimen...
def isel_points(self, dim='points', **indexers): # type: (...) -> Dataset """Returns a new dataset with each array indexed pointwise along the specified dimension(s). This method selects pointwise values from each array and is akin to the NumPy indexing behavior of `arr[[0, 1], ...
Returns a new dataset with each array indexed pointwise by tick labels along the specified dimension(s). In contrast to `Dataset.isel_points`, indexers for this method should use labels instead of integers. In contrast to `Dataset.sel`, this method selects points along the diag...
def sel_points(self, dim='points', method=None, tolerance=None, **indexers): """Returns a new dataset with each array indexed pointwise by tick labels along the specified dimension(s). In contrast to `Dataset.isel_points`, indexers for this method should use labels in...
Conform this object onto the indexes of another object, filling in missing values with NaN. Parameters ---------- other : Dataset or DataArray Object with an 'indexes' attribute giving a mapping from dimension names to pandas.Index objects, which provides coordin...
def reindex_like(self, other, method=None, tolerance=None, copy=True): """Conform this object onto the indexes of another object, filling in missing values with NaN. Parameters ---------- other : Dataset or DataArray Object with an 'indexes' attribute giving a mappin...
Conform this object onto a new set of indexes, filling in missing values with NaN. Parameters ---------- indexers : dict. optional Dictionary with keys given by dimension names and values given by arrays of coordinates tick labels. Any mis-matched coordinate ...
def reindex(self, indexers=None, method=None, tolerance=None, copy=True, **indexers_kwargs): """Conform this object onto a new set of indexes, filling in missing values with NaN. Parameters ---------- indexers : dict. optional Dictionary with keys giv...
Multidimensional interpolation of Dataset. Parameters ---------- coords : dict, optional Mapping from dimension names to the new coordinates. New coordinate can be a scalar, array-like or DataArray. If DataArrays are passed as new coordates, their dimensions ...
def interp(self, coords=None, method='linear', assume_sorted=False, kwargs={}, **coords_kwargs): """ Multidimensional interpolation of Dataset. Parameters ---------- coords : dict, optional Mapping from dimension names to the new coordinates. New c...
Interpolate this object onto the coordinates of another object, filling the out of range values with NaN. Parameters ---------- other : Dataset or DataArray Object with an 'indexes' attribute giving a mapping from dimension names to an 1d array-like, which provid...
def interp_like(self, other, method='linear', assume_sorted=False, kwargs={}): """Interpolate this object onto the coordinates of another object, filling the out of range values with NaN. Parameters ---------- other : Dataset or DataArray Object w...
Returns a new object with renamed variables and dimensions. Parameters ---------- name_dict : dict-like, optional Dictionary whose keys are current variable or dimension names and whose values are the desired names. inplace : bool, optional If True, r...
def rename(self, name_dict=None, inplace=None, **names): """Returns a new object with renamed variables and dimensions. Parameters ---------- name_dict : dict-like, optional Dictionary whose keys are current variable or dimension names and whose values are the de...
Returns a new object with swapped dimensions. Parameters ---------- dims_dict : dict-like Dictionary whose keys are current dimension names and whose values are new names. Each value must already be a variable in the dataset. inplace : bool, optional ...
def swap_dims(self, dims_dict, inplace=None): """Returns a new object with swapped dimensions. Parameters ---------- dims_dict : dict-like Dictionary whose keys are current dimension names and whose values are new names. Each value must already be a variable in t...
Return a new object with an additional axis (or axes) inserted at the corresponding position in the array shape. If dim is already a scalar coordinate, it will be promoted to a 1D coordinate consisting of a single value. Parameters ---------- dim : str, sequence of str,...
def expand_dims(self, dim=None, axis=None, **dim_kwargs): """Return a new object with an additional axis (or axes) inserted at the corresponding position in the array shape. If dim is already a scalar coordinate, it will be promoted to a 1D coordinate consisting of a single value. ...
Set Dataset (multi-)indexes using one or more existing coordinates or variables. Parameters ---------- indexes : {dim: index, ...} Mapping from names matching dimensions and values given by (lists of) the names of existing coordinates or variables to set ...
def set_index(self, indexes=None, append=False, inplace=None, **indexes_kwargs): """Set Dataset (multi-)indexes using one or more existing coordinates or variables. Parameters ---------- indexes : {dim: index, ...} Mapping from names matching dimens...
Reset the specified index(es) or multi-index level(s). Parameters ---------- dims_or_levels : str or list Name(s) of the dimension(s) and/or multi-index level(s) that will be reset. drop : bool, optional If True, remove the specified indexes and/or mu...
def reset_index(self, dims_or_levels, drop=False, inplace=None): """Reset the specified index(es) or multi-index level(s). Parameters ---------- dims_or_levels : str or list Name(s) of the dimension(s) and/or multi-index level(s) that will be reset. drop ...
Rearrange index levels using input order. Parameters ---------- dim_order : optional Mapping from names matching dimensions and values given by lists representing new level orders. Every given dimension must have a multi-index. inplace : bool, optiona...
def reorder_levels(self, dim_order=None, inplace=None, **dim_order_kwargs): """Rearrange index levels using input order. Parameters ---------- dim_order : optional Mapping from names matching dimensions and values given by lists representin...
Unstack existing dimensions corresponding to MultiIndexes into multiple new dimensions. New dimensions will be added at the end. Parameters ---------- dim : str or sequence of str, optional Dimension(s) over which to unstack. By default unstacks all Mult...
def unstack(self, dim=None): """ Unstack existing dimensions corresponding to MultiIndexes into multiple new dimensions. New dimensions will be added at the end. Parameters ---------- dim : str or sequence of str, optional Dimension(s) over which to ...
Update this dataset's variables with those from another dataset. Parameters ---------- other : Dataset or castable to Dataset Dataset or variables with which to update this dataset. inplace : bool, optional If True, merge the other dataset into this dataset in-pl...
def update(self, other, inplace=None): """Update this dataset's variables with those from another dataset. Parameters ---------- other : Dataset or castable to Dataset Dataset or variables with which to update this dataset. inplace : bool, optional If Tru...
Merge the arrays of two datasets into a single dataset. This method generally not allow for overriding data, with the exception of attributes, which are ignored on the second dataset. Variables with the same name are checked for conflicts via the equals or identical methods. Pa...
def merge(self, other, inplace=None, overwrite_vars=frozenset(), compat='no_conflicts', join='outer'): """Merge the arrays of two datasets into a single dataset. This method generally not allow for overriding data, with the exception of attributes, which are ignored on the second ...
Drop variables or index labels from this dataset. Parameters ---------- labels : scalar or list of scalars Name(s) of variables or index labels to drop. dim : None or str, optional Dimension along which to drop index labels. By default (if ``dim is No...
def drop(self, labels, dim=None): """Drop variables or index labels from this dataset. Parameters ---------- labels : scalar or list of scalars Name(s) of variables or index labels to drop. dim : None or str, optional Dimension along which to drop index l...
Drop dimensions and associated variables from this dataset. Parameters ---------- drop_dims : str or list Dimension or dimensions to drop. Returns ------- obj : Dataset The dataset without the given dimensions (or any variables contai...
def drop_dims(self, drop_dims): """Drop dimensions and associated variables from this dataset. Parameters ---------- drop_dims : str or list Dimension or dimensions to drop. Returns ------- obj : Dataset The dataset without the given dime...
Return a new Dataset object with all array dimensions transposed. Although the order of dimensions on each array will change, the dataset dimensions themselves will remain in fixed (sorted) order. Parameters ---------- *dims : str, optional By default, reverse the d...
def transpose(self, *dims): """Return a new Dataset object with all array dimensions transposed. Although the order of dimensions on each array will change, the dataset dimensions themselves will remain in fixed (sorted) order. Parameters ---------- *dims : str, optiona...
Returns a new dataset with dropped labels for missing values along the provided dimension. Parameters ---------- dim : str Dimension along which to drop missing values. Dropping along multiple dimensions simultaneously is not yet supported. how : {'any', ...
def dropna(self, dim, how='any', thresh=None, subset=None): """Returns a new dataset with dropped labels for missing values along the provided dimension. Parameters ---------- dim : str Dimension along which to drop missing values. Dropping along multiple...
Fill missing values in this object. This operation follows the normal broadcasting and alignment rules that xarray uses for binary arithmetic, except the result is aligned to this object (``join='left'``) instead of aligned to the intersection of index coordinates (``join='inner'``). ...
def fillna(self, value): """Fill missing values in this object. This operation follows the normal broadcasting and alignment rules that xarray uses for binary arithmetic, except the result is aligned to this object (``join='left'``) instead of aligned to the intersection of inde...
Interpolate values according to different methods. Parameters ---------- dim : str Specifies the dimension along which to interpolate. method : {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'polynomial', 'barycentric', 'krog', 'pchip', ...
def interpolate_na(self, dim=None, method='linear', limit=None, use_coordinate=True, **kwargs): """Interpolate values according to different methods. Parameters ---------- dim : str Specifies the dimension along which to interpol...
Fill NaN values by propogating values forward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None The maximum number of consecutive NaN values ...
def ffill(self, dim, limit=None): '''Fill NaN values by propogating values forward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None ...
Fill NaN values by propogating values backward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None The maximum number of consecutive NaN values...
def bfill(self, dim, limit=None): '''Fill NaN values by propogating values backward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None ...
Combine two Datasets, default to data_vars of self. The new coordinates follow the normal broadcasting and alignment rules of ``join='outer'``. Vacant cells in the expanded coordinates are filled with np.nan. Parameters ---------- other : DataArray Used to ...
def combine_first(self, other): """Combine two Datasets, default to data_vars of self. The new coordinates follow the normal broadcasting and alignment rules of ``join='outer'``. Vacant cells in the expanded coordinates are filled with np.nan. Parameters ---------- ...
Reduce this dataset by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `f(x, axis=axis, **kwargs)` to return the result of reducing an np.ndarray over an integer valued axis. dim ...
def reduce(self, func, dim=None, keep_attrs=None, numeric_only=False, allow_lazy=False, **kwargs): """Reduce this dataset by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `f(...
Assign new data variables to a Dataset, returning a new object with all the original variables in addition to the new ones. Parameters ---------- variables : mapping, value pairs Mapping from variables names to the new values. If the new values are callable, they...
def assign(self, variables=None, **variables_kwargs): """Assign new data variables to a Dataset, returning a new object with all the original variables in addition to the new ones. Parameters ---------- variables : mapping, value pairs Mapping from variables names to...