INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Manually trigger loading of this dataset s data from disk or a remote source into memory and return this dataset. | 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. | 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 | 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. | 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. | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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 ). | 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 ). | 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 ). | 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 ). | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 ). | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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 | 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. | 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 ). | 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(... |
Apply a function over the data variables in this dataset. | def apply(self, func, keep_attrs=None, args=(), **kwargs):
"""Apply a function over the data variables in this dataset.
Parameters
----------
func : function
Function which can be called in the form `func(x, *args, **kwargs)`
to transform each DataArray `x` in th... |
Assign new data variables to a Dataset returning a new object with all the original variables in addition to the new ones. | 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... |
Convert this dataset into an xarray. DataArray | def to_array(self, dim='variable', name=None):
"""Convert this dataset into an xarray.DataArray
The data variables of this dataset will be broadcast against each other
and stacked along the first axis of the new array. All coordinates of
this dataset will remain coordinates.
Pa... |
Convert a pandas. DataFrame into an xarray. Dataset | def from_dataframe(cls, dataframe):
"""Convert a pandas.DataFrame into an xarray.Dataset
Each column will be converted into an independent variable in the
Dataset. If the dataframe's index is a MultiIndex, it will be expanded
into a tensor product of one-dimensional indices (filling in ... |
Convert this dataset into a dask. dataframe. DataFrame. | def to_dask_dataframe(self, dim_order=None, set_index=False):
"""
Convert this dataset into a dask.dataframe.DataFrame.
The dimensions, coordinates and data variables in this dataset form
the columns of the DataFrame.
Parameters
----------
dim_order : list, opti... |
Convert this dataset to a dictionary following xarray naming conventions. | def to_dict(self, data=True):
"""
Convert this dataset to 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 kwarg in xarr... |
Convert a dictionary into an xarray. Dataset. | def from_dict(cls, d):
"""
Convert a dictionary into an xarray.Dataset.
Input dict can take several forms::
d = {'t': {'dims': ('t'), 'data': t},
'a': {'dims': ('t'), 'data': x},
'b': {'dims': ('t'), 'data': y}}
d = {'coords': {'t': {'... |
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 dataset by an offset along one or more dimensions. | def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
"""Shift this dataset by an offset along one or more dimensions.
Only data variables are moved; coordinates stay in place. This is
consistent with the behavior of ``shift`` in pandas.
Parameters
----------
... |
Roll this dataset by an offset along one or more dimensions. | def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
"""Roll this dataset 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`.
P... |
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 dataset, either along specified dimensions,
or according to values of 1-D dataarrays that share dimension
with calling object.
If the input variables are dataarra... |
Compute the qth quantile of the data along the specified dimension. | def quantile(self, q, dim=None, interpolation='linear',
numeric_only=False, keep_attrs=None):
"""Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements for each variable
in the Dataset.
Parameters
... |
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 is True, computes percentage ranks.... |
Differentiate with the second order accurate central differences. | def differentiate(self, coord, edge_order=1, datetime_unit=None):
""" Differentiate 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, coord, 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
... |
Returns a Dataset with variables that match specific conditions. | def filter_by_attrs(self, **kwargs):
"""Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either ``key=value`` for ... |
Lazily apply an element - wise function to an array. | def lazy_elemwise_func(array, func, dtype):
"""Lazily apply an element-wise function to an array.
Parameters
----------
array : any valid value of Variable._data
func : callable
Function to apply to indexed slices of an array. For use with dask,
this should be a pickle-able object.
... |
A convenience function which pops a key k from source to dest. None values are not passed on. If k already exists in dest an error is raised. | def pop_to(source, dest, key, name=None):
"""
A convenience function which pops a key k from source to dest.
None values are not passed on. If k already exists in dest an
error is raised.
"""
value = source.pop(key, None)
if value is not None:
safe_setitem(dest, key, value, name=nam... |
Mask all matching values in a NumPy arrays. | def _apply_mask(
data: np.ndarray,
encoded_fill_values: list,
decoded_fill_value: Any,
dtype: Any,
) -> np.ndarray:
"""Mask all matching values in a NumPy arrays."""
data = np.asarray(data, dtype=dtype)
condition = False
for fv in encoded_fill_values:
condition |= data == fv
... |
Return a float dtype that can losslessly represent dtype values. | def _choose_float_dtype(dtype, has_offset):
"""Return a float dtype that can losslessly represent `dtype` values."""
# Keep float32 as-is. Upcast half-precision to single-precision,
# because float16 is "intended for storage but not computation"
if dtype.itemsize <= 4 and np.issubdtype(dtype, np.floati... |
wrapper for datasets | def _apply_over_vars_with_dim(func, self, dim=None, **kwargs):
'''wrapper for datasets'''
ds = type(self)(coords=self.coords, attrs=self.attrs)
for name, var in self.data_vars.items():
if dim in var.dims:
ds[name] = func(var, dim=dim, **kwargs)
else:
ds[name] = var
... |
get index to use for x values in interpolation. | def get_clean_interp_index(arr, dim, use_coordinate=True, **kwargs):
'''get index to use for x values in interpolation.
If use_coordinate is True, the coordinate that shares the name of the
dimension along which interpolation is being performed will be used as the
x values.
If use_coordinate is Fa... |
Interpolate values according to different methods. | def interp_na(self, dim=None, use_coordinate=True, method='linear', limit=None,
**kwargs):
'''Interpolate values according to different methods.'''
if dim is None:
raise NotImplementedError('dim is a required argument')
if limit is not None:
valids = _get_valid_fill_mask(self... |
helper function to apply interpolation along 1 dimension | def func_interpolate_na(interpolator, x, y, **kwargs):
'''helper function to apply interpolation along 1 dimension'''
# it would be nice if this wasn't necessary, works around:
# "ValueError: assignment destination is read-only" in assignment below
out = y.copy()
nans = pd.isnull(y)
nonans = ~n... |
inverse of ffill | def _bfill(arr, n=None, axis=-1):
'''inverse of ffill'''
import bottleneck as bn
arr = np.flip(arr, axis=axis)
# fill
arr = bn.push(arr, axis=axis, n=n)
# reverse back to original
return np.flip(arr, axis=axis) |
forward fill missing values | def ffill(arr, dim=None, limit=None):
'''forward fill missing values'''
import bottleneck as bn
axis = arr.get_axis_num(dim)
# work around for bottleneck 178
_limit = limit if limit is not None else arr.shape[axis]
return apply_ufunc(bn.push, arr,
dask='parallelized',
... |
backfill missing values | def bfill(arr, dim=None, limit=None):
'''backfill missing values'''
axis = arr.get_axis_num(dim)
# work around for bottleneck 178
_limit = limit if limit is not None else arr.shape[axis]
return apply_ufunc(_bfill, arr,
dask='parallelized',
keep_attrs=T... |
helper function to select the appropriate interpolator class | def _get_interpolator(method, vectorizeable_only=False, **kwargs):
'''helper function to select the appropriate interpolator class
returns interpolator class and keyword arguments for the class
'''
interp1d_methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic',
'cubic',... |
helper function to select the appropriate interpolator class | def _get_interpolator_nd(method, **kwargs):
'''helper function to select the appropriate interpolator class
returns interpolator class and keyword arguments for the class
'''
valid_methods = ['linear', 'nearest']
try:
from scipy import interpolate
except ImportError:
raise Impo... |
helper function to determine values that can be filled when limit is not None | def _get_valid_fill_mask(arr, dim, limit):
'''helper function to determine values that can be filled when limit is not
None'''
kw = {dim: limit + 1}
# we explicitly use construct method to avoid copy.
new_dim = utils.get_temp_dimname(arr.dims, '_window')
return (arr.isnull().rolling(min_periods=... |
Speed up for linear and nearest neighbor method. Only consider a subspace that is needed for the interpolation | def _localize(var, indexes_coords):
""" Speed up for linear and nearest neighbor method.
Only consider a subspace that is needed for the interpolation
"""
indexes = {}
for dim, [x, new_x] in indexes_coords.items():
index = x.to_index()
imin = index.get_loc(np.min(new_x.values), metho... |
Make x and new_x float. This is particulary useful for datetime dtype. x new_x: tuple of np. ndarray | def _floatize_x(x, new_x):
""" Make x and new_x float.
This is particulary useful for datetime dtype.
x, new_x: tuple of np.ndarray
"""
x = list(x)
new_x = list(new_x)
for i in range(len(x)):
if _contains_datetime_like_objects(x[i]):
# Scipy casts coordinates to np.float6... |
Make an interpolation of Variable | def interp(var, indexes_coords, method, **kwargs):
""" Make an interpolation of Variable
Parameters
----------
var: Variable
index_coords:
Mapping from dimension name to a pair of original and new coordinates.
Original coordinates should be sorted in strictly ascending order.
... |
multi - dimensional interpolation for array - like. Interpolated axes should be located in the last position. | def interp_func(var, x, new_x, method, kwargs):
"""
multi-dimensional interpolation for array-like. Interpolated axes should be
located in the last position.
Parameters
----------
var: np.ndarray or dask.array.Array
Array to be interpolated. The final dimension is interpolated.
x: a... |
Put coord value in template and truncate at maxchar | def _nicetitle(coord, value, maxchar, template):
"""
Put coord, value in template and truncate at maxchar
"""
prettyvalue = format_item(value, quote_strings=False)
title = template.format(coord=coord, value=prettyvalue)
if len(title) > maxchar:
title = title[:(maxchar - 3)] + '...'
... |
Convenience method to call xarray. plot. FacetGrid from 2d plotting methods | def _easy_facetgrid(data, plotfunc, kind, x=None, y=None, row=None,
col=None, col_wrap=None, sharex=True, sharey=True,
aspect=None, size=None, subplot_kws=None, **kwargs):
"""
Convenience method to call xarray.plot.FacetGrid from 2d plotting methods
kwargs are the ar... |
Apply a plotting function to a 2d facet s subset of the data. | def map_dataarray(self, func, x, y, **kwargs):
"""
Apply a plotting function to a 2d facet's subset of the data.
This is more convenient and less general than ``FacetGrid.map``
Parameters
----------
func : callable
A plotting function with the same signature... |
Finalize the annotations and layout. | def _finalize_grid(self, *axlabels):
"""Finalize the annotations and layout."""
if not self._finalized:
self.set_axis_labels(*axlabels)
self.set_titles()
self.fig.tight_layout()
for ax, namedict in zip(self.axes.flat, self.name_dicts.flat):
... |
Draw a colorbar | def add_colorbar(self, **kwargs):
"""Draw a colorbar
"""
kwargs = kwargs.copy()
if self._cmap_extend is not None:
kwargs.setdefault('extend', self._cmap_extend)
if 'label' not in kwargs:
kwargs.setdefault('label', label_from_attrs(self.data))
self.... |
Set axis labels on the left column and bottom row of the grid. | def set_axis_labels(self, x_var=None, y_var=None):
"""Set axis labels on the left column and bottom row of the grid."""
if x_var is not None:
if x_var in self.data.coords:
self._x_var = x_var
self.set_xlabels(label_from_attrs(self.data[x_var]))
els... |
Label the x axis on the bottom row of the grid. | def set_xlabels(self, label=None, **kwargs):
"""Label the x axis on the bottom row of the grid."""
if label is None:
label = label_from_attrs(self.data[self._x_var])
for ax in self._bottom_axes:
ax.set_xlabel(label, **kwargs)
return self |
Label the y axis on the left column of the grid. | def set_ylabels(self, label=None, **kwargs):
"""Label the y axis on the left column of the grid."""
if label is None:
label = label_from_attrs(self.data[self._y_var])
for ax in self._left_axes:
ax.set_ylabel(label, **kwargs)
return self |
Draw titles either above each facet or on the grid margins. | def set_titles(self, template="{coord} = {value}", maxchar=30,
**kwargs):
"""
Draw titles either above each facet or on the grid margins.
Parameters
----------
template : string
Template for plot titles containing {coord} and {value}
maxcha... |
Set and control tick behavior | def set_ticks(self, max_xticks=_NTICKS, max_yticks=_NTICKS,
fontsize=_FONTSIZE):
"""
Set and control tick behavior
Parameters
----------
max_xticks, max_yticks : int, optional
Maximum number of labeled ticks to plot on x, y axes
fontsize : s... |
Apply a plotting function to each facet s subset of the data. | def map(self, func, *args, **kwargs):
"""
Apply a plotting function to each facet's subset of the data.
Parameters
----------
func : callable
A plotting function that takes data and keyword arguments. It
must plot to the currently active matplotlib Axes a... |
Obtain the bins and their respective labels for resampling operations. | def _get_time_bins(index, freq, closed, label, base):
"""Obtain the bins and their respective labels for resampling operations.
Parameters
----------
index : CFTimeIndex
Index object to be resampled (e.g., CFTimeIndex named 'time').
freq : xarray.coding.cftime_offsets.BaseCFTimeOffset
... |
This is required for determining the bin edges resampling with daily frequencies greater than one day month end and year end frequencies. | def _adjust_bin_edges(datetime_bins, offset, closed, index, labels):
"""This is required for determining the bin edges resampling with
daily frequencies greater than one day, month end, and year end
frequencies.
Consider the following example. Let's say you want to downsample the
time series with ... |
Get the correct starting and ending datetimes for the resampled CFTimeIndex range. | def _get_range_edges(first, last, offset, closed='left', base=0):
""" Get the correct starting and ending datetimes for the resampled
CFTimeIndex range.
Parameters
----------
first : cftime.datetime
Uncorrected starting datetime object for resampled CFTimeIndex range.
Usually the mi... |
First and last offsets should be calculated from the start day to fix an error cause by resampling across multiple days when a one day period is not a multiple of the frequency. See https:// github. com/ pandas - dev/ pandas/ issues/ 8683 | def _adjust_dates_anchored(first, last, offset, closed='right', base=0):
""" First and last offsets should be calculated from the start day to fix
an error cause by resampling across multiple days when a one day period is
not a multiple of the frequency.
See https://github.com/pandas-dev/pandas/issues/8... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.