Instruction:
Explain what the following Python 3 code does
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], [0, 1]]`, except this
        method does not require knowing the order of each array's dimensions.

        Parameters
        ----------
        dim : str or DataArray or pandas.Index or other list-like object, optional
            Name of the dimension to concatenate along. If dim is provided as a
            string, it must be a new dimension name, in which case it is added
            along axis=0. If dim is provided as a DataArray or Index or
            list-like object, its name, which must not be present in the
            dataset, is used as the dimension to concatenate along and the
            values are added as a coordinate.
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by array-like objects. All indexers must be the same length and
            1 dimensional.

        Returns
        -------
        obj : Dataset
            A new Dataset with the same contents as this dataset, except each
            array and dimension is indexed by the appropriate indexers. With
            pointwise indexing, the new Dataset will always be a copy of the
            original.

        See Also
        --------
        Dataset.sel
        Dataset.isel
        Dataset.sel_points
        DataArray.isel_points
        """  # noqa
        warnings.warn('Dataset.isel_points is deprecated: use Dataset.isel()'
                      'instead.', DeprecationWarning, stacklevel=2)

        indexer_dims = set(indexers)

        def take(variable, slices):
            # Note: remove helper function when once when numpy
            # supports vindex https://github.com/numpy/numpy/pull/6075
            if hasattr(variable.data, 'vindex'):
                # Special case for dask backed arrays to use vectorised list
                # indexing
                sel = variable.data.vindex[slices]
            else:
                # Otherwise assume backend is numpy array with 'fancy' indexing
                sel = variable.data[slices]
            return sel

        def relevant_keys(mapping):
            return [k for k, v in mapping.items()
                    if any(d in indexer_dims for d in v.dims)]

        coords = relevant_keys(self.coords)
        indexers = [(k, np.asarray(v))  # type: ignore
                    for k, v in indexers.items()]
        indexers_dict = dict(indexers)
        non_indexed_dims = set(self.dims) - indexer_dims
        non_indexed_coords = set(self.coords) - set(coords)

        # All the indexers should be iterables
        # Check that indexers are valid dims, integers, and 1D
        for k, v in indexers:
            if k not in self.dims:
                raise ValueError("dimension %s does not exist" % k)
            if v.dtype.kind != 'i':  # type: ignore
                raise TypeError('Indexers must be integers')
            if v.ndim != 1:  # type: ignore
                raise ValueError('Indexers must be 1 dimensional')

        # all the indexers should have the same length
        lengths = set(len(v) for k, v in indexers)
        if len(lengths) > 1:
            raise ValueError('All indexers must be the same length')

        # Existing dimensions are not valid choices for the dim argument
        if isinstance(dim, str):
            if dim in self.dims:
                # dim is an invalid string
                raise ValueError('Existing dimension names are not valid '
                                 'choices for the dim argument in sel_points')

        elif hasattr(dim, 'dims'):
            # dim is a DataArray or Coordinate
            if dim.name in self.dims:
                # dim already exists
                raise ValueError('Existing dimensions are not valid choices '
                                 'for the dim argument in sel_points')

        # Set the new dim_name, and optionally the new dim coordinate
        # dim is either an array-like or a string
        if not utils.is_scalar(dim):
            # dim is array like get name or assign 'points', get as variable
            dim_name = 'points' if not hasattr(dim, 'name') else dim.name
            dim_coord = as_variable(dim, name=dim_name)
        else:
            # dim is a string
            dim_name = dim
            dim_coord = None  # type: ignore

        reordered = self.transpose(
            *(list(indexer_dims) + list(non_indexed_dims)))

        variables = OrderedDict()  # type: ignore

        for name, var in reordered.variables.items():
            if name in indexers_dict or any(
                    d in indexer_dims for d in var.dims):
                # slice if var is an indexer or depends on an indexed dim
                slc = [indexers_dict[k]
                       if k in indexers_dict
                       else slice(None) for k in var.dims]

                var_dims = [dim_name] + [d for d in var.dims
                                         if d in non_indexed_dims]
                selection = take(var, tuple(slc))
                var_subset = type(var)(var_dims, selection, var.attrs)
                variables[name] = var_subset
            else:
                # If not indexed just add it back to variables or coordinates
                variables[name] = var

        coord_names = (set(coords) & set(variables)) | non_indexed_coords

        dset = self._replace_vars_and_dims(variables, coord_names=coord_names)
        # Add the dim coord to the new dset. Must be done after creation
        # because_replace_vars_and_dims can only access existing coords,
        # not add new ones
        if dim_coord is not None:
            dset.coords[dim_name] = dim_coord
        return dset

Response:
Returns a new Dataset with each array indexed pointwise along the
            specified dimension.


Instruction:
Create a Python 3 function for
returning a new Dataset with each array indexed pointwise by tick labels along the specified dimension.

Response:
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 instead of integers.

        In contrast to `Dataset.sel`, this method selects points along the
        diagonal of multi-dimensional arrays, not the intersection.

        Parameters
        ----------
        dim : str or DataArray or pandas.Index or other list-like object, optional
            Name of the dimension to concatenate along. If dim is provided as a
            string, it must be a new dimension name, in which case it is added
            along axis=0. If dim is provided as a DataArray or Index or
            list-like object, its name, which must not be present in the
            dataset, is used as the dimension to concatenate along and the
            values are added as a coordinate.
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for inexact matches (requires pandas>=0.16):

            * None (default): only exact matches
            * pad / ffill: propagate last valid index value forward
            * backfill / bfill: propagate next valid index value backward
            * nearest: use nearest valid index value
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Requires pandas>=0.17.
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by array-like objects. All indexers must be the same length and
            1 dimensional.

        Returns
        -------
        obj : Dataset
            A new Dataset with the same contents as this dataset, except each
            array and dimension is indexed by the appropriate indexers. With
            pointwise indexing, the new Dataset will always be a copy of the
            original.

        See Also
        --------
        Dataset.sel
        Dataset.isel
        Dataset.isel_points
        DataArray.sel_points
        """  # noqa
        warnings.warn('Dataset.sel_points is deprecated: use Dataset.sel()'
                      'instead.', DeprecationWarning, stacklevel=2)

        pos_indexers, _ = indexing.remap_label_indexers(
            self, indexers, method=method, tolerance=tolerance
        )
        return self.isel_points(dim=dim, **pos_indexers)


Instruction:
Make a summary of the following Python 3 code
def reindex_like(self, other, method=None, tolerance=None, copy=True):
        indexers = alignment.reindex_like_indexers(self, other)
        return self.reindex(indexers=indexers, method=method, copy=copy,
                            tolerance=tolerance)

Response: Conform this object onto the indexes of another object filling missing values with NaN.


Instruction:
Given the following Python 3 function, write the documentation
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 given by dimension names and values given by
            arrays of coordinates tick labels. Any mis-matched coordinate
            values will be filled in with NaN, and any mis-matched dimension
            names will simply be ignored.
            One of indexers or indexers_kwargs must be provided.
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for filling index values in ``indexers`` not found in
            this dataset:

            * None (default): don't fill gaps
            * pad / ffill: propagate last valid index value forward
            * backfill / bfill: propagate next valid index value backward
            * nearest: use nearest valid index value (requires pandas>=0.16)
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Requires pandas>=0.17.
        copy : bool, optional
            If ``copy=True``, data in the return value is always copied. If
            ``copy=False`` and reindexing is unnecessary, or can be performed
            with only slice operations, then the output may share memory with
            the input. In either case, a new xarray object is always returned.
        **indexers_kwarg : {dim: indexer, ...}, optional
            Keyword arguments in the same form as ``indexers``.
            One of indexers or indexers_kwargs must be provided.

        Returns
        -------
        reindexed : Dataset
            Another dataset, with this dataset's data but replaced coordinates.

        See Also
        --------
        Dataset.reindex_like
        align
        pandas.Index.get_indexer
        """
        indexers = utils.either_dict_or_kwargs(indexers, indexers_kwargs,
                                               'reindex')

        bad_dims = [d for d in indexers if d not in self.dims]
        if bad_dims:
            raise ValueError('invalid reindex dimensions: %s' % bad_dims)

        variables, indexes = alignment.reindex_variables(
            self.variables, self.sizes, self.indexes, indexers, method,
            tolerance, copy=copy)
        coord_names = set(self._coord_names)
        coord_names.update(indexers)
        return self._replace_with_new_dims(
            variables, coord_names, indexes=indexes)

Response: Conform this object onto a new set of indexes.


Instruction:
Can you generate the documentation for the following Python 3 function
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 coordinate can be a scalar, array-like or DataArray.
            If DataArrays are passed as new coordates, their dimensions are
            used for the broadcasting.
        method: string, optional.
            {'linear', 'nearest'} for multidimensional array,
            {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'}
            for 1-dimensional array. 'linear' is used by default.
        assume_sorted: boolean, optional
            If False, values of coordinates that are interpolated over can be
            in any order and they are sorted first. If True, interpolated
            coordinates are assumed to be an array of monotonically increasing
            values.
        kwargs: dictionary, optional
            Additional keyword passed to scipy's interpolator.
        **coords_kwarg : {dim: coordinate, ...}, optional
            The keyword arguments form of ``coords``.
            One of coords or coords_kwargs must be provided.

        Returns
        -------
        interpolated: xr.Dataset
            New dataset on the new coordinates.

        Notes
        -----
        scipy is required.

        See Also
        --------
        scipy.interpolate.interp1d
        scipy.interpolate.interpn
        """
        from . import missing

        coords = either_dict_or_kwargs(coords, coords_kwargs, 'interp')
        indexers = OrderedDict(self._validate_indexers(coords))

        obj = self if assume_sorted else self.sortby([k for k in coords])

        def maybe_variable(obj, k):
            # workaround to get variable for dimension without coordinate.
            try:
                return obj._variables[k]
            except KeyError:
                return as_variable((k, range(obj.dims[k])))

        def _validate_interp_indexer(x, new_x):
            # In the case of datetimes, the restrictions placed on indexers
            # used with interp are stronger than those which are placed on
            # isel, so we need an additional check after _validate_indexers.
            if (_contains_datetime_like_objects(x) and
                    not _contains_datetime_like_objects(new_x)):
                raise TypeError('When interpolating over a datetime-like '
                                'coordinate, the coordinates to '
                                'interpolate to must be either datetime '
                                'strings or datetimes. '
                                'Instead got\n{}'.format(new_x))
            else:
                return (x, new_x)

        variables = OrderedDict()
        for name, var in obj._variables.items():
            if name not in indexers:
                if var.dtype.kind in 'uifc':
                    var_indexers = {
                        k: _validate_interp_indexer(maybe_variable(obj, k), v)
                        for k, v in indexers.items()
                        if k in var.dims
                    }
                    variables[name] = missing.interp(
                        var, var_indexers, method, **kwargs)
                elif all(d not in indexers for d in var.dims):
                    # keep unrelated object array
                    variables[name] = var

        coord_names = set(variables).intersection(obj._coord_names)
        indexes = OrderedDict(
            (k, v) for k, v in obj.indexes.items() if k not in indexers)
        selected = self._replace_with_new_dims(
            variables.copy(), coord_names, indexes=indexes)

        # attach indexer as coordinate
        variables.update(indexers)
        indexes.update(
            (k, v.to_index()) for k, v in indexers.items() if v.dims == (k,)
        )

        # Extract coordinates from indexers
        coord_vars, new_indexes = (
            selected._get_indexers_coords_and_indexes(coords))
        variables.update(coord_vars)
        indexes.update(new_indexes)

        coord_names = (set(variables)
                       .intersection(obj._coord_names)
                       .union(coord_vars))
        return self._replace_with_new_dims(
            variables, coord_names, indexes=indexes)

Response: Interpolate a multidimensional array over a set of coordinates.


Instruction:
Implement a function in Python 3 to
interpolate this object onto the coordinates of another object.

Response:
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 with an 'indexes' attribute giving a mapping from dimension
            names to an 1d array-like, which provides coordinates upon
            which to index the variables in this dataset.
        method: string, optional.
            {'linear', 'nearest'} for multidimensional array,
            {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'}
            for 1-dimensional array. 'linear' is used by default.
        assume_sorted: boolean, optional
            If False, values of coordinates that are interpolated over can be
            in any order and they are sorted first. If True, interpolated
            coordinates are assumed to be an array of monotonically increasing
            values.
        kwargs: dictionary, optional
            Additional keyword passed to scipy's interpolator.

        Returns
        -------
        interpolated: xr.Dataset
            Another dataset by interpolating this dataset's data along the
            coordinates of the other object.

        Notes
        -----
        scipy is required.
        If the dataset has object-type coordinates, reindex is used for these
        coordinates instead of the interpolation.

        See Also
        --------
        Dataset.interp
        Dataset.reindex_like
        """
        coords = alignment.reindex_like_indexers(self, other)

        numeric_coords = OrderedDict()
        object_coords = OrderedDict()
        for k, v in coords.items():
            if v.dtype.kind in 'uifcMm':
                numeric_coords[k] = v
            else:
                object_coords[k] = v

        ds = self
        if object_coords:
            # We do not support interpolation along object coordinate.
            # reindex instead.
            ds = self.reindex(object_coords)
        return ds.interp(numeric_coords, method, assume_sorted, kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def rename(self, name_dict=None, inplace=None, **names):
        # TODO: add separate rename_vars and rename_dims methods.
        inplace = _check_inplace(inplace)
        name_dict = either_dict_or_kwargs(name_dict, names, 'rename')
        for k, v in name_dict.items():
            if k not in self and k not in self.dims:
                raise ValueError("cannot rename %r because it is not a "
                                 "variable or dimension in this dataset" % k)

        variables, coord_names, dims, indexes = self._rename_all(
            name_dict=name_dict, dim_dict=name_dict)
        return self._replace(variables, coord_names, dims=dims,
                             indexes=indexes, inplace=inplace)

Response: Returns a new Dataset object with renamed variables and dimensions.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def swap_dims(self, dims_dict, inplace=None):
        # TODO: deprecate this method in favor of a (less confusing)
        # rename_dims() method that only renames dimensions.
        inplace = _check_inplace(inplace)
        for k, v in dims_dict.items():
            if k not in self.dims:
                raise ValueError('cannot swap from dimension %r because it is '
                                 'not an existing dimension' % k)
            if self.variables[v].dims != (k,):
                raise ValueError('replacement dimension %r is not a 1D '
                                 'variable along the old dimension %r'
                                 % (v, k))

        result_dims = set(dims_dict.get(dim, dim) for dim in self.dims)

        coord_names = self._coord_names.copy()
        coord_names.update(dims_dict.values())

        variables = OrderedDict()
        indexes = OrderedDict()
        for k, v in self.variables.items():
            dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
            if k in result_dims:
                var = v.to_index_variable()
                if k in self.indexes:
                    indexes[k] = self.indexes[k]
                else:
                    indexes[k] = var.to_index()
            else:
                var = v.to_base_variable()
            var.dims = dims
            variables[k] = var

        return self._replace_with_new_dims(variables, coord_names,
                                           indexes=indexes, inplace=inplace)

Response: Returns a new Dataset containing swapped dimensions.


Instruction:
Implement a function in Python 3 to
return a new object with an additional dimension inserted at the corresponding position in the array.

Response:
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.

        Parameters
        ----------
        dim : str, sequence of str, dict, or None
            Dimensions to include on the new variable.
            If provided as str or sequence of str, then dimensions are inserted
            with length 1. If provided as a dict, then the keys are the new
            dimensions and the values are either integers (giving the length of
            the new dimensions) or sequence/ndarray (giving the coordinates of
            the new dimensions). **WARNING** for python 3.5, if ``dim`` is
            dict-like, then it must be an ``OrderedDict``. This is to ensure
            that the order in which the dims are given is maintained.
        axis : integer, list (or tuple) of integers, or None
            Axis position(s) where new axis is to be inserted (position(s) on
            the result array). If a list (or tuple) of integers is passed,
            multiple axes are inserted. In this case, dim arguments should be
            same length list. If axis=None is passed, all the axes will be
            inserted to the start of the result array.
        **dim_kwargs : int or sequence/ndarray
            The keywords are arbitrary dimensions being inserted and the values
            are either the lengths of the new dims (if int is given), or their
            coordinates. Note, this is an alternative to passing a dict to the
            dim kwarg and will only be used if dim is None. **WARNING** for
            python 3.5 ``dim_kwargs`` is not available.

        Returns
        -------
        expanded : same type as caller
            This object, but with an additional dimension(s).
        """
        if isinstance(dim, int):
            raise TypeError('dim should be str or sequence of strs or dict')
        elif isinstance(dim, str):
            dim = OrderedDict(((dim, 1),))
        elif isinstance(dim, (list, tuple)):
            if len(dim) != len(set(dim)):
                raise ValueError('dims should not contain duplicate values.')
            dim = OrderedDict(((d, 1) for d in dim))

        # TODO: get rid of the below code block when python 3.5 is no longer
        #   supported.
        python36_plus = sys.version_info[0] == 3 and sys.version_info[1] > 5
        not_ordereddict = dim is not None and not isinstance(dim, OrderedDict)
        if not python36_plus and not_ordereddict:
            raise TypeError("dim must be an OrderedDict for python <3.6")
        elif not python36_plus and dim_kwargs:
            raise ValueError("dim_kwargs isn't available for python <3.6")

        dim = either_dict_or_kwargs(dim, dim_kwargs, 'expand_dims')

        if axis is not None and not isinstance(axis, (list, tuple)):
            axis = [axis]

        if axis is None:
            axis = list(range(len(dim)))

        if len(dim) != len(axis):
            raise ValueError('lengths of dim and axis should be identical.')
        for d in dim:
            if d in self.dims:
                raise ValueError(
                    'Dimension {dim} already exists.'.format(dim=d))
            if (d in self._variables and
                    not utils.is_scalar(self._variables[d])):
                raise ValueError(
                    '{dim} already exists as coordinate or'
                    ' variable name.'.format(dim=d))

        variables = OrderedDict()
        coord_names = self._coord_names.copy()
        # If dim is a dict, then ensure that the values are either integers
        # or iterables.
        for k, v in dim.items():
            if hasattr(v, "__iter__"):
                # If the value for the new dimension is an iterable, then
                # save the coordinates to the variables dict, and set the
                # value within the dim dict to the length of the iterable
                # for later use.
                variables[k] = xr.IndexVariable((k,), v)
                coord_names.add(k)
                dim[k] = variables[k].size
            elif isinstance(v, int):
                pass  # Do nothing if the dimensions value is just an int
            else:
                raise TypeError('The value of new dimension {k} must be '
                                'an iterable or an int'.format(k=k))

        for k, v in self._variables.items():
            if k not in dim:
                if k in coord_names:  # Do not change coordinates
                    variables[k] = v
                else:
                    result_ndim = len(v.dims) + len(axis)
                    for a in axis:
                        if a < -result_ndim or result_ndim - 1 < a:
                            raise IndexError(
                                'Axis {a} is out of bounds of the expanded'
                                ' dimension size {dim}.'.format(
                                    a=a, v=k, dim=result_ndim))

                    axis_pos = [a if a >= 0 else result_ndim + a
                                for a in axis]
                    if len(axis_pos) != len(set(axis_pos)):
                        raise ValueError('axis should not contain duplicate'
                                         ' values.')
                    # We need to sort them to make sure `axis` equals to the
                    # axis positions of the result array.
                    zip_axis_dim = sorted(zip(axis_pos, dim.items()))

                    all_dims = list(zip(v.dims, v.shape))
                    for d, c in zip_axis_dim:
                        all_dims.insert(d, c)
                    all_dims = OrderedDict(all_dims)

                    variables[k] = v.set_dims(all_dims)
            else:
                # If dims includes a label of a non-dimension coordinate,
                # it will be promoted to a 1D coordinate with a single value.
                variables[k] = v.set_dims(k)

        new_dims = self._dims.copy()
        new_dims.update(dim)

        return self._replace_vars_and_dims(
            variables, dims=new_dims, coord_names=coord_names)


Instruction:
Make a summary of the following Python 3 code
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 dimensions and values given
            by (lists of) the names of existing coordinates or variables to set
            as new (multi-)index.
        append : bool, optional
            If True, append the supplied index(es) to the existing index(es).
            Otherwise replace the existing index(es) (default).
        inplace : bool, optional
            If True, set new index(es) in-place. Otherwise, return a new
            Dataset object.
        **indexes_kwargs: optional
            The keyword arguments form of ``indexes``.
            One of indexes or indexes_kwargs must be provided.

        Returns
        -------
        obj : Dataset
            Another dataset, with this dataset's data but replaced coordinates.

        See Also
        --------
        Dataset.reset_index
        Dataset.swap_dims
        """
        inplace = _check_inplace(inplace)
        indexes = either_dict_or_kwargs(indexes, indexes_kwargs, 'set_index')
        variables, coord_names = merge_indexes(indexes, self._variables,
                                               self._coord_names,
                                               append=append)
        return self._replace_vars_and_dims(variables, coord_names=coord_names,
                                           inplace=inplace)

Response: Set the index of the data for the given locations.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def reset_index(self, dims_or_levels, drop=False, inplace=None):
        inplace = _check_inplace(inplace)
        variables, coord_names = split_indexes(dims_or_levels, self._variables,
                                               self._coord_names,
                                               self._level_coords, drop=drop)
        return self._replace_vars_and_dims(variables, coord_names=coord_names,
                                           inplace=inplace)

Response: Reset the index of the specified dimension or multi - index levels.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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 representing new level orders. Every given dimension
            must have a multi-index.
        inplace : bool, optional
            If True, modify the dataset in-place. Otherwise, return a new
            DataArray object.
        **dim_order_kwargs: optional
            The keyword arguments form of ``dim_order``.
            One of dim_order or dim_order_kwargs must be provided.

        Returns
        -------
        obj : Dataset
            Another dataset, with this dataset's data but replaced
            coordinates.
        """
        inplace = _check_inplace(inplace)
        dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs,
                                          'reorder_levels')
        replace_variables = {}
        for dim, order in dim_order.items():
            coord = self._variables[dim]
            index = coord.to_index()
            if not isinstance(index, pd.MultiIndex):
                raise ValueError("coordinate %r has no MultiIndex" % dim)
            replace_variables[dim] = IndexVariable(coord.dims,
                                                   index.reorder_levels(order))
        variables = self._variables.copy()
        variables.update(replace_variables)
        return self._replace_vars_and_dims(variables, inplace=inplace)

Response: Rearrange index levels using input order.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update(self, other, inplace=None):
        inplace = _check_inplace(inplace, default=True)
        variables, coord_names, dims = dataset_update_method(self, other)

        return self._replace_vars_and_dims(variables, coord_names, dims,
                                           inplace=inplace)

Response: Update this dataset s variables with those from another dataset.


Instruction:
How would you code a function in Python 3 to
merge two set of exception - related datasets into a single dataset.

Response:
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 dataset. Variables with
        the same name are checked for conflicts via the equals or identical
        methods.

        Parameters
        ----------
        other : Dataset or castable to Dataset
            Dataset or variables to merge with this dataset.
        inplace : bool, optional
            If True, merge the other dataset into this dataset in-place.
            Otherwise, return a new dataset object.
        overwrite_vars : str or sequence, optional
            If provided, update variables of these name(s) without checking for
            conflicts in this dataset.
        compat : {'broadcast_equals', 'equals', 'identical',
                  'no_conflicts'}, optional
            String indicating how to compare variables of the same name for
            potential conflicts:
            - 'broadcast_equals': all values must be equal when variables are
              broadcast against each other to ensure common dimensions.
            - 'equals': all values and dimensions must be the same.
            - 'identical': all values, dimensions and attributes must be the
              same.
            - 'no_conflicts': only values which are not null in both datasets
              must be equal. The returned dataset then contains the combination
              of all non-null values.
        join : {'outer', 'inner', 'left', 'right', 'exact'}, optional
            Method for joining ``self`` and ``other`` along shared dimensions:

            - 'outer': use the union of the indexes
            - 'inner': use the intersection of the indexes
            - 'left': use indexes from ``self``
            - 'right': use indexes from ``other``
            - 'exact': error instead of aligning non-equal indexes

        Returns
        -------
        merged : Dataset
            Merged dataset.

        Raises
        ------
        MergeError
            If any variables conflict (see ``compat``).
        """
        inplace = _check_inplace(inplace)
        variables, coord_names, dims = dataset_merge_method(
            self, other, overwrite_vars=overwrite_vars, compat=compat,
            join=join)

        return self._replace_vars_and_dims(variables, coord_names, dims,
                                           inplace=inplace)


Instruction:
How would you implement a function in Python 3 that
drops variables or index labels from this dataset.

Response:
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 labels. By default (if
            ``dim is None``), drops variables rather than index labels.

        Returns
        -------
        dropped : Dataset
        """
        if utils.is_scalar(labels):
            labels = [labels]
        if dim is None:
            return self._drop_vars(labels)
        else:
            try:
                index = self.indexes[dim]
            except KeyError:
                raise ValueError(
                    'dimension %r does not have coordinate labels' % dim)
            new_index = index.drop(labels)
            return self.loc[{dim: new_index}]


Instruction:
Given the following Python 3 function, write the documentation
def drop_dims(self, drop_dims):
        if utils.is_scalar(drop_dims):
            drop_dims = [drop_dims]

        missing_dimensions = [d for d in drop_dims if d not in self.dims]
        if missing_dimensions:
            raise ValueError('Dataset does not contain the dimensions: %s'
                             % missing_dimensions)

        drop_vars = set(k for k, v in self._variables.items()
                        for d in v.dims if d in drop_dims)

        variables = OrderedDict((k, v) for k, v in self._variables.items()
                                if k not in drop_vars)
        coord_names = set(k for k in self._coord_names if k in variables)

        return self._replace_with_new_dims(variables, coord_names)

Response: Drop dimensions and associated variables from this dataset.


Instruction:
Create a Python 3 function to
return a new Dataset object with all array dimensions transposed.

Response:
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, optional
            By default, reverse the dimensions on each array. Otherwise,
            reorder the dimensions to this order.

        Returns
        -------
        transposed : Dataset
            Each array in the dataset (including) coordinates will be
            transposed to the given order.

        Notes
        -----
        This operation returns a view of each array's data. It is
        lazy for dask-backed DataArrays but not for numpy-backed DataArrays
        -- the data will be fully loaded into memory.

        See Also
        --------
        numpy.transpose
        DataArray.transpose
        """
        if dims:
            if set(dims) ^ set(self.dims):
                raise ValueError('arguments to transpose (%s) must be '
                                 'permuted dataset dimensions (%s)'
                                 % (dims, tuple(self.dims)))
        ds = self.copy()
        for name, var in self._variables.items():
            var_dims = tuple(dim for dim in dims if dim in var.dims)
            ds._variables[name] = var.transpose(*var_dims)
        return ds


Instruction:
Given the following Python 3 function, write the documentation
def dropna(self, dim, how='any', thresh=None, subset=None):
        # TODO: consider supporting multiple dimensions? Or not, given that
        # there are some ugly edge cases, e.g., pandas's dropna differs
        # depending on the order of the supplied axes.

        if dim not in self.dims:
            raise ValueError('%s must be a single dataset dimension' % dim)

        if subset is None:
            subset = list(self.data_vars)

        count = np.zeros(self.dims[dim], dtype=np.int64)
        size = 0

        for k in subset:
            array = self._variables[k]
            if dim in array.dims:
                dims = [d for d in array.dims if d != dim]
                count += np.asarray(array.count(dims))
                size += np.prod([self.dims[d] for d in dims])

        if thresh is not None:
            mask = count >= thresh
        elif how == 'any':
            mask = count == size
        elif how == 'all':
            mask = count > 0
        elif how is not None:
            raise ValueError('invalid how option: %s' % how)
        else:
            raise TypeError('must specify how or thresh')

        return self.isel({dim: mask})

Response: Returns a new dataset with dropped labels for missing values along the provided dimension.


Instruction:
Create a Python 3 function for
filling missing values in this object with the given value.

Response:
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
        index coordinates (``join='inner'``).

        Parameters
        ----------
        value : scalar, ndarray, DataArray, dict or Dataset
            Used to fill all matching missing values in this dataset's data
            variables. Scalars, ndarrays or DataArrays arguments are used to
            fill all data with aligned coordinates (for DataArrays).
            Dictionaries or datasets match data variables and then align
            coordinates if necessary.

        Returns
        -------
        Dataset
        """
        if utils.is_dict_like(value):
            value_keys = getattr(value, 'data_vars', value).keys()
            if not set(value_keys) <= set(self.data_vars.keys()):
                raise ValueError('all variables in the argument to `fillna` '
                                 'must be contained in the original dataset')
        out = ops.fillna(self, value)
        return out


Instruction:
How would you code a function in Python 3 to
interpolate values along a specified dimension.

Response:
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 interpolate.
        method : {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
                  'polynomial', 'barycentric', 'krog', 'pchip',
                  'spline'}, optional
            String indicating which method to use for interpolation:

            - 'linear': linear interpolation (Default). Additional keyword
              arguments are passed to ``numpy.interp``
            - 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
              'polynomial': are passed to ``scipy.interpolate.interp1d``. If
              method=='polynomial', the ``order`` keyword argument must also be
              provided.
            - 'barycentric', 'krog', 'pchip', 'spline': use their respective
              ``scipy.interpolate`` classes.
        use_coordinate : boolean or str, default True
            Specifies which index to use as the x values in the interpolation
            formulated as `y = f(x)`. If False, values are treated as if
            eqaully-spaced along `dim`. If True, the IndexVariable `dim` is
            used. If use_coordinate is a string, it specifies the name of a
            coordinate variariable to use as the index.
        limit : int, default None
            Maximum number of consecutive NaNs to fill. Must be greater than 0
            or None for no limit.

        Returns
        -------
        Dataset

        See also
        --------
        numpy.interp
        scipy.interpolate
        """
        from .missing import interp_na, _apply_over_vars_with_dim

        new = _apply_over_vars_with_dim(interp_na, self, dim=dim,
                                        method=method, limit=limit,
                                        use_coordinate=use_coordinate,
                                        **kwargs)
        return new


Instruction:
Implement a Python 3 function for
filling NaN values by propogating values forward

Response:
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
            The maximum number of consecutive NaN values to forward fill. In
            other words, if there is a gap with more than this number of
            consecutive NaNs, it will only be partially filled. Must be greater
            than 0 or None for no limit.

        Returns
        -------
        Dataset
        '''
        from .missing import ffill, _apply_over_vars_with_dim

        new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
        return new


Instruction:
Can you generate a brief explanation for the following Python 3 code
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
            The maximum number of consecutive NaN values to backward fill. In
            other words, if there is a gap with more than this number of
            consecutive NaNs, it will only be partially filled. Must be greater
            than 0 or None for no limit.

        Returns
        -------
        Dataset
        '''
        from .missing import bfill, _apply_over_vars_with_dim

        new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit)
        return new

Response:
Fill NaN values by propogating values backward
            filling.


Instruction:
Make a summary of the following Python 3 code
def combine_first(self, other):
        out = ops.fillna(self, other, join="outer", dataset_join="outer")
        return out

Response: Combine two Datasets default to data_vars of self.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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(x, axis=axis, **kwargs)` to return the result of reducing an
            np.ndarray over an integer valued axis.
        dim : str or sequence of str, optional
            Dimension(s) over which to apply `func`.  By default `func` is
            applied over all dimensions.
        keep_attrs : bool, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        numeric_only : bool, optional
            If True, only apply ``func`` to variables with a numeric dtype.
        **kwargs : dict
            Additional keyword arguments passed on to ``func``.

        Returns
        -------
        reduced : Dataset
            Dataset with this object's DataArrays replaced with new DataArrays
            of summarized data and the indicated dimension(s) removed.
        """
        if dim is ALL_DIMS:
            dim = None
        if isinstance(dim, str):
            dims = set([dim])
        elif dim is None:
            dims = set(self.dims)
        else:
            dims = set(dim)

        missing_dimensions = [d for d in dims if d not in self.dims]
        if missing_dimensions:
            raise ValueError('Dataset does not contain the dimensions: %s'
                             % missing_dimensions)

        if keep_attrs is None:
            keep_attrs = _get_keep_attrs(default=False)

        variables = OrderedDict()
        for name, var in self._variables.items():
            reduce_dims = [d for d in var.dims if d in dims]
            if name in self.coords:
                if not reduce_dims:
                    variables[name] = var
            else:
                if (not numeric_only or
                        np.issubdtype(var.dtype, np.number) or
                        (var.dtype == np.bool_)):
                    if len(reduce_dims) == 1:
                        # unpack dimensions for the benefit of functions
                        # like np.argmin which can't handle tuple arguments
                        reduce_dims, = reduce_dims
                    elif len(reduce_dims) == var.ndim:
                        # prefer to aggregate over axis=None rather than
                        # axis=(0, 1) if they will be equivalent, because
                        # the former is often more efficient
                        reduce_dims = None
                    variables[name] = var.reduce(func, dim=reduce_dims,
                                                 keep_attrs=keep_attrs,
                                                 allow_lazy=allow_lazy,
                                                 **kwargs)

        coord_names = set(k for k in self.coords if k in variables)
        attrs = self.attrs if keep_attrs else None
        return self._replace_vars_and_dims(variables, coord_names, attrs=attrs)

Response: Reduces this Dataset by applying func along some dimension.


Instruction:
Implement a function in Python 3 to
apply a function over the data variables in this dataset and return a new dataset with the result.

Response:
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 this dataset into another
            DataArray.
        keep_attrs : bool, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one. If False, the new object will
            be returned without attributes.
        args : tuple, optional
            Positional arguments passed on to `func`.
        **kwargs : dict
            Keyword arguments passed on to `func`.

        Returns
        -------
        applied : Dataset
            Resulting dataset from applying ``func`` over each data variable.

        Examples
        --------
        >>> da = xr.DataArray(np.random.randn(2, 3))
        >>> ds = xr.Dataset({'foo': da, 'bar': ('x', [-1, 2])})
        >>> ds
        <xarray.Dataset>
        Dimensions:  (dim_0: 2, dim_1: 3, x: 2)
        Dimensions without coordinates: dim_0, dim_1, x
        Data variables:
            foo      (dim_0, dim_1) float64 -0.3751 -1.951 -1.945 0.2948 0.711 -0.3948
            bar      (x) int64 -1 2
        >>> ds.apply(np.fabs)
        <xarray.Dataset>
        Dimensions:  (dim_0: 2, dim_1: 3, x: 2)
        Dimensions without coordinates: dim_0, dim_1, x
        Data variables:
            foo      (dim_0, dim_1) float64 0.3751 1.951 1.945 0.2948 0.711 0.3948
            bar      (x) float64 1.0 2.0
        """  # noqa
        variables = OrderedDict(
            (k, maybe_wrap_array(v, func(v, *args, **kwargs)))
            for k, v in self.data_vars.items())
        if keep_attrs is None:
            keep_attrs = _get_keep_attrs(default=False)
        attrs = self.attrs if keep_attrs else None
        return type(self)(variables, attrs=attrs)


