INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a copy of this object.
def copy(self, deep=True, data=None): """Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same struct...
Convert this variable to a pandas. Index
def to_index(self): """Convert this variable to a pandas.Index""" # n.b. creating a new pandas.Index from an old pandas.Index is # basically free as pandas.Index objects are immutable assert self.ndim == 1 index = self._data.array if isinstance(index, pd.MultiIndex): ...
Return MultiIndex level names or None if this IndexVariable has no MultiIndex.
def level_names(self): """Return MultiIndex level names or None if this IndexVariable has no MultiIndex. """ index = self.to_index() if isinstance(index, pd.MultiIndex): return index.names else: return None
Return a new IndexVariable from a given MultiIndex level.
def get_level_variable(self, level): """Return a new IndexVariable from a given MultiIndex level.""" if self.level_names is None: raise ValueError("IndexVariable %r has no MultiIndex" % self.name) index = self.to_index() return type(self)(self.dims, index.get_level_values(lev...
Generalization of pandas. tseries. index. DatetimeIndex. _parsed_string_to_bounds for use with non - standard calendars and cftime. datetime objects.
def _parsed_string_to_bounds(date_type, resolution, parsed): """Generalization of pandas.tseries.index.DatetimeIndex._parsed_string_to_bounds for use with non-standard calendars and cftime.datetime objects. """ if resolution == 'year': return (date_type(parsed.year, 1, 1), ...
Adapted from pandas. tslib. get_date_field
def get_date_field(datetimes, field): """Adapted from pandas.tslib.get_date_field""" return np.array([getattr(date, field) for date in datetimes])
Adapted from pandas. tseries. index. _field_accessor
def _field_accessor(name, docstring=None, min_cftime_version='0.0'): """Adapted from pandas.tseries.index._field_accessor""" def f(self, min_cftime_version=min_cftime_version): import cftime version = cftime.__version__ if LooseVersion(version) >= LooseVersion(min_cftime_version): ...
Create a numpy array from an array of strings.
def _parse_array_of_cftime_strings(strings, date_type): """Create a numpy array from an array of strings. For use in generating dates from strings for use with interp. Assumes the array is either 0-dimensional or 1-dimensional. Parameters ---------- strings : array of strings Strings ...
Adapted from pandas. tseries. index. DatetimeIndex. _partial_date_slice
def _partial_date_slice(self, resolution, parsed): """Adapted from pandas.tseries.index.DatetimeIndex._partial_date_slice Note that when using a CFTimeIndex, if a partial-date selection returns a single element, it will never be converted to a scalar coordinate; this is in sligh...
Adapted from pandas. tseries. index. DatetimeIndex. _get_string_slice
def _get_string_slice(self, key): """Adapted from pandas.tseries.index.DatetimeIndex._get_string_slice""" parsed, resolution = _parse_iso8601_with_reso(self.date_type, key) try: loc = self._partial_date_slice(resolution, parsed) except KeyError: raise KeyError(key...
Adapted from pandas. tseries. index. DatetimeIndex. get_loc
def get_loc(self, key, method=None, tolerance=None): """Adapted from pandas.tseries.index.DatetimeIndex.get_loc""" if isinstance(key, str): return self._get_string_slice(key) else: return pd.Index.get_loc(self, key, method=method, toler...
Adapted from pandas. tseries. index. DatetimeIndex. _maybe_cast_slice_bound
def _maybe_cast_slice_bound(self, label, side, kind): """Adapted from pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound""" if isinstance(label, str): parsed, resolution = _parse_iso8601_with_reso(self.date_type, label...
Adapted from pandas. tseries. index. DatetimeIndex. get_value
def get_value(self, series, key): """Adapted from pandas.tseries.index.DatetimeIndex.get_value""" if np.asarray(key).dtype == np.dtype(bool): return series.iloc[key] elif isinstance(key, slice): return series.iloc[self.slice_indexer( key.start, key.stop, k...
Shift the CFTimeIndex a multiple of the given frequency.
def shift(self, n, freq): """Shift the CFTimeIndex a multiple of the given frequency. See the documentation for :py:func:`~xarray.cftime_range` for a complete listing of valid frequency strings. Parameters ---------- n : int Periods to shift by freq ...
If possible convert this index to a pandas. DatetimeIndex.
def to_datetimeindex(self, unsafe=False): """If possible, convert this index to a pandas.DatetimeIndex. Parameters ---------- unsafe : bool Flag to turn off warning when converting from a CFTimeIndex with a non-standard calendar to a DatetimeIndex (default ``Fals...
Create a function that dispatches to dask for dask array inputs.
def _dask_or_eager_func(name, eager_module=np, dask_module=dask_array, list_of_args=False, array_args=slice(1), requires_dask=None): """Create a function that dispatches to dask for dask array inputs.""" if dask_module is not None: def f(*args, **kwargs): ...
Cast a arrays to a shared dtype using xarray s type promotion rules.
def as_shared_dtype(scalars_or_arrays): """Cast a arrays to a shared dtype using xarray's type promotion rules.""" arrays = [asarray(x) for x in scalars_or_arrays] # Pass arrays directly instead of dtypes to result_type so scalars # get handled properly. # Note that result_type() safely gets the dty...
Like np. allclose but also allows values to be NaN in both arrays
def allclose_or_equiv(arr1, arr2, rtol=1e-5, atol=1e-8): """Like np.allclose, but also allows values to be NaN in both arrays """ arr1, arr2 = as_like_arrays(arr1, arr2) if arr1.shape != arr2.shape: return False return bool( isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=True).a...
Like np. array_equal but also allows values to be NaN in both arrays
def array_equiv(arr1, arr2): """Like np.array_equal, but also allows values to be NaN in both arrays """ arr1, arr2 = as_like_arrays(arr1, arr2) if arr1.shape != arr2.shape: return False with warnings.catch_warnings(): warnings.filterwarnings('ignore', "In the future, 'NAT == x'") ...
Count the number of non - NA in this array along the given axis or axes
def count(data, axis=None): """Count the number of non-NA in this array along the given axis or axes """ return np.sum(np.logical_not(isnull(data)), axis=axis)
Convert an array containing datetime - like data to an array of floats.
def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float): """Convert an array containing datetime-like data to an array of floats. Parameters ---------- da : np.array Input data offset: Scalar with the same type of array or None If None, subtract minimum values t...
inhouse mean that can handle np. datetime64 or cftime. datetime dtypes
def mean(array, axis=None, skipna=None, **kwargs): """inhouse mean that can handle np.datetime64 or cftime.datetime dtypes""" from .common import _contains_cftime_datetimes array = asarray(array) if array.dtype.kind in 'Mm': offset = min(array) # xarray always uses np.datetime64[ns]...
Return the first non - NA elements in this array along the given axis
def first(values, axis, skipna=None): """Return the first non-NA elements in this array along the given axis """ if (skipna or skipna is None) and values.dtype.kind not in 'iSU': # only bother for dtypes that can hold NaN _fail_on_dask_array_input_skipna(values) return nanfirst(value...
Return the last non - NA elements in this array along the given axis
def last(values, axis, skipna=None): """Return the last non-NA elements in this array along the given axis """ if (skipna or skipna is None) and values.dtype.kind not in 'iSU': # only bother for dtypes that can hold NaN _fail_on_dask_array_input_skipna(values) return nanlast(values, ...
Make an ndarray with a rolling window of axis - th dimension. The rolling dimension will be placed at the last dimension.
def rolling_window(array, axis, window, center, fill_value): """ Make an ndarray with a rolling window of axis-th dimension. The rolling dimension will be placed at the last dimension. """ if isinstance(array, dask_array_type): return dask_array_ops.rolling_window( array, axis, w...
Concatenate xarray objects along a new or existing dimension.
def concat(objs, dim=None, data_vars='all', coords='different', compat='equals', positions=None, indexers=None, mode=None, concat_over=None): """Concatenate xarray objects along a new or existing dimension. Parameters ---------- objs : sequence of Dataset and DataArray objects ...
Infer the dimension name and 1d coordinate variable ( if appropriate ) for concatenating along the new dimension.
def _calc_concat_dim_coord(dim): """ Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension. """ from .dataarray import DataArray if isinstance(dim, str): coord = None elif not isinstance(dim, (DataArray, Variable)): di...
Determine which dataset variables need to be concatenated in the result and which can simply be taken from the first dataset.
def _calc_concat_over(datasets, dim, data_vars, coords): """ Determine which dataset variables need to be concatenated in the result, and which can simply be taken from the first dataset. """ # Return values concat_over = set() equals = {} if dim in datasets[0]: concat_over.add(...
Concatenate a sequence of datasets along a new or existing dimension
def _dataset_concat(datasets, dim, data_vars, coords, compat, positions): """ Concatenate a sequence of datasets along a new or existing dimension """ from .dataset import Dataset if compat not in ['equals', 'identical']: raise ValueError("compat=%r invalid: must be 'equals' " ...
Given a list of lists ( of lists... ) of objects returns a iterator which returns a tuple containing the index of each object in the nested list structure as the key and the object. This can then be called by the dict constructor to create a dictionary of the objects organised by their position in the original nested l...
def _infer_tile_ids_from_nested_list(entry, current_pos): """ Given a list of lists (of lists...) of objects, returns a iterator which returns a tuple containing the index of each object in the nested list structure as the key, and the object. This can then be called by the dict constructor to creat...
Concatenates and merges an N - dimensional structure of datasets.
def _combine_nd(combined_ids, concat_dims, data_vars='all', coords='different', compat='no_conflicts'): """ Concatenates and merges an N-dimensional structure of datasets. No checks are performed on the consistency of the datasets, concat_dims or tile_IDs, because it is assumed that thi...
Calls logic to decide concatenation order before concatenating.
def _auto_combine(datasets, concat_dims, compat, data_vars, coords, infer_order_from_coords, ids): """ Calls logic to decide concatenation order before concatenating. """ # Arrange datasets for concatenation if infer_order_from_coords: raise NotImplementedError # T...
Attempt to auto - magically combine the given datasets into one. This method attempts to combine a list of datasets into a single entity by inspecting metadata and using a combination of concat and merge. It does not concatenate along more than one dimension or sort data under any circumstances. It does align coordinat...
def auto_combine(datasets, concat_dim=_CONCAT_DIM_DEFAULT, compat='no_conflicts', data_vars='all', coords='different'): """Attempt to auto-magically combine the given datasets into one. This method attempts to combine a list of datasets into a single entity by inspecting metadata and using ...
Return the cftime date type for a given calendar name.
def get_date_type(calendar): """Return the cftime date type for a given calendar name.""" try: import cftime except ImportError: raise ImportError( 'cftime is required for dates with non-standard calendars') else: calendars = { 'noleap': cftime.DatetimeNoL...
Find the day in other s month that satisfies a BaseCFTimeOffset s onOffset policy as described by the day_option argument.
def _get_day_of_month(other, day_option): """Find the day in `other`'s month that satisfies a BaseCFTimeOffset's onOffset policy, as described by the `day_option` argument. Parameters ---------- other : cftime.datetime day_option : 'start', 'end' 'start': returns 1 'end': return...
The number of days in the month of the given date
def _days_in_month(date): """The number of days in the month of the given date""" if date.month == 12: reference = type(date)(date.year + 1, 1, 1) else: reference = type(date)(date.year, date.month + 1, 1) return (reference - timedelta(days=1)).day
Adjust the number of times a monthly offset is applied based on the day of a given date and the reference day provided.
def _adjust_n_months(other_day, n, reference_day): """Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided. """ if n > 0 and other_day < reference_day: n = n - 1 elif n <= 0 and other_day > reference_day: n = n + 1 ...
Adjust the number of times an annual offset is applied based on another date and the reference day provided
def _adjust_n_years(other, n, month, reference_day): """Adjust the number of times an annual offset is applied based on another date, and the reference day provided""" if n > 0: if other.month < month or (other.month == month and other.day < reference_day): ...
Shift the date to a month start or end a given number of months away.
def _shift_month(date, months, day_option='start'): """Shift the date to a month start or end a given number of months away. """ delta_year = (date.month + months) // 12 month = (date.month + months) % 12 if month == 0: month = 12 delta_year = delta_year - 1 year = date.year + d...
Possibly increment or decrement the number of periods to shift based on rollforward/ rollbackward conventions.
def roll_qtrday(other, n, month, day_option, modby=3): """Possibly increment or decrement the number of periods to shift based on rollforward/rollbackward conventions. Parameters ---------- other : cftime.datetime n : number of periods to increment, before adjusting for rolling month : int ...
Convert a frequency string to the appropriate subclass of BaseCFTimeOffset.
def to_offset(freq): """Convert a frequency string to the appropriate subclass of BaseCFTimeOffset.""" if isinstance(freq, BaseCFTimeOffset): return freq else: try: freq_data = re.match(_PATTERN, freq).groupdict() except AttributeError: raise ValueError('I...
Generate an equally - spaced sequence of cftime. datetime objects between and including two dates ( whose length equals the number of periods ).
def _generate_linear_range(start, end, periods): """Generate an equally-spaced sequence of cftime.datetime objects between and including two dates (whose length equals the number of periods).""" import cftime total_seconds = (end - start).total_seconds() values = np.linspace(0., total_seconds, peri...
Generate a regular range of cftime. datetime objects with a given time offset.
def _generate_range(start, end, periods, offset): """Generate a regular range of cftime.datetime objects with a given time offset. Adapted from pandas.tseries.offsets.generate_range. Parameters ---------- start : cftime.datetime, or None Start of range end : cftime.datetime, or Non...
Return a fixed frequency CFTimeIndex.
def cftime_range(start=None, end=None, periods=None, freq='D', normalize=False, name=None, closed=None, calendar='standard'): """Return a fixed frequency CFTimeIndex. Parameters ---------- start : str or cftime.datetime, optional Left bound for generating dates...
Check if the given date is in the set of possible dates created using a length - one version of this offset class.
def onOffset(self, date): """Check if the given date is in the set of possible dates created using a length-one version of this offset class.""" mod_month = (date.month - self.month) % 3 return mod_month == 0 and date.day == self._get_offset_day(date)
Roll date forward to nearest start of quarter
def rollforward(self, date): """Roll date forward to nearest start of quarter""" if self.onOffset(date): return date else: return date + QuarterBegin(month=self.month)
Roll date backward to nearest start of quarter
def rollback(self, date): """Roll date backward to nearest start of quarter""" if self.onOffset(date): return date else: return date - QuarterBegin(month=self.month)
Roll date forward to nearest end of quarter
def rollforward(self, date): """Roll date forward to nearest end of quarter""" if self.onOffset(date): return date else: return date + QuarterEnd(month=self.month)
Roll date backward to nearest end of quarter
def rollback(self, date): """Roll date backward to nearest end of quarter""" if self.onOffset(date): return date else: return date - QuarterEnd(month=self.month)
Roll date forward to nearest start of year
def rollforward(self, date): """Roll date forward to nearest start of year""" if self.onOffset(date): return date else: return date + YearBegin(month=self.month)
Roll date backward to nearest start of year
def rollback(self, date): """Roll date backward to nearest start of year""" if self.onOffset(date): return date else: return date - YearBegin(month=self.month)
Check if the given date is in the set of possible dates created using a length - one version of this offset class.
def onOffset(self, date): """Check if the given date is in the set of possible dates created using a length-one version of this offset class.""" return date.day == _days_in_month(date) and date.month == self.month
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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