INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convert this array into a numpy. ma. MaskedArray
def to_masked_array(self, copy=True): """Convert this array into a numpy.ma.MaskedArray Parameters ---------- copy : bool If True (default) make a copy of the array in the result. If False, a MaskedArray view of DataArray.values is returned. Returns ...
Write DataArray contents to a netCDF file.
def to_netcdf(self, *args, **kwargs): """Write DataArray contents to a netCDF file. Parameters ---------- path : str or Path, optional Path to which to save this dataset. If no path is provided, this function returns the resulting netCDF file as a bytes object; i...
Convert this xarray. DataArray into a dictionary following xarray naming conventions.
def to_dict(self, data=True): """ Convert this xarray.DataArray into a dictionary following xarray naming conventions. Converts all variables and attributes to native Python objects. Useful for coverting to json. To avoid datetime incompatibility use decode_times=False k...
Convert a dictionary into an xarray. DataArray
def from_dict(cls, d): """ Convert a dictionary into an xarray.DataArray Input dict can take several forms:: d = {'dims': ('t'), 'data': x} d = {'coords': {'t': {'dims': 't', 'data': t, 'attrs': {'units':'s'}}}, 'attrs...
Convert a pandas. Series into an xarray. DataArray.
def from_series(cls, series): """Convert a pandas.Series into an xarray.DataArray. If the series's index is a MultiIndex, it will be expanded into a tensor product of one-dimensional coordinates (filling in missing values with NaN). Thus this operation should be the inverse of the ...
Helper function for equals and identical
def _all_compat(self, other, compat_str): """Helper function for equals and identical""" def compat(x, y): return getattr(x.variable, compat_str)(y.variable) return (utils.dict_equiv(self.coords, other.coords, compat=compat) and compat(self, other))
Like equals but also checks the array name and attributes and attributes on all coordinates.
def identical(self, other): """Like equals, but also checks the array name and attributes, and attributes on all coordinates. See Also -------- DataArray.broadcast_equals DataArray.equal """ try: return (self.name == other.name and ...
If the dataarray has 1 dimensional coordinates or comes from a slice we can show that info in the title
def _title_for_slice(self, truncate=50): """ If the dataarray has 1 dimensional coordinates or comes from a slice we can show that info in the title Parameters ---------- truncate : integer maximum number of characters for title Returns -----...
Calculate the n - th order discrete difference along given axis.
def diff(self, dim, n=1, label='upper'): """Calculate the n-th order discrete difference along given axis. Parameters ---------- dim : str, optional Dimension over which to calculate the finite difference. n : int, optional The number of times values are ...
Shift this array by an offset along one or more dimensions.
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs): """Shift this array by an offset along one or more dimensions. Only the data is moved; coordinates stay in place. Values shifted from beyond array bounds are replaced by NaN. This is consistent with the behavior of ``s...
Roll this array by an offset along one or more dimensions.
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs): """Roll this array by an offset along one or more dimensions. Unlike shift, roll may rotate all variables, including coordinates if specified. The direction of rotation is consistent with :py:func:`numpy.roll`. Par...
Perform dot product of two DataArrays along their shared dims.
def dot(self, other, dims=None): """Perform dot product of two DataArrays along their shared dims. Equivalent to taking taking tensordot over all shared dims. Parameters ---------- other : DataArray The other array with which the dot product is performed. di...
Sort object by labels or values ( along an axis ).
def sortby(self, variables, ascending=True): """ Sort object by labels or values (along an axis). Sorts the dataarray, either along specified dimensions, or according to values of 1-D dataarrays that share dimension with calling object. If the input variables are dataar...
Compute the qth quantile of the data along the specified dimension.
def quantile(self, q, dim=None, interpolation='linear', keep_attrs=None): """Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements. Parameters ---------- q : float in range of [0,1] (or sequence of floats) ...
Ranks the data.
def rank(self, dim, pct=False, keep_attrs=None): """Ranks the data. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. If pct, computes percentage ranks. NaNs ...
Differentiate the array with the second order accurate central differences.
def differentiate(self, coord, edge_order=1, datetime_unit=None): """ Differentiate the array with the second order accurate central differences. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ...
integrate the array with the trapezoidal rule.
def integrate(self, dim, datetime_unit=None): """ integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str ...
Convert this rolling object to xr. DataArray where the window dimension is stacked as a new dimension
def construct(self, window_dim, stride=1, fill_value=dtypes.NA): """ Convert this rolling object to xr.DataArray, where the window dimension is stacked as a new dimension Parameters ---------- window_dim: str New name of the window dimension. stride: ...
Reduce the items in this group by applying func along some dimension ( s ).
def reduce(self, func, **kwargs): """Reduce the items in this group by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `func(x, **kwargs)` to return the result of collapsing an ...
Number of non - nan entries in each rolling window.
def _counts(self): """ Number of non-nan entries in each rolling window. """ rolling_dim = utils.get_temp_dimname(self.obj.dims, '_rolling_dim') # We use False as the fill_value instead of np.nan, since boolean # array is faster to be reduced than object array. # The use of skip...
Methods to return a wrapped function for any function func for numpy methods.
def _reduce_method(cls, func): """ Methods to return a wrapped function for any function `func` for numpy methods. """ def wrapped_func(self, **kwargs): return self.reduce(func, **kwargs) return wrapped_func
Methods to return a wrapped function for any function func for bottoleneck method except for median.
def _bottleneck_reduce(cls, func): """ Methods to return a wrapped function for any function `func` for bottoleneck method, except for `median`. """ def wrapped_func(self, **kwargs): from .dataarray import DataArray # bottleneck doesn't allow min_count t...
Reduce the items in this group by applying func along some dimension ( s ).
def reduce(self, func, **kwargs): """Reduce the items in this group by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `func(x, **kwargs)` to return the result of collapsing an ...
Return a wrapped function for injecting numpy and bottoleneck methods. see ops. inject_datasetrolling_methods
def _reduce_method(cls, func): """ Return a wrapped function for injecting numpy and bottoleneck methods. see ops.inject_datasetrolling_methods """ def wrapped_func(self, **kwargs): from .dataset import Dataset reduced = OrderedDict() for key,...
Convert this rolling object to xr. Dataset where the window dimension is stacked as a new dimension
def construct(self, window_dim, stride=1, fill_value=dtypes.NA): """ Convert this rolling object to xr.Dataset, where the window dimension is stacked as a new dimension Parameters ---------- window_dim: str New name of the window dimension. stride: in...
Return a wrapped function for injecting numpy methods. see ops. inject_coarsen_methods
def _reduce_method(cls, func): """ Return a wrapped function for injecting numpy methods. see ops.inject_coarsen_methods """ def wrapped_func(self, **kwargs): from .dataarray import DataArray reduced = self.obj.variable.coarsen( self.windo...
Return a wrapped function for injecting numpy methods. see ops. inject_coarsen_methods
def _reduce_method(cls, func): """ Return a wrapped function for injecting numpy methods. see ops.inject_coarsen_methods """ def wrapped_func(self, **kwargs): from .dataset import Dataset reduced = OrderedDict() for key, da in self.obj.data_va...
Ensure that a variable with vlen bytes is converted to fixed width.
def ensure_fixed_length_bytes(var): """Ensure that a variable with vlen bytes is converted to fixed width.""" dims, data, attrs, encoding = unpack_for_encoding(var) if check_vlen_dtype(data.dtype) == bytes: # TODO: figure out how to handle this with dask data = np.asarray(data, dtype=np.stri...
Convert numpy/ dask arrays from fixed width bytes to characters.
def bytes_to_char(arr): """Convert numpy/dask arrays from fixed width bytes to characters.""" if arr.dtype.kind != 'S': raise ValueError('argument must have a fixed-width bytes dtype') if isinstance(arr, dask_array_type): import dask.array as da return da.map_blocks(_numpy_bytes_to_...
Like netCDF4. stringtochar but faster and more flexible.
def _numpy_bytes_to_char(arr): """Like netCDF4.stringtochar, but faster and more flexible. """ # ensure the array is contiguous arr = np.array(arr, copy=False, order='C', dtype=np.string_) return arr.reshape(arr.shape + (1,)).view('S1')
Convert numpy/ dask arrays from characters to fixed width bytes.
def char_to_bytes(arr): """Convert numpy/dask arrays from characters to fixed width bytes.""" if arr.dtype != 'S1': raise ValueError("argument must have dtype='S1'") if not arr.ndim: # no dimension to concatenate along return arr size = arr.shape[-1] if not size: #...
Like netCDF4. chartostring but faster and more flexible.
def _numpy_char_to_bytes(arr): """Like netCDF4.chartostring, but faster and more flexible. """ # based on: http://stackoverflow.com/a/10984878/809705 arr = np.array(arr, copy=False, order='C') dtype = 'S' + str(arr.shape[-1]) return arr.view(dtype).reshape(arr.shape[:-1])
Given an array safely cast it to a pandas. Index.
def safe_cast_to_index(array: Any) -> pd.Index: """Given an array, safely cast it to a pandas.Index. If it is already a pandas.Index, return it unchanged. Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64, this function will not attempt to do automatic type conversion but will ...
Creating a MultiIndex from a product without refactorizing levels.
def multiindex_from_product_levels(levels: Sequence[pd.Index], names: Optional[Sequence[str]] = None ) -> pd.MultiIndex: """Creating a MultiIndex from a product without refactorizing levels. Keeping levels the same gives back the original la...
Wrap a transformed array with __array_wrap__ is it can be done safely.
def maybe_wrap_array(original, new_array): """Wrap a transformed array with __array_wrap__ is it can be done safely. This lets us treat arbitrary functions that take and return ndarray objects like ufuncs, as long as they return an array with the same shape. """ # in case func lost array's metadata...
Compare two objects for equivalence ( identity or equality ) using array_equiv if either object is an ndarray
def equivalent(first: T, second: T) -> bool: """Compare two objects for equivalence (identity or equality), using array_equiv if either object is an ndarray """ # TODO: refactor to avoid circular import from . import duck_array_ops if isinstance(first, np.ndarray) or isinstance(second, np.ndarra...
Returns the first value from iterable as well as a new iterator with the same content as the original iterable
def peek_at(iterable: Iterable[T]) -> Tuple[T, Iterator[T]]: """Returns the first value from iterable, as well as a new iterator with the same content as the original iterable """ gen = iter(iterable) peek = next(gen) return peek, itertools.chain([peek], gen)
Check the safety of updating one dictionary with another.
def update_safety_check(first_dict: MutableMapping[K, V], second_dict: Mapping[K, V], compat: Callable[[V, V], bool] = equivalent) -> None: """Check the safety of updating one dictionary with another. Raises ValueError if dictionaries have non-compatible values f...
Remove incompatible items from the first dictionary in - place.
def remove_incompatible_items(first_dict: MutableMapping[K, V], second_dict: Mapping[K, V], compat: Callable[[V, V], bool] = equivalent ) -> None: """Remove incompatible items from the first dictionary in-place. Items are...
Whether to treat a value as a scalar.
def is_scalar(value: Any) -> bool: """Whether to treat a value as a scalar. Any non-iterable, string, or 0-D array """ return ( getattr(value, 'ndim', None) == 0 or isinstance(value, (str, bytes)) or not isinstance(value, (Iterable, ) + dask_array_type))
Given a value wrap it in a 0 - D numpy. ndarray with dtype = object.
def to_0d_object_array(value: Any) -> np.ndarray: """Given a value, wrap it in a 0-D numpy.ndarray with dtype=object. """ result = np.empty((), dtype=object) result[()] = value return result
Given a value wrap it in a 0 - D numpy. ndarray.
def to_0d_array(value: Any) -> np.ndarray: """Given a value, wrap it in a 0-D numpy.ndarray. """ if np.isscalar(value) or (isinstance(value, np.ndarray) and value.ndim == 0): return np.array(value) else: return to_0d_object_array(value)
Test equivalence of two dict - like objects. If any of the values are numpy arrays compare them correctly.
def dict_equiv(first: Mapping[K, V], second: Mapping[K, V], compat: Callable[[V, V], bool] = equivalent) -> bool: """Test equivalence of two dict-like objects. If any of the values are numpy arrays, compare them correctly. Parameters ---------- first, second : dict-like Dicti...
Return the intersection of two dictionaries as a new OrderedDict.
def ordered_dict_intersection(first_dict: Mapping[K, V], second_dict: Mapping[K, V], compat: Callable[[V, V], bool] = equivalent ) -> MutableMapping[K, V]: """Return the intersection of two dictionaries as a new OrderedDict. ...
Return True if values of an array are uniformly spaced and sorted.
def is_uniform_spaced(arr, **kwargs) -> bool: """Return True if values of an array are uniformly spaced and sorted. >>> is_uniform_spaced(range(5)) True >>> is_uniform_spaced([-4, 0, 100]) False kwargs are additional arguments to ``np.isclose`` """ arr = np.array(arr, dtype=float) ...
Convert attribute values from numpy objects to native Python objects for use in to_dict
def decode_numpy_dict_values(attrs: Mapping[K, V]) -> Dict[K, V]: """Convert attribute values from numpy objects to native Python objects, for use in to_dict """ attrs = dict(attrs) for k, v in attrs.items(): if isinstance(v, np.ndarray): attrs[k] = v.tolist() elif isinst...
Convert val out of numpy time for use in to_dict. Needed because of numpy bug GH#7619
def ensure_us_time_resolution(val): """Convert val out of numpy time, for use in to_dict. Needed because of numpy bug GH#7619""" if np.issubdtype(val.dtype, np.datetime64): val = val.astype('datetime64[us]') elif np.issubdtype(val.dtype, np.timedelta64): val = val.astype('timedelta64[us]...
Get an new dimension name based on new_dim that is not used in dims. If the same name exists we add an underscore ( s ) in the head.
def get_temp_dimname(dims: Container[Hashable], new_dim: Hashable) -> Hashable: """ Get an new dimension name based on new_dim, that is not used in dims. If the same name exists, we add an underscore(s) in the head. Example1: dims: ['a', 'b', 'c'] new_dim: ['_rolling'] -> ['_rolling...
Given an object array with no missing values infer its dtype from its first element
def _infer_dtype(array, name=None): """Given an object array with no missing values, infer its dtype from its first element """ if array.dtype.kind != 'O': raise TypeError('infer_type must be called on a dtype=object array') if array.size == 0: return np.dtype(float) element = ...
Create a copy of an array with the given dtype.
def _copy_with_dtype(data, dtype): """Create a copy of an array with the given dtype. We use this instead of np.array() to ensure that custom object dtypes end up on the resulting array. """ result = np.empty(data.shape, dtype) result[...] = data return result
Converts an Variable into an Variable which follows some of the CF conventions:
def encode_cf_variable(var, needs_copy=True, name=None): """ Converts an Variable into an Variable which follows some of the CF conventions: - Nans are masked using _FillValue (or the deprecated missing_value) - Rescaling via: scale_factor and add_offset - datetimes are converted to...
Decodes a variable which may hold CF encoded information.
def decode_cf_variable(name, var, concat_characters=True, mask_and_scale=True, decode_times=True, decode_endianness=True, stack_char_dim=True, use_cftime=None): """ Decodes a variable which may hold CF encoded information. This includes variables that have been...
Adds time attributes to time bounds variables.
def _update_bounds_attributes(variables): """Adds time attributes to time bounds variables. Variables handling time bounds ("Cell boundaries" in the CF conventions) do not necessarily carry the necessary attributes to be decoded. This copies the attributes from the time variable to the associated b...
Decode several CF encoded variables.
def decode_cf_variables(variables, attributes, concat_characters=True, mask_and_scale=True, decode_times=True, decode_coords=True, drop_variables=None, use_cftime=None): """ Decode several CF encoded variables. See: decode_cf_variable ...
Decode the given Dataset or Datastore according to CF conventions into a new Dataset.
def decode_cf(obj, concat_characters=True, mask_and_scale=True, decode_times=True, decode_coords=True, drop_variables=None, use_cftime=None): """Decode the given Dataset or Datastore according to CF conventions into a new Dataset. Parameters ---------- obj : Dataset or D...
Decode a set of CF encoded variables and attributes.
def cf_decoder(variables, attributes, concat_characters=True, mask_and_scale=True, decode_times=True): """ Decode a set of CF encoded variables and attributes. See Also, decode_cf_variable Parameters ---------- variables : dict A dictionary mapping from va...
Encode coordinates on the given dataset object into variable specific and global attributes.
def encode_dataset_coordinates(dataset): """Encode coordinates on the given dataset object into variable specific and global attributes. When possible, this is done according to CF conventions. Parameters ---------- dataset : Dataset Object to encode. Returns ------- varia...
A function which takes a dicts of variables and attributes and encodes them to conform to CF conventions as much as possible. This includes masking scaling character array handling and CF - time encoding.
def cf_encoder(variables, attributes): """ A function which takes a dicts of variables and attributes and encodes them to conform to CF conventions as much as possible. This includes masking, scaling, character array handling, and CF-time encoding. Decode a set of CF encoded variables and attr...
Coerce an array to a data type that can be stored in a netCDF - 3 file
def coerce_nc3_dtype(arr): """Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keywo...
Test whether an object can be validly converted to a netCDF - 3 dimension variable or attribute name
def is_valid_nc3_name(s): """Test whether an object can be validly converted to a netCDF-3 dimension, variable or attribute name Earlier versions of the netCDF C-library reference implementation enforced a more restricted set of characters in creating new names, but permitted reading names containi...
Convert an object into a Variable.
def as_variable(obj, name=None) -> 'Union[Variable, IndexVariable]': """Convert an object into a Variable. Parameters ---------- obj : object Object to convert into a Variable. - If the object is already a Variable, return a shallow copy. - Otherwise, if the object has 'dims' a...
Convert arrays of datetime. datetime and datetime. timedelta objects into datetime64 and timedelta64 according to the pandas convention.
def _possibly_convert_objects(values): """Convert arrays of datetime.datetime and datetime.timedelta objects into datetime64 and timedelta64, according to the pandas convention. """ return np.asarray(pd.Series(values.ravel())).reshape(values.shape)
Prepare and wrap data to put in a Variable.
def as_compatible_data(data, fastpath=False): """Prepare and wrap data to put in a Variable. - If data does not have the necessary attributes, convert it to ndarray. - If data has dtype=datetime64, ensure that it has ns precision. If it's a pandas.Timestamp, convert it to datetime64. - If data is...
Return the given values as a numpy array or as an individual item if it s a 0d datetime64 or timedelta64 array.
def _as_array_or_item(data): """Return the given values as a numpy array, or as an individual item if it's a 0d datetime64 or timedelta64 array. Importantly, this function does not copy data if it is already an ndarray - otherwise, it will not be possible to update Variable values in place. This f...
Create broadcast compatible variables with the same dimensions.
def _broadcast_compat_variables(*variables): """Create broadcast compatible variables, with the same dimensions. Unlike the result of broadcast_variables(), some variables may have dimensions of size 1 instead of the the size of the broadcast dimension. """ dims = tuple(_unified_dims(variables)) ...
Given any number of variables return variables with matching dimensions and broadcast data.
def broadcast_variables(*variables): """Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and inserted so that both broadca...
Concatenate variables along a new or existing dimension.
def concat(variables, dim='concat_dim', positions=None, shortcut=False): """Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have matching dimensions and shape except for a...
Check for uniqueness of MultiIndex level names in all given variables.
def assert_unique_multiindex_level_names(variables): """Check for uniqueness of MultiIndex level names in all given variables. Not public API. Used for checking consistency of DataArray and Dataset objects. """ level_names = defaultdict(list) all_level_names = set() for var_name, var in...
Manually trigger loading of this variable s data from disk or a remote source into memory and return this variable.
def load(self, **kwargs): """Manually trigger loading of this variable's data from disk or a remote source into memory and return this variable. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data or ...
Return this variable as a base xarray. Variable
def to_base_variable(self): """Return this variable as a base xarray.Variable""" return Variable(self.dims, self._data, self._attrs, encoding=self._encoding, fastpath=True)
Return this variable as an xarray. IndexVariable
def to_index_variable(self): """Return this variable as an xarray.IndexVariable""" return IndexVariable(self.dims, self._data, self._attrs, encoding=self._encoding, fastpath=True)
Dictionary representation of variable.
def to_dict(self, data=True): """Dictionary representation of variable.""" item = {'dims': self.dims, 'attrs': decode_numpy_dict_values(self.attrs)} if data: item['data'] = ensure_us_time_resolution(self.values).tolist() else: item.update({'dtype':...
Prepare an indexing key for an indexing operation.
def _broadcast_indexes(self, key): """Prepare an indexing key for an indexing operation. Parameters ----------- key: int, slice, array, dict or tuple of integer, slices and arrays Any valid input for indexing. Returns ------- dims: tuple ...
Make sanity checks
def _validate_indexers(self, key): """ Make sanity checks """ for dim, k in zip(self.dims, key): if isinstance(k, BASIC_INDEXING_TYPES): pass else: if not isinstance(k, Variable): k = np.asarray(k) if k.ndim ...
Equivalent numpy s nonzero but returns a tuple of Varibles.
def _nonzero(self): """ Equivalent numpy's nonzero but returns a tuple of Varibles. """ # TODO we should replace dask's native nonzero # after https://github.com/dask/dask/issues/1076 is implemented. nonzeros = np.nonzero(self.data) return tuple(Variable((dim), nz) for nz, dim ...
Used by IndexVariable to return IndexVariable objects when possible.
def _finalize_indexing_result(self, dims, data): """Used by IndexVariable to return IndexVariable objects when possible. """ return type(self)(dims, data, self._attrs, self._encoding, fastpath=True)
Index this Variable with - 1 remapped to fill_value.
def _getitem_with_mask(self, key, fill_value=dtypes.NA): """Index this Variable with -1 remapped to fill_value.""" # TODO(shoyer): expose this method in public API somewhere (isel?) and # use it for reindex. # TODO(shoyer): add a sanity check that all other integers are # non-neg...
Returns a copy of this object.
def copy(self, deep=True, data=None): """Returns a copy of this object. If `deep=True`, the data array is loaded into memory and copied onto the new object. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same structure as orig...
Coerce this array s data into a dask arrays with the given chunks.
def chunk(self, chunks=None, name=None, lock=False): """Coerce this array's data into a dask arrays with the given chunks. If this variable is a non-dask array, it will be converted to dask array. If it's a dask array, it will be rechunked to the given chunk sizes. If neither c...
Return a new array indexed along the specified dimension ( s ).
def isel(self, indexers=None, drop=False, **indexers_kwargs): """Return a new array indexed along the specified dimension(s). Parameters ---------- **indexers : {dim: indexer, ...} Keyword arguments with names matching dimensions and values given by integers, sli...
Return a new object with squeezed data.
def squeeze(self, dim=None): """Return a new object with squeezed data. Parameters ---------- dim : None or str or tuple of str, optional Selects a subset of the length one dimensions. If a dimension is selected with length greater than one, an error is raised. I...
Return a new Variable with shifted data.
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs): """ Return a new Variable with shifted data. Parameters ---------- shifts : mapping of the form {dim: offset} Integer offset to shift along each of the given dimensions. Positive offsets...
Return a new Variable with paddings.
def pad_with_fill_value(self, pad_widths=None, fill_value=dtypes.NA, **pad_widths_kwargs): """ Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the ...
Return a new Variable with rolld data.
def roll(self, shifts=None, **shifts_kwargs): """ Return a new Variable with rolld data. Parameters ---------- shifts : mapping of the form {dim: offset} Integer offset to roll along each of the given dimensions. Positive offsets roll to the right; negati...
Return a new Variable object with transposed dimensions.
def transpose(self, *dims) -> 'Variable': """Return a new Variable object with transposed dimensions. Parameters ---------- *dims : str, optional By default, reverse the dimensions. Otherwise, reorder the dimensions to this order. Returns -------...
Return a new variable with given set of dimensions. This method might be used to attach new dimension ( s ) to variable.
def set_dims(self, dims, shape=None): """Return a new variable with given set of dimensions. This method might be used to attach new dimension(s) to variable. When possible, this operation does not copy this variable's data. Parameters ---------- dims : str or sequence ...
Stack any number of existing dimensions into a single new dimension.
def stack(self, dimensions=None, **dimensions_kwargs): """ Stack any number of existing dimensions into a single new dimension. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ------...
Unstack an existing dimension into multiple new dimensions.
def unstack(self, dimensions=None, **dimensions_kwargs): """ Unstack an existing dimension into multiple new dimensions. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ---------- ...
Reduce this array by applying func along some dimension ( s ).
def reduce(self, func, dim=None, axis=None, keep_attrs=None, allow_lazy=False, **kwargs): """Reduce this array by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `func(x, axis=...
Concatenate variables along a new or existing dimension.
def concat(cls, variables, dim='concat_dim', positions=None, shortcut=False): """Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have ...
True if two Variables have the same dimensions and values ; otherwise False.
def equals(self, other, equiv=duck_array_ops.array_equiv): """True if two Variables have the same dimensions and values; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations. This method is necessary because `v1 == v2...
True if two Variables have the values after being broadcast against each other ; otherwise False.
def broadcast_equals(self, other, equiv=duck_array_ops.array_equiv): """True if two Variables have the values after being broadcast against each other; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations. """ ...
Like equals but also checks attributes.
def identical(self, other): """Like equals, but also checks attributes. """ try: return (utils.dict_equiv(self.attrs, other.attrs) and self.equals(other)) except (TypeError, AttributeError): return False
Compute the qth quantile of the data along the specified dimension.
def quantile(self, q, dim=None, interpolation='linear'): """Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements. Parameters ---------- q : float in range of [0,1] (or sequence of floats) Quantile to ...
Ranks the data.
def rank(self, dim, pct=False): """Ranks the data. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks. NaNs in the input ar...
Make a rolling_window along dim and add a new_dim to the last place.
def rolling_window(self, dim, window, window_dim, center=False, fill_value=dtypes.NA): """ Make a rolling_window along dim and add a new_dim to the last place. Parameters ---------- dim: str Dimension over which to compute rolling_window ...
Apply
def coarsen(self, windows, func, boundary='exact', side='left'): """ Apply """ windows = {k: v for k, v in windows.items() if k in self.dims} if not windows: return self.copy() reshaped, axes = self._coarsen_reshape(windows, boundary, side) if isinsta...
Construct a reshaped - array for corsen
def _coarsen_reshape(self, windows, boundary, side): """ Construct a reshaped-array for corsen """ if not utils.is_dict_like(boundary): boundary = {d: boundary for d in windows.keys()} if not utils.is_dict_like(side): side = {d: side for d in windows.keys...
A ( private ) method to convert datetime array to numeric dtype See duck_array_ops. datetime_to_numeric
def _to_numeric(self, offset=None, datetime_unit=None, dtype=float): """ A (private) method to convert datetime array to numeric dtype See duck_array_ops.datetime_to_numeric """ numeric_array = duck_array_ops.datetime_to_numeric( self.data, offset, datetime_unit, dtype) ...
Specialized version of Variable. concat for IndexVariable objects.
def concat(cls, variables, dim='concat_dim', positions=None, shortcut=False): """Specialized version of Variable.concat for IndexVariable objects. This exists because we want to avoid converting Index objects to NumPy arrays, if possible. """ if not isinstance(dim...