Instruction:
Given the following Python 3 function, write the documentation
def assign(self, variables=None, **variables_kwargs):
        variables = either_dict_or_kwargs(
            variables, variables_kwargs, 'assign')
        data = self.copy()
        # do all calculations first...
        results = data._calc_assign_results(variables)
        # ... and then assign
        data.update(results)
        return data

Response: Assign new data variables to a Dataset returning a new Dataset with all the original variables added to the new ones.


Instruction:
Can you tell what is the following Python 3 function doing
def to_array(self, dim='variable', name=None):
        from .dataarray import DataArray

        data_vars = [self.variables[k] for k in self.data_vars]
        broadcast_vars = broadcast_variables(*data_vars)
        data = duck_array_ops.stack([b.data for b in broadcast_vars], axis=0)

        coords = dict(self.coords)
        coords[dim] = list(self.data_vars)

        dims = (dim,) + broadcast_vars[0].dims

        return DataArray(data, coords, dims, attrs=self.attrs, name=name)

Response: Convert this dataset into an xarray. DataArray.


Instruction:
Implement a Python 3 function for
converting this dataset into a dask. dataframe. DataFrame.

Response:
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, optional
            Hierarchical dimension order for the resulting dataframe. All
            arrays are transposed to this order and then written out as flat
            vectors in contiguous order, so the last dimension in this list
            will be contiguous in the resulting DataFrame. This has a major
            influence on which operations are efficient on the resulting dask
            dataframe.

            If provided, must include all dimensions on this dataset. By
            default, dimensions are sorted alphabetically.
        set_index : bool, optional
            If set_index=True, the dask DataFrame is indexed by this dataset's
            coordinate. Since dask DataFrames to not support multi-indexes,
            set_index only works if the dataset only contains one dimension.

        Returns
        -------
        dask.dataframe.DataFrame
        """

        import dask.array as da
        import dask.dataframe as dd

        if dim_order is None:
            dim_order = list(self.dims)
        elif set(dim_order) != set(self.dims):
            raise ValueError(
                'dim_order {} does not match the set of dimensions on this '
                'Dataset: {}'.format(dim_order, list(self.dims)))

        ordered_dims = OrderedDict((k, self.dims[k]) for k in dim_order)

        columns = list(ordered_dims)
        columns.extend(k for k in self.coords if k not in self.dims)
        columns.extend(self.data_vars)

        series_list = []
        for name in columns:
            try:
                var = self.variables[name]
            except KeyError:
                # dimension without a matching coordinate
                size = self.dims[name]
                data = da.arange(size, chunks=size, dtype=np.int64)
                var = Variable((name,), data)

            # IndexVariable objects have a dummy .chunk() method
            if isinstance(var, IndexVariable):
                var = var.to_base_variable()

            dask_array = var.set_dims(ordered_dims).chunk(self.chunks).data
            series = dd.from_array(dask_array.reshape(-1), columns=[name])
            series_list.append(series)

        df = dd.concat(series_list, axis=1)

        if set_index:
            if len(dim_order) == 1:
                (dim,) = dim_order
                df = df.set_index(dim)
            else:
                # triggers an error about multi-indexes, even if only one
                # dimension is passed
                df = df.set_index(dim_order)

        return df


Instruction:
Can you implement a function in Python 3 that
converts this dataset to a dictionary following xarray naming conventions.

Response:
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 xarrray.open_dataset.

        Parameters
        ----------
        data : bool, optional
            Whether to include the actual data in the dictionary. When set to
            False, returns just the schema.

        See also
        --------
        Dataset.from_dict
        """
        d = {'coords': {}, 'attrs': decode_numpy_dict_values(self.attrs),
             'dims': dict(self.dims), 'data_vars': {}}
        for k in self.coords:
            d['coords'].update({k: self[k].variable.to_dict(data=data)})
        for k in self.data_vars:
            d['data_vars'].update({k: self[k].variable.to_dict(data=data)})
        return d


