INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
This provides a centralized method to set the variables on the data store. | def set_variables(self, variables, check_encoding_set, writer,
unlimited_dims=None):
"""
This provides a centralized method to set the variables on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (vari... |
This provides a centralized method to set the dimensions on the data store. | def set_dimensions(self, variables, unlimited_dims=None):
"""
This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited... |
Compute season ( DJF MAM JJA SON ) from month ordinal | def _season_from_months(months):
"""Compute season (DJF, MAM, JJA, SON) from month ordinal
"""
# TODO: Move "season" accessor upstream into pandas
seasons = np.array(['DJF', 'MAM', 'JJA', 'SON'])
months = np.asarray(months)
return seasons[(months // 3) % 4] |
Coerce an array of datetime - like values to a CFTimeIndex and access requested datetime component | def _access_through_cftimeindex(values, name):
"""Coerce an array of datetime-like values to a CFTimeIndex
and access requested datetime component
"""
from ..coding.cftimeindex import CFTimeIndex
values_as_cftimeindex = CFTimeIndex(values.ravel())
if name == 'season':
months = values_as_... |
Coerce an array of datetime - like values to a pandas Series and access requested datetime component | def _access_through_series(values, name):
"""Coerce an array of datetime-like values to a pandas Series and
access requested datetime component
"""
values_as_series = pd.Series(values.ravel())
if name == "season":
months = values_as_series.dt.month.values
field_values = _season_from_... |
Indirectly access pandas libts. get_date_field by wrapping data as a Series and calling through. dt attribute. | def _get_date_field(values, name, dtype):
"""Indirectly access pandas' libts.get_date_field by wrapping data
as a Series and calling through `.dt` attribute.
Parameters
----------
values : np.ndarray or dask.array-like
Array-like container of datetime-like values
name : str
Name... |
Coerce an array of datetime - like values to a pandas Series and apply requested rounding | def _round_series(values, name, freq):
"""Coerce an array of datetime-like values to a pandas Series and
apply requested rounding
"""
values_as_series = pd.Series(values.ravel())
method = getattr(values_as_series.dt, name)
field_values = method(freq=freq).values
return field_values.reshape(... |
Indirectly access pandas rounding functions by wrapping data as a Series and calling through. dt attribute. | def _round_field(values, name, freq):
"""Indirectly access pandas rounding functions by wrapping data
as a Series and calling through `.dt` attribute.
Parameters
----------
values : np.ndarray or dask.array-like
Array-like container of datetime-like values
name : str (ceil, floor, round... |
Fill missing values in this object with data from the other object. Follows normal broadcasting and alignment rules. | def fillna(data, other, join="left", dataset_join="left"):
"""Fill missing values in this object with data from the other object.
Follows normal broadcasting and alignment rules.
Parameters
----------
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining the indexes of the... |
Return elements from self or other depending on cond. | def where_method(self, cond, other=dtypes.NA):
"""Return elements from `self` or `other` depending on `cond`.
Parameters
----------
cond : DataArray or Dataset with boolean dtype
Locations at which to preserve this objects values.
other : scalar, DataArray or Dataset, optional
Value... |
Load a dataset from the online repository ( requires internet ). | def open_dataset(name, cache=True, cache_dir=_default_cache_dir,
github_url='https://github.com/pydata/xarray-data',
branch='master', **kws):
"""
Load a dataset from the online repository (requires internet).
If a local copy is found then always use that to avoid network t... |
load_dataset will be removed a future version of xarray. The current behavior of this function can be achived by using tutorial. open_dataset (... ). load (). | def load_dataset(*args, **kwargs):
"""
`load_dataset` will be removed a future version of xarray. The current
behavior of this function can be achived by using
`tutorial.open_dataset(...).load()`.
See Also
--------
open_dataset
"""
warnings.warn(
"load_dataset` will be remov... |
Make a key for caching files in the LRU cache. | def _make_key(self):
"""Make a key for caching files in the LRU cache."""
value = (self._opener,
self._args,
'a' if self._mode == 'w' else self._mode,
tuple(sorted(self._kwargs.items())))
return _HashedSequence(value) |
Acquiring a file object from the manager. | def acquire(self, needs_lock=True):
"""Acquiring a file object from the manager.
A new file is only opened if it has expired from the
least-recently-used cache.
This method uses a lock, which ensures that it is thread-safe. You can
safely acquire a file in multiple threads at t... |
Explicitly close any associated file object ( if necessary ). | def close(self, needs_lock=True):
"""Explicitly close any associated file object (if necessary)."""
# TODO: remove needs_lock if/when we have a reentrant lock in
# dask.distributed: https://github.com/dask/dask/issues/3832
with self._optional_lock(needs_lock):
default = None
... |
Shrink the cache if necessary evicting the oldest items. | def _enforce_size_limit(self, capacity):
"""Shrink the cache if necessary, evicting the oldest items."""
while len(self._cache) > capacity:
key, value = self._cache.popitem(last=False)
if self._on_evict is not None:
self._on_evict(key, value) |
Resize the cache evicting the oldest items if necessary. | def maxsize(self, size):
"""Resize the cache, evicting the oldest items if necessary."""
if size < 0:
raise ValueError('maxsize must be non-negative')
with self._lock:
self._enforce_size_limit(size)
self._maxsize = size |
Returns system information as a dict | def get_sys_info():
"Returns system information as a dict"
blob = []
# get full commit hash
commit = None
if os.path.isdir(".git") and os.path.isdir("xarray"):
try:
pipe = subprocess.Popen('git log --format="%H" -n 1'.split(" "),
stdout=subpr... |
Given a key for indexing an ndarray return an equivalent key which is a tuple with length equal to the number of dimensions. | def expanded_indexer(key, ndim):
"""Given a key for indexing an ndarray, return an equivalent key which is a
tuple with length equal to the number of dimensions.
The expansion is done by replacing all `Ellipsis` items with the right
number of full slices and then padding the key with full slices so tha... |
Convert values into a numpy array of at most 1 - dimension while preserving tuples. | def _asarray_tuplesafe(values):
"""
Convert values into a numpy array of at most 1-dimension, while preserving
tuples.
Adapted from pandas.core.common._asarray_tuplesafe
"""
if isinstance(values, tuple):
result = utils.to_0d_object_array(values)
else:
result = np.asarray(val... |
Call pd. Index. get_indexer ( labels ). | def get_indexer_nd(index, labels, method=None, tolerance=None):
""" Call pd.Index.get_indexer(labels). """
kwargs = _index_method_kwargs(method, tolerance)
flat_labels = np.ravel(labels)
flat_indexer = index.get_indexer(flat_labels, **kwargs)
indexer = flat_indexer.reshape(labels.shape)
return ... |
Given a pandas. Index and labels ( e. g. from __getitem__ ) for one dimension return an indexer suitable for indexing an ndarray along that dimension. If index is a pandas. MultiIndex and depending on label return a new pandas. Index or pandas. MultiIndex ( otherwise return None ). | def convert_label_indexer(index, label, index_name='', method=None,
tolerance=None):
"""Given a pandas.Index and labels (e.g., from __getitem__) for one
dimension, return an indexer suitable for indexing an ndarray along that
dimension. If `index` is a pandas.MultiIndex and dependi... |
Given a xarray data object and label based indexers return a mapping of label indexers with only dimension names as keys. | def get_dim_indexers(data_obj, indexers):
"""Given a xarray data object and label based indexers, return a mapping
of label indexers with only dimension names as keys.
It groups multiple level indexers given on a multi-index dimension
into a single, dictionary indexer for that dimension (Raise a ValueE... |
Given an xarray data object and label based indexers return a mapping of equivalent location based indexers. Also return a mapping of updated pandas index objects ( in case of multi - index level drop ). | def remap_label_indexers(data_obj, indexers, method=None, tolerance=None):
"""Given an xarray data object and label based indexers, return a mapping
of equivalent location based indexers. Also return a mapping of updated
pandas index objects (in case of multi-index level drop).
"""
if method is not ... |
Given a slice and the size of the dimension to which it will be applied index it with another slice to return a new slice equivalent to applying the slices sequentially | def slice_slice(old_slice, applied_slice, size):
"""Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
"""
step = (old_slice.step or 1) * (applied_slice.step or 1)
# For now, u... |
This function always returns a ExplicitlyIndexed subclass so that the vectorized indexing is always possible with the returned object. | def as_indexable(array):
"""
This function always returns a ExplicitlyIndexed subclass,
so that the vectorized indexing is always possible with the returned
object.
"""
if isinstance(array, ExplicitlyIndexed):
return array
if isinstance(array, np.ndarray):
return NumpyIndexin... |
Convert an OuterIndexer into an vectorized indexer. | def _outer_to_vectorized_indexer(key, shape):
"""Convert an OuterIndexer into an vectorized indexer.
Parameters
----------
key : Outer/Basic Indexer
An indexer to convert.
shape : tuple
Shape of the array subject to the indexing.
Returns
-------
VectorizedIndexer
... |
Convert an OuterIndexer into an indexer for NumPy. | def _outer_to_numpy_indexer(key, shape):
"""Convert an OuterIndexer into an indexer for NumPy.
Parameters
----------
key : Basic/OuterIndexer
An indexer to convert.
shape : tuple
Shape of the array subject to the indexing.
Returns
-------
tuple
Tuple suitable fo... |
Combine two indexers. | def _combine_indexers(old_key, shape, new_key):
""" Combine two indexers.
Parameters
----------
old_key: ExplicitIndexer
The first indexer for the original array
shape: tuple of ints
Shape of the original array to be indexed by old_key
new_key:
The second indexer for ind... |
Support explicit indexing by delegating to a raw indexing method. | def explicit_indexing_adapter(
key, shape, indexing_support, raw_indexing_method):
"""Support explicit indexing by delegating to a raw indexing method.
Outer and/or vectorized indexers are supported by indexing a second time
with a NumPy array.
Parameters
----------
key : ExplicitIndex... |
convert a slice to successive two slices. The first slice always has a positive step. | def _decompose_slice(key, size):
""" convert a slice to successive two slices. The first slice always has
a positive step.
"""
start, stop, step = key.indices(size)
if step > 0:
# If key already has a positive step, use it as is in the backend
return key, slice(None)
else:
... |
Decompose vectorized indexer to the successive two indexers where the first indexer will be used to index backend arrays while the second one is used to index loaded on - memory np. ndarray. | def _decompose_vectorized_indexer(indexer, shape, indexing_support):
"""
Decompose vectorized indexer to the successive two indexers, where the
first indexer will be used to index backend arrays, while the second one
is used to index loaded on-memory np.ndarray.
Parameters
----------
indexe... |
Decompose outer indexer to the successive two indexers where the first indexer will be used to index backend arrays while the second one is used to index the loaded on - memory np. ndarray. | def _decompose_outer_indexer(indexer, shape, indexing_support):
"""
Decompose outer indexer to the successive two indexers, where the
first indexer will be used to index backend arrays, while the second one
is used to index the loaded on-memory np.ndarray.
Parameters
----------
indexer: Vec... |
Return an identical vindex but slices are replaced by arrays | def _arrayize_vectorized_indexer(indexer, shape):
""" Return an identical vindex but slices are replaced by arrays """
slices = [v for v in indexer.tuple if isinstance(v, slice)]
if len(slices) == 0:
return indexer
arrays = [v for v in indexer.tuple if isinstance(v, np.ndarray)]
n_dim = arr... |
Create a dask array using the chunks hint for dimensions of size > 1. | def _dask_array_with_chunks_hint(array, chunks):
"""Create a dask array using the chunks hint for dimensions of size > 1."""
import dask.array as da
if len(chunks) < array.ndim:
raise ValueError('not enough chunks in hint')
new_chunks = []
for chunk, size in zip(chunks, array.shape):
... |
Create a mask for indexing with a fill - value. | def create_mask(indexer, shape, chunks_hint=None):
"""Create a mask for indexing with a fill-value.
Parameters
----------
indexer : ExplicitIndexer
Indexer with -1 in integer or ndarray value to indicate locations in
the result that should be masked.
shape : tuple
Shape of t... |
Convert masked indices in a flat array to the nearest unmasked index. | def _posify_mask_subindexer(index):
"""Convert masked indices in a flat array to the nearest unmasked index.
Parameters
----------
index : np.ndarray
One dimensional ndarray with dtype=int.
Returns
-------
np.ndarray
One dimensional ndarray with all values equal to -1 repla... |
Convert masked values ( - 1 ) in an indexer to nearest unmasked values. | def posify_mask_indexer(indexer):
"""Convert masked values (-1) in an indexer to nearest unmasked values.
This routine is useful for dask, where it can be much faster to index
adjacent points than arbitrary points from the end of an array.
Parameters
----------
indexer : ExplicitIndexer
... |
import seaborn and handle deprecation of apionly module | def import_seaborn():
'''import seaborn and handle deprecation of apionly module'''
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
try:
import seaborn.apionly as sns
if (w and issubclass(w[-1].category, UserWarning) and
... |
Build a discrete colormap and normalization of the data. | def _build_discrete_cmap(cmap, levels, extend, filled):
"""
Build a discrete colormap and normalization of the data.
"""
import matplotlib as mpl
if not filled:
# non-filled contour plots
extend = 'max'
if extend == 'both':
ext_n = 2
elif extend in ['min', 'max']:
... |
Use some heuristics to set good defaults for colorbar and range. | def _determine_cmap_params(plot_data, vmin=None, vmax=None, cmap=None,
center=None, robust=False, extend=None,
levels=None, filled=True, norm=None):
"""
Use some heuristics to set good defaults for colorbar and range.
Parameters
==========
plot_... |
Determine x and y labels for showing RGB images. | def _infer_xy_labels_3d(darray, x, y, rgb):
"""
Determine x and y labels for showing RGB images.
Attempts to infer which dimension is RGB/RGBA by size and order of dims.
"""
assert rgb is None or rgb != x
assert rgb is None or rgb != y
# Start by detecting and reporting invalid combination... |
Determine x and y labels. For use in _plot2d | def _infer_xy_labels(darray, x, y, imshow=False, rgb=None):
"""
Determine x and y labels. For use in _plot2d
darray must be a 2 dimensional data array, or 3d for imshow only.
"""
assert x is None or x != y
if imshow and darray.ndim == 3:
return _infer_xy_labels_3d(darray, x, y, rgb)
... |
Makes informative labels if variable metadata ( attrs ) follows CF conventions. | def label_from_attrs(da, extra=''):
''' Makes informative labels if variable metadata (attrs) follows
CF conventions. '''
if da.attrs.get('long_name'):
name = da.attrs['long_name']
elif da.attrs.get('standard_name'):
name = da.attrs['standard_name']
elif da.name is not None:
... |
Helper function which returns an array with the Intervals boundaries. | def _interval_to_bound_points(array):
"""
Helper function which returns an array
with the Intervals' boundaries.
"""
array_boundaries = np.array([x.left for x in array])
array_boundaries = np.concatenate(
(array_boundaries, np.array([array[-1].right])))
return array_boundaries |
Helper function to deal with a xarray consisting of pd. Intervals. Each interval is replaced with both boundaries. I. e. the length of xarray doubles. yarray is modified so it matches the new shape of xarray. | def _interval_to_double_bound_points(xarray, yarray):
"""
Helper function to deal with a xarray consisting of pd.Intervals. Each
interval is replaced with both boundaries. I.e. the length of xarray
doubles. yarray is modified so it matches the new shape of xarray.
"""
xarray1 = np.array([x.left... |
Helper function to replace the values of a coordinate array containing pd. Interval with their mid - points or - for pcolormesh - boundaries which increases length by 1. | def _resolve_intervals_2dplot(val, func_name):
"""
Helper function to replace the values of a coordinate array containing
pd.Interval with their mid-points or - for pcolormesh - boundaries which
increases length by 1.
"""
label_extra = ''
if _valid_other_type(val, [pd.Interval]):
if ... |
Do all elements of x have a type from types? | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) |
Is any dtype from numpy_types superior to the dtype of x? | def _valid_numpy_subdtype(x, numpy_types):
"""
Is any dtype from numpy_types superior to the dtype of x?
"""
# If any of the types given in numpy_types is understood as numpy.generic,
# all possible x will be considered valid. This is probably unwanted.
for t in numpy_types:
assert not ... |
Raise exception if there is anything in args that can t be plotted on an axis by matplotlib. | def _ensure_plottable(*args):
"""
Raise exception if there is anything in args that can't be plotted on an
axis by matplotlib.
"""
numpy_types = [np.floating, np.integer, np.timedelta64, np.datetime64]
other_types = [datetime]
try:
import cftime
cftime_datetime = [cftime.date... |
Update axes with provided parameters | def _update_axes(ax, xincrease, yincrease,
xscale=None, yscale=None,
xticks=None, yticks=None,
xlim=None, ylim=None):
"""
Update axes with provided parameters
"""
if xincrease is None:
pass
elif xincrease and ax.xaxis_inverted():
ax.... |
>>> _is_monotonic ( np. array ( [ 0 1 2 ] )) True >>> _is_monotonic ( np. array ( [ 2 1 0 ] )) True >>> _is_monotonic ( np. array ( [ 0 2 1 ] )) False | def _is_monotonic(coord, axis=0):
"""
>>> _is_monotonic(np.array([0, 1, 2]))
True
>>> _is_monotonic(np.array([2, 1, 0]))
True
>>> _is_monotonic(np.array([0, 2, 1]))
False
"""
if coord.shape[axis] < 3:
return True
else:
n = coord.shape[axis]
delta_pos = (co... |
>>> _infer_interval_breaks ( np. arange ( 5 )) array ( [ - 0. 5 0. 5 1. 5 2. 5 3. 5 4. 5 ] ) >>> _infer_interval_breaks ( [[ 0 1 ] [ 3 4 ]] axis = 1 ) array ( [[ - 0. 5 0. 5 1. 5 ] [ 2. 5 3. 5 4. 5 ]] ) | def _infer_interval_breaks(coord, axis=0, check_monotonic=False):
"""
>>> _infer_interval_breaks(np.arange(5))
array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])
>>> _infer_interval_breaks([[0, 1], [3, 4]], axis=1)
array([[-0.5, 0.5, 1.5],
[ 2.5, 3.5, 4.5]])
"""
coord = np.asarray(co... |
Parameters ========== func: plotting function kwargs: dict Dictionary with arguments that need to be parsed data: ndarray Data values | def _process_cmap_cbar_kwargs(func, kwargs, data):
"""
Parameters
==========
func : plotting function
kwargs : dict,
Dictionary with arguments that need to be parsed
data : ndarray,
Data values
Returns
=======
cmap_params
cbar_kwargs
"""
cmap = kwargs.p... |
Default plot of DataArray using matplotlib. pyplot. | def plot(darray, row=None, col=None, col_wrap=None, ax=None, hue=None,
rtol=0.01, subplot_kws=None, **kwargs):
"""
Default plot of DataArray using matplotlib.pyplot.
Calls xarray plotting function based on the dimensions of
darray.squeeze()
=============== ===========================
... |
Line plot of DataArray index against values | def line(darray, *args, **kwargs):
"""
Line plot of DataArray index against values
Wraps :func:`matplotlib:matplotlib.pyplot.plot`
Parameters
----------
darray : DataArray
Must be 1 dimensional
figsize : tuple, optional
A tuple (width, height) of the figure in inches.
... |
Step plot of DataArray index against values | def step(darray, *args, **kwargs):
"""
Step plot of DataArray index against values
Similar to :func:`matplotlib:matplotlib.pyplot.step`
Parameters
----------
where : {'pre', 'post', 'mid'}, optional, default 'pre'
Define where the steps should be placed:
- 'pre': The y value is... |
Histogram of DataArray | def hist(darray, figsize=None, size=None, aspect=None, ax=None, **kwargs):
"""
Histogram of DataArray
Wraps :func:`matplotlib:matplotlib.pyplot.hist`
Plots N dimensional arrays by first flattening the array.
Parameters
----------
darray : DataArray
Can be any dimension
figsize... |
Decorator for common 2d plotting logic | def _plot2d(plotfunc):
"""
Decorator for common 2d plotting logic
Also adds the 2d plot method to class _PlotMethods
"""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots
x : string, optional
Coordinate for ... |
Image plot of 2d DataArray using matplotlib. pyplot | def imshow(x, y, z, ax, **kwargs):
"""
Image plot of 2d DataArray using matplotlib.pyplot
Wraps :func:`matplotlib:matplotlib.pyplot.imshow`
While other plot methods require the DataArray to be strictly
two-dimensional, ``imshow`` also accepts a 3D array where some
dimension can be interpreted ... |
Contour plot of 2d DataArray | def contour(x, y, z, ax, **kwargs):
"""
Contour plot of 2d DataArray
Wraps :func:`matplotlib:matplotlib.pyplot.contour`
"""
primitive = ax.contour(x, y, z, **kwargs)
return primitive |
Filled contour plot of 2d DataArray | def contourf(x, y, z, ax, **kwargs):
"""
Filled contour plot of 2d DataArray
Wraps :func:`matplotlib:matplotlib.pyplot.contourf`
"""
primitive = ax.contourf(x, y, z, **kwargs)
return primitive |
Pseudocolor plot of 2d DataArray | def pcolormesh(x, y, z, ax, infer_intervals=None, **kwargs):
"""
Pseudocolor plot of 2d DataArray
Wraps :func:`matplotlib:matplotlib.pyplot.pcolormesh`
"""
# decide on a default for infer_intervals (GH781)
x = np.asarray(x)
if infer_intervals is None:
if hasattr(ax, 'projection'):
... |
Determine the dask scheduler that is being used. | def _get_scheduler(get=None, collection=None):
"""Determine the dask scheduler that is being used.
None is returned if no dask scheduler is active.
See also
--------
dask.base.get_scheduler
"""
try:
# dask 0.18.1 and later
from dask.base import get_scheduler
actual_... |
Acquire a lock possibly in a non - blocking fashion. | def acquire(lock, blocking=True):
"""Acquire a lock, possibly in a non-blocking fashion.
Includes backwards compatibility hacks for old versions of Python, dask
and dask-distributed.
"""
if blocking:
# no arguments needed
return lock.acquire()
elif DistributedLock is not None an... |
Combine a sequence of locks into a single lock. | def combine_locks(locks):
"""Combine a sequence of locks into a single lock."""
all_locks = []
for lock in locks:
if isinstance(lock, CombinedLock):
all_locks.extend(lock.locks)
elif lock is not None:
all_locks.append(lock)
num_locks = len(all_locks)
if num_l... |
Get a list of dimensions to squeeze out. | def get_squeeze_dims(xarray_obj,
dim: Union[Hashable, Iterable[Hashable], None] = None,
axis: Union[int, Iterable[int], None] = None
) -> List[Hashable]:
"""Get a list of dimensions to squeeze out.
"""
if dim is not None and axis is not None:
... |
Return a new object with the same shape and type as a given object. | def full_like(other, fill_value, dtype: Union[str, np.dtype, None] = None):
"""Return a new object with the same shape and type as a given object.
Parameters
----------
other : DataArray, Dataset, or Variable
The reference object in input
fill_value : scalar
Value to fill the new ob... |
Inner function of full_like where other must be a variable | def _full_like_variable(other, fill_value,
dtype: Union[str, np.dtype, None] = None):
"""Inner function of full_like, where other must be a variable
"""
from .variable import Variable
if isinstance(other.data, dask_array_type):
import dask.array
if dtype is None:... |
Shorthand for full_like ( other 0 dtype ) | def zeros_like(other, dtype: Union[str, np.dtype, None] = None):
"""Shorthand for full_like(other, 0, dtype)
"""
return full_like(other, 0, dtype) |
Shorthand for full_like ( other 1 dtype ) | def ones_like(other, dtype: Union[str, np.dtype, None] = None):
"""Shorthand for full_like(other, 1, dtype)
"""
return full_like(other, 1, dtype) |
Check if a dtype is a subclass of the numpy datetime types | def is_np_datetime_like(dtype: Union[str, np.dtype]) -> bool:
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) |
Check if an array contains cftime. datetime objects | def _contains_cftime_datetimes(array) -> bool:
"""Check if an array contains cftime.datetime objects
"""
try:
from cftime import datetime as cftime_datetime
except ImportError:
return False
else:
if array.dtype == np.dtype('O') and array.size > 0:
sample = array.r... |
Return axis number ( s ) corresponding to dimension ( s ) in this array. | def get_axis_num(self, dim: Union[Hashable, Iterable[Hashable]]
) -> Union[int, Tuple[int, ...]]:
"""Return axis number(s) corresponding to dimension(s) in this array.
Parameters
----------
dim : str or iterable of str
Dimension name(s) for which to look... |
Ordered mapping from dimension names to lengths. | def sizes(self: Any) -> Mapping[Hashable, int]:
"""Ordered mapping from dimension names to lengths.
Immutable.
See also
--------
Dataset.sizes
"""
return Frozen(OrderedDict(zip(self.dims, self.shape))) |
Provide method for the key - autocompletions in IPython. See http:// ipython. readthedocs. io/ en/ stable/ config/ integrating. html#tab - completion For the details. | def _ipython_key_completions_(self) -> List[str]:
"""Provide method for the key-autocompletions in IPython.
See http://ipython.readthedocs.io/en/stable/config/integrating.html#tab-completion
For the details.
""" # noqa
item_lists = [item
for sublist in self... |
Return a new object with squeezed data. | def squeeze(self, dim: Union[Hashable, Iterable[Hashable], None] = None,
drop: bool = False,
axis: Union[int, Iterable[int], None] = None):
"""Return a new object with squeezed data.
Parameters
----------
dim : None or Hashable or iterable of Hashable, op... |
Get an index for a dimension with fall - back to a default RangeIndex | def get_index(self, key: Hashable) -> pd.Index:
"""Get an index for a dimension, with fall-back to a default RangeIndex
"""
if key not in self.dims:
raise KeyError(key)
try:
return self.indexes[key]
except KeyError:
# need to ensure dtype=int6... |
Assign new coordinates to this object. | def assign_coords(self, **kwargs):
"""Assign new coordinates to this object.
Returns a new object with all the original data in addition to the new
coordinates.
Parameters
----------
kwargs : keyword, value pairs
keywords are the variables names. If the valu... |
Assign new attrs to this object. | def assign_attrs(self, *args, **kwargs):
"""Assign new attrs to this object.
Returns a new object equivalent to self.attrs.update(*args, **kwargs).
Parameters
----------
args : positional arguments passed into ``attrs.update``.
kwargs : keyword arguments passed into ``a... |
Apply func ( self * args ** kwargs ) | def pipe(self, func: Union[Callable[..., T], Tuple[Callable[..., T], str]],
*args, **kwargs) -> T:
"""
Apply func(self, *args, **kwargs)
This method replicates the pandas method of the same name.
Parameters
----------
func : function
function to... |
Returns a GroupBy object for performing grouped operations. | def groupby(self, group, squeeze: bool = True):
"""Returns a GroupBy object for performing grouped operations.
Parameters
----------
group : str, DataArray or IndexVariable
Array whose unique values should be used to group this array. If a
string, must be the nam... |
Returns a GroupBy object for performing grouped operations. | def groupby_bins(self, group, bins, right: bool = True, labels=None,
precision: int = 3, include_lowest: bool = False,
squeeze: bool = True):
"""Returns a GroupBy object for performing grouped operations.
Rather than using all unique values of `group`, the valu... |
Rolling window object. | def rolling(self, dim: Optional[Mapping[Hashable, int]] = None,
min_periods: Optional[int] = None, center: bool = False,
**dim_kwargs: int):
"""
Rolling window object.
Parameters
----------
dim: dict, optional
Mapping from the dimensio... |
Coarsen object. | def coarsen(self, dim: Optional[Mapping[Hashable, int]] = None,
boundary: str = 'exact',
side: Union[str, Mapping[Hashable, str]] = 'left',
coord_func: str = 'mean',
**dim_kwargs: int):
"""
Coarsen object.
Parameters
------... |
Returns a Resample object for performing resampling operations. | def resample(self, indexer: Optional[Mapping[Hashable, str]] = None,
skipna=None, closed: Optional[str] = None,
label: Optional[str] = None,
base: int = 0, keep_attrs: Optional[bool] = None,
loffset=None,
**indexer_kwargs: str):
... |
Filter elements from this object according to a condition. | def where(self, cond, other=dtypes.NA, drop: bool = False):
"""Filter elements from this object according to a condition.
This operation follows the normal broadcasting and alignment rules that
xarray uses for binary arithmetic.
Parameters
----------
cond : DataArray or... |
Close any files linked to this object | def close(self: Any) -> None:
"""Close any files linked to this object
"""
if self._file_obj is not None:
self._file_obj.close()
self._file_obj = None |
Tests each value in the array for whether it is in test elements. | def isin(self, test_elements):
"""Tests each value in the array for whether it is in test elements.
Parameters
----------
test_elements : array_like
The values against which to test each value of `element`.
This argument is flattened if an array or array_like.
... |
Compare docker versions | def compare_version(v1, v2):
"""Compare docker versions
>>> v1 = '1.9'
>>> v2 = '1.10'
>>> compare_version(v1, v2)
1
>>> compare_version(v2, v1)
-1
>>> compare_version(v2, v2)
0
"""
s1 = StrictVersion(v1)
s2 = StrictVersion(v2)
if s1 == s2:
return 0
elif ... |
Convert a UTC datetime to a Unix timestamp | def datetime_to_timestamp(dt):
"""Convert a UTC datetime to a Unix timestamp"""
delta = dt - datetime.utcfromtimestamp(0)
return delta.seconds + delta.days * 24 * 3600 |
Reads a line - separated environment file. The format of each line should be key = value. | def parse_env_file(env_file):
"""
Reads a line-separated environment file.
The format of each line should be "key=value".
"""
environment = {}
with open(env_file, 'r') as f:
for line in f:
if line[0] == '#':
continue
line = line.strip()
... |
Configure a plugin. | def configure_plugin(self, name, options):
"""
Configure a plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
options (dict): A key-value mapping of options
... |
Create a new plugin. | def create_plugin(self, name, plugin_data_dir, gzip=False):
"""
Create a new plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
plugin_data_dir (string): Path to the plu... |
Disable an installed plugin. | def disable_plugin(self, name):
"""
Disable an installed plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
Returns:
``True`` if successful
"""
... |
Enable an installed plugin. | def enable_plugin(self, name, timeout=0):
"""
Enable an installed plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
timeout (int): Operation timeout (in seconds). Defau... |
Retrieve plugin metadata. | def inspect_plugin(self, name):
"""
Retrieve plugin metadata.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
Returns:
A dict containing plugin info
"""
... |
Retrieve a list of installed plugins. | def plugins(self):
"""
Retrieve a list of installed plugins.
Returns:
A list of dicts, one per plugin
"""
url = self._url('/plugins')
return self._result(self._get(url), True) |
Retrieve list of privileges to be granted to a plugin. | def plugin_privileges(self, name):
"""
Retrieve list of privileges to be granted to a plugin.
Args:
name (string): Name of the remote plugin to examine. The
``:latest`` tag is optional, and is the default if omitted.
Returns:
... |
Push a plugin to the registry. | def push_plugin(self, name):
"""
Push a plugin to the registry.
Args:
name (string): Name of the plugin to upload. The ``:latest``
tag is optional, and is the default if omitted.
Returns:
``True`` if successful
"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.