Instruction:
Write a Python 3 script to
convert a dictionary into an xarray. Dataset.

Response:
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': {'dims': 't', 'data': t,
                                  'attrs': {'units':'s'}}},
                 'attrs': {'title': 'air temperature'},
                 'dims': 't',
                 'data_vars': {'a': {'dims': 't', 'data': x, },
                               'b': {'dims': 't', 'data': y}}}

        where 't' is the name of the dimesion, 'a' and 'b' are names of data
        variables and t, x, and y are lists, numpy.arrays or pandas objects.

        Parameters
        ----------
        d : dict, with a minimum structure of {'var_0': {'dims': [..], \
                                                         'data': [..]}, \
                                               ...}

        Returns
        -------
        obj : xarray.Dataset

        See also
        --------
        Dataset.to_dict
        DataArray.from_dict
        """

        if not set(['coords', 'data_vars']).issubset(set(d)):
            variables = d.items()
        else:
            import itertools
            variables = itertools.chain(d.get('coords', {}).items(),
                                        d.get('data_vars', {}).items())
        try:
            variable_dict = OrderedDict([(k, (v['dims'],
                                              v['data'],
                                              v.get('attrs'))) for
                                         k, v in variables])
        except KeyError as e:
            raise ValueError(
                "cannot convert dict without the key "
                "'{dims_data}'".format(dims_data=str(e.args[0])))
        obj = cls(variable_dict)

        # what if coords aren't dims?
        coords = set(d.get('coords', {})) - set(d.get('dims', {}))
        obj = obj.set_coords(coords)

        obj.attrs.update(d.get('attrs', {}))

        return obj


Instruction:
Write a Python 3 function for
calculating the n - th order discrete difference along a given dimension.

Response:
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 differenced.
        label : str, optional
            The new coordinate in dimension ``dim`` will have the
            values of either the minuend's or subtrahend's coordinate
            for values 'upper' and 'lower', respectively.  Other
            values are not supported.

        Returns
        -------
        difference : same type as caller
            The n-th order finite difference of this object.

        Examples
        --------
        >>> ds = xr.Dataset({'foo': ('x', [5, 5, 6, 6])})
        >>> ds.diff('x')
        <xarray.Dataset>
        Dimensions:  (x: 3)
        Coordinates:
          * x        (x) int64 1 2 3
        Data variables:
            foo      (x) int64 0 1 0
        >>> ds.diff('x', 2)
        <xarray.Dataset>
        Dimensions:  (x: 2)
        Coordinates:
        * x        (x) int64 2 3
        Data variables:
        foo      (x) int64 1 -1

        See Also
        --------
        Dataset.differentiate
        """
        if n == 0:
            return self
        if n < 0:
            raise ValueError('order `n` must be non-negative but got {0}'
                             ''.format(n))

        # prepare slices
        kwargs_start = {dim: slice(None, -1)}
        kwargs_end = {dim: slice(1, None)}

        # prepare new coordinate
        if label == 'upper':
            kwargs_new = kwargs_end
        elif label == 'lower':
            kwargs_new = kwargs_start
        else:
            raise ValueError('The \'label\' argument has to be either '
                             '\'upper\' or \'lower\'')

        variables = OrderedDict()

        for name, var in self.variables.items():
            if dim in var.dims:
                if name in self.data_vars:
                    variables[name] = (var.isel(**kwargs_end) -
                                       var.isel(**kwargs_start))
                else:
                    variables[name] = var.isel(**kwargs_new)
            else:
                variables[name] = var

        difference = self._replace_vars_and_dims(variables)

        if n > 1:
            return difference.diff(dim, n - 1)
        else:
            return difference


Instruction:
How would you code a function in Python 3 to
shift this Dataset by an offset along one or more dimensions.

Response:
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
        ----------
        shifts : Mapping with the form of {dim: offset}
            Integer offset to shift along each of the given dimensions.
            Positive offsets shift to the right; negative offsets shift to the
            left.
        fill_value: scalar, optional
            Value to use for newly missing values
        **shifts_kwargs:
            The keyword arguments form of ``shifts``.
            One of shifts or shifts_kwarg must be provided.

        Returns
        -------
        shifted : Dataset
            Dataset with the same coordinates and attributes but shifted data
            variables.

        See also
        --------
        roll

        Examples
        --------

        >>> ds = xr.Dataset({'foo': ('x', list('abcde'))})
        >>> ds.shift(x=2)
        <xarray.Dataset>
        Dimensions:  (x: 5)
        Coordinates:
          * x        (x) int64 0 1 2 3 4
        Data variables:
            foo      (x) object nan nan 'a' 'b' 'c'
        """
        shifts = either_dict_or_kwargs(shifts, shifts_kwargs, 'shift')
        invalid = [k for k in shifts if k not in self.dims]
        if invalid:
            raise ValueError("dimensions %r do not exist" % invalid)

        variables = OrderedDict()
        for name, var in self.variables.items():
            if name in self.data_vars:
                var_shifts = {k: v for k, v in shifts.items()
                              if k in var.dims}
                variables[name] = var.shift(
                    fill_value=fill_value, shifts=var_shifts)
            else:
                variables[name] = var

        return self._replace_vars_and_dims(variables)


Instruction:
Explain what the following Python 3 code does
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
        shifts = either_dict_or_kwargs(shifts, shifts_kwargs, 'roll')
        invalid = [k for k in shifts if k not in self.dims]
        if invalid:
            raise ValueError("dimensions %r do not exist" % invalid)

        if roll_coords is None:
            warnings.warn("roll_coords will be set to False in the future."
                          " Explicitly set roll_coords to silence warning.",
                          FutureWarning, stacklevel=2)
            roll_coords = True

        unrolled_vars = () if roll_coords else self.coords

        variables = OrderedDict()
        for k, v in self.variables.items():
            if k not in unrolled_vars:
                variables[k] = v.roll(**{k: s for k, s in shifts.items()
                                         if k in v.dims})
            else:
                variables[k] = v

        return self._replace_vars_and_dims(variables)

Response: Roll this Dataset by an offset along one or more dimensions.


Instruction:
Write a Python 3 script for
sorting the dataset by the specified variables.

Response:
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 dataarrays, then the dataarrays are aligned
        (via left-join) to the calling object prior to sorting by cell values.
        NaNs are sorted to the end, following Numpy convention.

        If multiple sorts along the same dimension is
        given, numpy's lexsort is performed along that dimension:
        https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html
        and the FIRST key in the sequence is used as the primary sort key,
        followed by the 2nd key, etc.

        Parameters
        ----------
        variables: str, DataArray, or list of either
            1D DataArray objects or name(s) of 1D variable(s) in
            coords/data_vars whose values are used to sort the dataset.
        ascending: boolean, optional
            Whether to sort by ascending or descending order.

        Returns
        -------
        sorted: Dataset
            A new dataset where all the specified dims are sorted by dim
            labels.
        """
        from .dataarray import DataArray

        if not isinstance(variables, list):
            variables = [variables]
        else:
            variables = variables
        variables = [v if isinstance(v, DataArray) else self[v]
                     for v in variables]
        aligned_vars = align(self, *variables, join='left')
        aligned_self = aligned_vars[0]
        aligned_other_vars = aligned_vars[1:]
        vars_by_dim = defaultdict(list)
        for data_array in aligned_other_vars:
            if data_array.ndim != 1:
                raise ValueError("Input DataArray is not 1-D.")
            if (data_array.dtype == object and
                    LooseVersion(np.__version__) < LooseVersion('1.11.0')):
                raise NotImplementedError(
                    'sortby uses np.lexsort under the hood, which requires '
                    'numpy 1.11.0 or later to support object data-type.')
            (key,) = data_array.dims
            vars_by_dim[key].append(data_array)

        indices = {}
        for key, arrays in vars_by_dim.items():
            order = np.lexsort(tuple(reversed(arrays)))
            indices[key] = order if ascending else order[::-1]
        return aligned_self.isel(**indices)


Instruction:
Can you generate the documentation for the following Python 3 function
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
        ----------
        q : float in range of [0,1] (or sequence of floats)
            Quantile to compute, which must be between 0 and 1 inclusive.
        dim : str or sequence of str, optional
            Dimension(s) over which to apply quantile.
        interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
            This optional parameter specifies the interpolation method to
            use when the desired quantile lies between two data points
            ``i < j``:

                * linear: ``i + (j - i) * fraction``, where ``fraction`` is
                  the fractional part of the index surrounded by ``i`` and
                  ``j``.
                * lower: ``i``.
                * higher: ``j``.
                * nearest: ``i`` or ``j``, whichever is nearest.
                * midpoint: ``(i + j) / 2``.
        keep_attrs : bool, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        numeric_only : bool, optional
            If True, only apply ``func`` to variables with a numeric dtype.

        Returns
        -------
        quantiles : Dataset
            If `q` is a single quantile, then the result is a scalar for each
            variable in data_vars. If multiple percentiles are given, first
            axis of the result corresponds to the quantile and a quantile
            dimension is added to the return Dataset. The other dimensions are
            the dimensions that remain after the reduction of the array.

        See Also
        --------
        numpy.nanpercentile, pandas.Series.quantile, DataArray.quantile
        """

        if isinstance(dim, str):
            dims = set([dim])
        elif dim is None:
            dims = set(self.dims)
        else:
            dims = set(dim)

        _assert_empty([d for d in dims if d not in self.dims],
                      'Dataset does not contain the dimensions: %s')

        q = np.asarray(q, dtype=np.float64)

        variables = OrderedDict()
        for name, var in self.variables.items():
            reduce_dims = [d for d in var.dims if d in dims]
            if reduce_dims or not var.dims:
                if name not in self.coords:
                    if (not numeric_only or
                        np.issubdtype(var.dtype, np.number) or
                            var.dtype == np.bool_):
                        if len(reduce_dims) == var.ndim:
                            # prefer to aggregate over axis=None rather than
                            # axis=(0, 1) if they will be equivalent, because
                            # the former is often more efficient
                            reduce_dims = None
                        variables[name] = var.quantile(
                            q, dim=reduce_dims, interpolation=interpolation)

            else:
                variables[name] = var

        # construct the new dataset
        coord_names = set(k for k in self.coords if k in variables)
        if keep_attrs is None:
            keep_attrs = _get_keep_attrs(default=False)
        attrs = self.attrs if keep_attrs else None
        new = self._replace_vars_and_dims(variables, coord_names, attrs=attrs)
        if 'quantile' in new.dims:
            new.coords['quantile'] = Variable('quantile', q)
        else:
            new.coords['quantile'] = q
        return new

Response: Compute the qth quantile of the data along the specified dimension.


Instruction:
Make a summary of the following Python 3 code
def rank(self, dim, pct=False, keep_attrs=None):
        if dim not in self.dims:
            raise ValueError(
                'Dataset does not contain the dimension: %s' % dim)

        variables = OrderedDict()
        for name, var in self.variables.items():
            if name in self.data_vars:
                if dim in var.dims:
                    variables[name] = var.rank(dim, pct=pct)
            else:
                variables[name] = var

        coord_names = set(self.coords)
        if keep_attrs is None:
            keep_attrs = _get_keep_attrs(default=False)
        attrs = self.attrs if keep_attrs else None
        return self._replace_vars_and_dims(variables, coord_names, attrs=attrs)

Response:
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.

        NaNs in the input array are returned as NaNs.

        The `bottleneck` library is required.

        Parameters
        ----------
        dim : str
            Dimension over which to compute rank.
        pct : bool, optional
            If True, compute percentage ranks, otherwise compute integer ranks.
        keep_attrs : bool, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.

        Returns
        -------
        ranked : Dataset
            Variables that do not depend on `dim` are dropped.


Instruction:
Given the following Python 3 function, write the documentation
def differentiate(self, coord, edge_order=1, datetime_unit=None):
        from .variable import Variable

        if coord not in self.variables and coord not in self.dims:
            raise ValueError('Coordinate {} does not exist.'.format(coord))

        coord_var = self[coord].variable
        if coord_var.ndim != 1:
            raise ValueError('Coordinate {} must be 1 dimensional but is {}'
                             ' dimensional'.format(coord, coord_var.ndim))

        dim = coord_var.dims[0]
        if _contains_datetime_like_objects(coord_var):
            if coord_var.dtype.kind in 'mM' and datetime_unit is None:
                datetime_unit, _ = np.datetime_data(coord_var.dtype)
            elif datetime_unit is None:
                datetime_unit = 's'  # Default to seconds for cftime objects
            coord_var = coord_var._to_numeric(datetime_unit=datetime_unit)

        variables = OrderedDict()
        for k, v in self.variables.items():
            if (k in self.data_vars and dim in v.dims and
                    k not in self.coords):
                if _contains_datetime_like_objects(v):
                    v = v._to_numeric(datetime_unit=datetime_unit)
                grad = duck_array_ops.gradient(
                    v.data, coord_var, edge_order=edge_order,
                    axis=v.get_axis_num(dim))
                variables[k] = Variable(v.dims, grad)
            else:
                variables[k] = v
        return self._replace_vars_and_dims(variables)

Response: Differentiate with the second order accurate central centralCOOKIE entries.


Instruction:
Implement a Python 3 function for
integrating the array with the trapezoidal rule.

Response:
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
            Coordinate(s) used for the integration.
        datetime_unit
            Can be specify the unit if datetime coordinate is used. One of
            {'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs',
             'as'}

        Returns
        -------
        integrated: Dataset

        See also
        --------
        DataArray.integrate
        numpy.trapz: corresponding numpy function
        """
        if not isinstance(coord, (list, tuple)):
            coord = (coord, )
        result = self
        for c in coord:
            result = result._integrate_one(c, datetime_unit=datetime_unit)
        return result


Instruction:
How would you explain what the following Python 3 function does
def filter_by_attrs(self, **kwargs):
        selection = []
        for var_name, variable in self.data_vars.items():
            has_value_flag = False
            for attr_name, pattern in kwargs.items():
                attr_value = variable.attrs.get(attr_name)
                if ((callable(pattern) and pattern(attr_value)) or
                        attr_value == pattern):
                    has_value_flag = True
                else:
                    has_value_flag = False
                    break
            if has_value_flag is True:
                selection.append(var_name)
        return self[selection]

Response: Returns a new Dataset with variables that match specific conditions.


Instruction:
How would you explain what the following Python 3 function does
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 np.where(condition, decoded_fill_value, data)

Response: Mask all matching values in a NumPy arrays.


Instruction:
Write a Python 3 script for
returning a float dtype that can losslessly represent dtype values.

Response:
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.floating):
        return np.float32
    # float32 can exactly represent all integers up to 24 bits
    if dtype.itemsize <= 2 and np.issubdtype(dtype, np.integer):
        # A scale factor is entirely safe (vanishing into the mantissa),
        # but a large integer offset could lead to loss of precision.
        # Sensitivity analysis can be tricky, so we just use a float64
        # if there's any offset at all - better unoptimised than wrong!
        if not has_offset:
            return np.float32
    # For all other types and circumstances, we just use float64.
    # (safe because eg. complex numbers are not supported in NetCDF)
    return np.float64


Instruction:
How would you explain what the following Python 3 function does
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

    return ds

Response: wrapper for datasets with dim = None


Instruction:
Here you have a function in Python 3, explain what it does
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 False, the x values are set as an equally spaced
    sequence.
    '''
    if use_coordinate:
        if use_coordinate is True:
            index = arr.get_index(dim)
        else:
            index = arr.coords[use_coordinate]
            if index.ndim != 1:
                raise ValueError(
                    'Coordinates used for interpolation must be 1D, '
                    '%s is %dD.' % (use_coordinate, index.ndim))

        # raise if index cannot be cast to a float (e.g. MultiIndex)
        try:
            index = index.values.astype(np.float64)
        except (TypeError, ValueError):
            # pandas raises a TypeError
            # xarray/nuppy raise a ValueError
            raise TypeError('Index must be castable to float64 to support'
                            'interpolation, got: %s' % type(index))
        # check index sorting now so we can skip it later
        if not (np.diff(index) > 0).all():
            raise ValueError("Index must be monotonicly increasing")
    else:
        axis = arr.get_axis_num(dim)
        index = np.arange(arr.shape[axis], dtype=np.float64)

    return index

Response: get index to use for x values in interpolation.


Instruction:
Can you generate the documentation for the following Python 3 function
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, dim, limit)

    # method
    index = get_clean_interp_index(self, dim, use_coordinate=use_coordinate,
                                   **kwargs)
    interp_class, kwargs = _get_interpolator(method, **kwargs)
    interpolator = partial(func_interpolate_na, interp_class, **kwargs)

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', 'overflow', RuntimeWarning)
        warnings.filterwarnings('ignore', 'invalid value', RuntimeWarning)
        arr = apply_ufunc(interpolator, index, self,
                          input_core_dims=[[dim], [dim]],
                          output_core_dims=[[dim]],
                          output_dtypes=[self.dtype],
                          dask='parallelized',
                          vectorize=True,
                          keep_attrs=True).transpose(*self.dims)

    if limit is not None:
        arr = arr.where(valids)

    return arr

Response: Interpolate values according to different methods.


Instruction:
How would you explain what the following Python 3 function does
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 = ~nans

    # fast track for no-nans and all-nans cases
    n_nans = nans.sum()
    if n_nans == 0 or n_nans == len(y):
        return y

    f = interpolator(x[nonans], y[nonans], **kwargs)
    out[nans] = f(x[nans])
    return out

Response: helper function to apply interpolation along 1 dimension


Instruction:
Can you generate a brief explanation for the following Python 3 code
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',
                       keep_attrs=True,
                       output_dtypes=[arr.dtype],
                       kwargs=dict(n=_limit, axis=axis)).transpose(*arr.dims)

Response: forward fill missing values


Instruction:
Given the following Python 3 function, write the documentation
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', 'polynomial']
    valid_methods = interp1d_methods + ['barycentric', 'krog', 'pchip',
                                        'spline', 'akima']

    has_scipy = True
    try:
        from scipy import interpolate
    except ImportError:
        has_scipy = False

    # prioritize scipy.interpolate
    if (method == 'linear' and not
            kwargs.get('fill_value', None) == 'extrapolate' and
            not vectorizeable_only):
        kwargs.update(method=method)
        interp_class = NumpyInterpolator

    elif method in valid_methods:
        if not has_scipy:
            raise ImportError(
                'Interpolation with method `%s` requires scipy' % method)

        if method in interp1d_methods:
            kwargs.update(method=method)
            interp_class = ScipyInterpolator
        elif vectorizeable_only:
            raise ValueError('{} is not a vectorizeable interpolator. '
                             'Available methods are {}'.format(
                                 method, interp1d_methods))
        elif method == 'barycentric':
            interp_class = interpolate.BarycentricInterpolator
        elif method == 'krog':
            interp_class = interpolate.KroghInterpolator
        elif method == 'pchip':
            interp_class = interpolate.PchipInterpolator
        elif method == 'spline':
            kwargs.update(method=method)
            interp_class = SplineInterpolator
        elif method == 'akima':
            interp_class = interpolate.Akima1DInterpolator
        else:
            raise ValueError('%s is not a valid scipy interpolator' % method)
    else:
        raise ValueError('%s is not a valid interpolator' % method)

    return interp_class, kwargs

Response:
helper function to select the appropriate interpolator class for the appropriate class
    returns interpolator class and keyword arguments for the class


Instruction:
Can you generate the documentation for the following Python 3 function
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 ImportError(
            'Interpolation with method `%s` requires scipy' % method)

    if method in valid_methods:
        kwargs.update(method=method)
        interp_class = interpolate.interpn
    else:
        raise ValueError('%s is not a valid interpolator for interpolating '
                         'over multiple dimensions.' % method)

    return interp_class, kwargs

Response: helper function to select the appropriate interpolator class and keyword arguments for the class


Instruction:
Explain what the following Python 3 code does
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=1, **kw)
            .construct(new_dim, fill_value=False)
            .sum(new_dim, skipna=False)) <= limit

Response:
helper function to determine values that can be filled when limit is not
    None


Instruction:
Implement a function in Python 3 to
localize a variable by linear and nearest neighbor method.

Response:
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), method='nearest')
        imax = index.get_loc(np.max(new_x.values), method='nearest')

        indexes[dim] = slice(max(imin - 2, 0), imax + 2)
        indexes_coords[dim] = (x[indexes[dim]], new_x)
    return var.isel(**indexes), indexes_coords


Instruction:
Write a Python 3 script for
making x and new_x float.

Response:
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.float64, which is not accurate
            # enough for datetime64 (uses 64bit integer).
            # We assume that the most of the bits are used to represent the
            # offset (min(x)) and the variation (x - min(x)) can be
            # represented by float.
            xmin = x[i].values.min()
            x[i] = x[i]._to_numeric(offset=xmin, dtype=np.float64)
            new_x[i] = new_x[i]._to_numeric(offset=xmin, dtype=np.float64)
    return x, new_x


Instruction:
Given the following Python 3 function, write the documentation
def interp(var, indexes_coords, method, **kwargs):
    if not indexes_coords:
        return var.copy()

    # simple speed up for the local interpolation
    if method in ['linear', 'nearest']:
        var, indexes_coords = _localize(var, indexes_coords)

    # default behavior
    kwargs['bounds_error'] = kwargs.get('bounds_error', False)

    # target dimensions
    dims = list(indexes_coords)
    x, new_x = zip(*[indexes_coords[d] for d in dims])
    destination = broadcast_variables(*new_x)

    # transpose to make the interpolated axis to the last position
    broadcast_dims = [d for d in var.dims if d not in dims]
    original_dims = broadcast_dims + dims
    new_dims = broadcast_dims + list(destination[0].dims)
    interped = interp_func(var.transpose(*original_dims).data,
                           x, destination, method, kwargs)

    result = Variable(new_dims, interped, attrs=var.attrs)

    # dimension of the output array
    out_dims = OrderedSet()
    for d in var.dims:
        if d in dims:
            out_dims.update(indexes_coords[d][1].dims)
        else:
            out_dims.add(d)
    return result.transpose(*tuple(out_dims))

Response: Interpolate a Variable with a set of indexes coordinates.


Instruction:
Write a Python 3 script for
interpolating a 1 - dimensional array - like or array - like into a new array - like.

Response:
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 list of 1d array.
        Original coordinates. Should not contain NaN.
    new_x: a list of 1d array
        New coordinates. Should not contain NaN.
    method: string
        {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'} for
        1-dimensional itnterpolation.
        {'linear', 'nearest'} for multidimensional interpolation
    **kwargs:
        Optional keyword arguments to be passed to scipy.interpolator

    Returns
    -------
    interpolated: array
        Interpolated array

    Note
    ----
    This requiers scipy installed.

    See Also
    --------
    scipy.interpolate.interp1d
    """
    if not x:
        return var.copy()

    if len(x) == 1:
        func, kwargs = _get_interpolator(method, vectorizeable_only=True,
                                         **kwargs)
    else:
        func, kwargs = _get_interpolator_nd(method, **kwargs)

    if isinstance(var, dask_array_type):
        import dask.array as da

        _assert_single_chunk(var, range(var.ndim - len(x), var.ndim))
        chunks = var.chunks[:-len(x)] + new_x[0].shape
        drop_axis = range(var.ndim - len(x), var.ndim)
        new_axis = range(var.ndim - len(x), var.ndim - len(x) + new_x[0].ndim)
        return da.map_blocks(_interpnd, var, x, new_x, func, kwargs,
                             dtype=var.dtype, chunks=chunks,
                             new_axis=new_axis, drop_axis=drop_axis)

    return _interpnd(var, x, new_x, func, kwargs)


Instruction:
Explain what the following Python 3 code does
def _nicetitle(coord, value, maxchar, template):
    prettyvalue = format_item(value, quote_strings=False)
    title = template.format(coord=coord, value=prettyvalue)

    if len(title) > maxchar:
        title = title[:(maxchar - 3)] + '...'

    return title

Response: Return a nicetitle for a given coordinate and value.


Instruction:
Explain what the following Python 3 code does
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 arguments to 2d plotting method
    """
    ax = kwargs.pop('ax', None)
    figsize = kwargs.pop('figsize', None)
    if ax is not None:
        raise ValueError("Can't use axes when making faceted plots.")
    if aspect is None:
        aspect = 1
    if size is None:
        size = 3
    elif figsize is not None:
        raise ValueError('cannot provide both `figsize` and `size` arguments')

    g = FacetGrid(data=data, col=col, row=row, col_wrap=col_wrap,
                  sharex=sharex, sharey=sharey, figsize=figsize,
                  aspect=aspect, size=size, subplot_kws=subplot_kws)

    if kind == 'line':
        return g.map_dataarray_line(plotfunc, x, y, **kwargs)

    if kind == 'dataarray':
        return g.map_dataarray(plotfunc, x, y, **kwargs)

Response: This method is used to make faceted plots from 2d plotting.


Instruction:
Can you tell what is the following Python 3 function doing
def map_dataarray(self, func, x, y, **kwargs):

        if kwargs.get('cbar_ax', None) is not None:
            raise ValueError('cbar_ax not supported by FacetGrid.')

        cmap_params, cbar_kwargs = _process_cmap_cbar_kwargs(
            func, kwargs, self.data.values)

        self._cmap_extend = cmap_params.get('extend')

        # Order is important
        func_kwargs = kwargs.copy()
        func_kwargs.update(cmap_params)
        func_kwargs.update({'add_colorbar': False, 'add_labels': False})

        # Get x, y labels for the first subplot
        x, y = _infer_xy_labels(
            darray=self.data.loc[self.name_dicts.flat[0]], x=x, y=y,
            imshow=func.__name__ == 'imshow', rgb=kwargs.get('rgb', None))

        for d, ax in zip(self.name_dicts.flat, self.axes.flat):
            # None is the sentinel value
            if d is not None:
                subset = self.data.loc[d]
                mappable = func(subset, x=x, y=y, ax=ax, **func_kwargs)
                self._mappables.append(mappable)

        self._cmap_extend = cmap_params.get('extend')
        self._finalize_grid(x, y)

        if kwargs.get('add_colorbar', True):
            self.add_colorbar(**cbar_kwargs)

        return self

Response: Applies a function to a 2d xarray containing a subset of the data.


Instruction:
Create a Python 3 function to
finalize the annotations and layout.

Response:
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):
                if namedict is None:
                    ax.set_visible(False)

            self._finalized = True


Instruction:
Implement a Python 3 function for
drawing a colorbar for the current object

Response:
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.cbar = self.fig.colorbar(self._mappables[-1],
                                      ax=list(self.axes.flat),
                                      **kwargs)
        return self


Instruction:
Can you tell what is the following Python 3 function doing
def set_axis_labels(self, x_var=None, y_var=None):
        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]))
            else:
                # x_var is a string
                self.set_xlabels(x_var)

        if y_var is not None:
            if y_var in self.data.coords:
                self._y_var = y_var
                self.set_ylabels(label_from_attrs(self.data[y_var]))
            else:
                self.set_ylabels(y_var)
        return self

Response: Set axis labels on the left column and bottom row of the grid.


Instruction:
Write a Python 3 function for
labeling the x axis on the bottom row of the grid.

Response:
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


Instruction:
Make a summary of the following Python 3 code
def set_ylabels(self, label=None, **kwargs):
        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

Response: Label the y axis on the left column of the grid.


Instruction:
Can you generate the documentation for the following Python 3 function
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}
        maxchar : int
            Truncate titles at maxchar
        kwargs : keyword args
            additional arguments to matplotlib.text

        Returns
        -------
        self: FacetGrid object

        """
        import matplotlib as mpl

        kwargs["size"] = kwargs.pop("size", mpl.rcParams["axes.labelsize"])

        nicetitle = functools.partial(_nicetitle, maxchar=maxchar,
                                      template=template)

        if self._single_group:
            for d, ax in zip(self.name_dicts.flat, self.axes.flat):
                # Only label the ones with data
                if d is not None:
                    coord, value = list(d.items()).pop()
                    title = nicetitle(coord, value, maxchar=maxchar)
                    ax.set_title(title, **kwargs)
        else:
            # The row titles on the right edge of the grid
            for ax, row_name in zip(self.axes[:, -1], self.row_names):
                title = nicetitle(coord=self._row_var, value=row_name,
                                  maxchar=maxchar)
                ax.annotate(title, xy=(1.02, .5), xycoords="axes fraction",
                            rotation=270, ha="left", va="center", **kwargs)

            # The column titles on the top row
            for ax, col_name in zip(self.axes[0, :], self.col_names):
                title = nicetitle(coord=self._col_var, value=col_name,
                                  maxchar=maxchar)
                ax.set_title(title, **kwargs)

        return self

Response: Draw titles on the grid and the grid margins.