Instruction:
Write a Python 3 function that can
retrieve pandas object stored in file optionally based on where applet.

Response:
def select(self, key, where=None, start=None, stop=None, columns=None,
               iterator=False, chunksize=None, auto_close=False, **kwargs):
        """
        Retrieve pandas object stored in file, optionally based on where
        criteria

        Parameters
        ----------
        key : object
        where : list of Term (or convertible) objects, optional
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection
        columns : a list of columns that if not None, will limit the return
            columns
        iterator : boolean, return an iterator, default False
        chunksize : nrows to include in iteration, return an iterator
        auto_close : boolean, should automatically close the store when
            finished, default is False

        Returns
        -------
        The selected object
        """
        group = self.get_node(key)
        if group is None:
            raise KeyError('No object named {key} in the file'.format(key=key))

        # create the storer and axes
        where = _ensure_term(where, scope_level=1)
        s = self._create_storer(group)
        s.infer_axes()

        # function to call on iteration
        def func(_start, _stop, _where):
            return s.read(start=_start, stop=_stop,
                          where=_where,
                          columns=columns)

        # create the iterator
        it = TableIterator(self, s, func, where=where, nrows=s.nrows,
                           start=start, stop=stop, iterator=iterator,
                           chunksize=chunksize, auto_close=auto_close)

        return it.get_result()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def select_as_coordinates(
            self, key, where=None, start=None, stop=None, **kwargs):
        """
        return the selection as an Index

        Parameters
        ----------
        key : object
        where : list of Term (or convertible) objects, optional
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection
        """
        where = _ensure_term(where, scope_level=1)
        return self.get_storer(key).read_coordinates(where=where, start=start,
                                                     stop=stop, **kwargs)

Response:
return the selection as an Index
Taxonomy


Instruction:
Here you have a function in Python 3, explain what it does
def select_column(self, key, column, **kwargs):
        return self.get_storer(key).read_column(column=column, **kwargs)

Response:
This is generally only useful to use to
           . select_column


Instruction:
Write a Python 3 function for
retrieving pandas objects from multiple tables.

Response:
def select_as_multiple(self, keys, where=None, selector=None, columns=None,
                           start=None, stop=None, iterator=False,
                           chunksize=None, auto_close=False, **kwargs):
        """ Retrieve pandas objects from multiple tables

        Parameters
        ----------
        keys : a list of the tables
        selector : the table to apply the where criteria (defaults to keys[0]
            if not supplied)
        columns : the columns I want back
        start : integer (defaults to None), row number to start selection
        stop  : integer (defaults to None), row number to stop selection
        iterator : boolean, return an iterator, default False
        chunksize : nrows to include in iteration, return an iterator

        Exceptions
        ----------
        raises KeyError if keys or selector is not found or keys is empty
        raises TypeError if keys is not a list or tuple
        raises ValueError if the tables are not ALL THE SAME DIMENSIONS
        """

        # default to single select
        where = _ensure_term(where, scope_level=1)
        if isinstance(keys, (list, tuple)) and len(keys) == 1:
            keys = keys[0]
        if isinstance(keys, str):
            return self.select(key=keys, where=where, columns=columns,
                               start=start, stop=stop, iterator=iterator,
                               chunksize=chunksize, **kwargs)

        if not isinstance(keys, (list, tuple)):
            raise TypeError("keys must be a list/tuple")

        if not len(keys):
            raise ValueError("keys must have a non-zero length")

        if selector is None:
            selector = keys[0]

        # collect the tables
        tbls = [self.get_storer(k) for k in keys]
        s = self.get_storer(selector)

        # validate rows
        nrows = None
        for t, k in itertools.chain([(s, selector)], zip(tbls, keys)):
            if t is None:
                raise KeyError("Invalid table [{key}]".format(key=k))
            if not t.is_table:
                raise TypeError(
                    "object [{obj}] is not a table, and cannot be used in all "
                    "select as multiple".format(obj=t.pathname)
                )

            if nrows is None:
                nrows = t.nrows
            elif t.nrows != nrows:
                raise ValueError(
                    "all tables must have exactly the same nrows!")

        # axis is the concentation axes
        axis = list({t.non_index_axes[0][0] for t in tbls})[0]

        def func(_start, _stop, _where):

            # retrieve the objs, _where is always passed as a set of
            # coordinates here
            objs = [t.read(where=_where, columns=columns, start=_start,
                           stop=_stop, **kwargs) for t in tbls]

            # concat and return
            return concat(objs, axis=axis,
                          verify_integrity=False)._consolidate()

        # create the iterator
        it = TableIterator(self, s, func, where=where, nrows=nrows,
                           start=start, stop=stop, iterator=iterator,
                           chunksize=chunksize, auto_close=auto_close)

        return it.get_result(coordinates=True)


Instruction:
Implement a Python 3 function for
storing object in HDFStore with optional format

Response:
def put(self, key, value, format=None, append=False, **kwargs):
        """
        Store object in HDFStore

        Parameters
        ----------
        key      : object
        value    : {Series, DataFrame}
        format   : 'fixed(f)|table(t)', default is 'fixed'
            fixed(f) : Fixed format
                       Fast writing/reading. Not-appendable, nor searchable
            table(t) : Table format
                       Write as a PyTables Table structure which may perform
                       worse but allow more flexible operations like searching
                       / selecting subsets of the data
        append   : boolean, default False
            This will force Table format, append the input data to the
            existing.
        data_columns : list of columns to create as data columns, or True to
            use all columns. See
            `here <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__ # noqa
        encoding : default None, provide an encoding for strings
        dropna   : boolean, default False, do not write an ALL nan row to
            the store settable by the option 'io.hdf.dropna_table'
        """
        if format is None:
            format = get_option("io.hdf.default_format") or 'fixed'
        kwargs = self._validate_format(format, kwargs)
        self._write_to_group(key, value, append=append, **kwargs)


Instruction:
Given the following Python 3 function, write the documentation
def remove(self, key, where=None, start=None, stop=None):
        where = _ensure_term(where, scope_level=1)
        try:
            s = self.get_storer(key)
        except KeyError:
            # the key is not a valid store, re-raising KeyError
            raise
        except Exception:

            if where is not None:
                raise ValueError(
                    "trying to remove a node with a non-None where clause!")

            # we are actually trying to remove a node (with children)
            s = self.get_node(key)
            if s is not None:
                s._f_remove(recursive=True)
                return None

        # remove the node
        if com._all_none(where, start, stop):
            s.group._f_remove(recursive=True)

        # delete from the table
        else:
            if not s.is_table:
                raise ValueError(
                    'can only remove with where on objects written as tables')
            return s.delete(where=where, start=start, stop=stop)

Response: Remove pandas object partially by specifying the where condition


Instruction:
Can you create a Python 3 function that
appends a value to a table in file.

Response:
def append(self, key, value, format=None, append=True, columns=None,
               dropna=None, **kwargs):
        """
        Append to Table in file. Node must already exist and be Table
        format.

        Parameters
        ----------
        key : object
        value : {Series, DataFrame}
        format : 'table' is the default
            table(t) : table format
                       Write as a PyTables Table structure which may perform
                       worse but allow more flexible operations like searching
                       / selecting subsets of the data
        append       : boolean, default True, append the input data to the
            existing
        data_columns :  list of columns, or True, default None
            List of columns to create as indexed data columns for on-disk
            queries, or True to use all columns. By default only the axes
            of the object are indexed. See `here
            <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__.
        min_itemsize : dict of columns that specify minimum string sizes
        nan_rep      : string to use as string nan represenation
        chunksize    : size to chunk the writing
        expectedrows : expected TOTAL row size of this table
        encoding     : default None, provide an encoding for strings
        dropna       : boolean, default False, do not write an ALL nan row to
            the store settable by the option 'io.hdf.dropna_table'

        Notes
        -----
        Does *not* check if data being appended overlaps with existing
        data in the table, so be careful
        """
        if columns is not None:
            raise TypeError("columns is not a supported keyword in append, "
                            "try data_columns")

        if dropna is None:
            dropna = get_option("io.hdf.dropna_table")
        if format is None:
            format = get_option("io.hdf.default_format") or 'table'
        kwargs = self._validate_format(format, kwargs)
        self._write_to_group(key, value, append=append, dropna=dropna,
                             **kwargs)


Instruction:
Implement a Python 3 function for
appending a value to a set of tables in a multi - level manner.

Response:
def append_to_multiple(self, d, value, selector, data_columns=None,
                           axes=None, dropna=False, **kwargs):
        """
        Append to multiple tables

        Parameters
        ----------
        d : a dict of table_name to table_columns, None is acceptable as the
            values of one node (this will get all the remaining columns)
        value : a pandas object
        selector : a string that designates the indexable table; all of its
            columns will be designed as data_columns, unless data_columns is
            passed, in which case these are used
        data_columns : list of columns to create as data columns, or True to
            use all columns
        dropna : if evaluates to True, drop rows from all tables if any single
                 row in each table has all NaN. Default False.

        Notes
        -----
        axes parameter is currently not accepted

        """
        if axes is not None:
            raise TypeError("axes is currently not accepted as a parameter to"
                            " append_to_multiple; you can create the "
                            "tables independently instead")

        if not isinstance(d, dict):
            raise ValueError(
                "append_to_multiple must have a dictionary specified as the "
                "way to split the value"
            )

        if selector not in d:
            raise ValueError(
                "append_to_multiple requires a selector that is in passed dict"
            )

        # figure out the splitting axis (the non_index_axis)
        axis = list(set(range(value.ndim)) - set(_AXES_MAP[type(value)]))[0]

        # figure out how to split the value
        remain_key = None
        remain_values = []
        for k, v in d.items():
            if v is None:
                if remain_key is not None:
                    raise ValueError(
                        "append_to_multiple can only have one value in d that "
                        "is None"
                    )
                remain_key = k
            else:
                remain_values.extend(v)
        if remain_key is not None:
            ordered = value.axes[axis]
            ordd = ordered.difference(Index(remain_values))
            ordd = sorted(ordered.get_indexer(ordd))
            d[remain_key] = ordered.take(ordd)

        # data_columns
        if data_columns is None:
            data_columns = d[selector]

        # ensure rows are synchronized across the tables
        if dropna:
            idxs = (value[cols].dropna(how='all').index for cols in d.values())
            valid_index = next(idxs)
            for index in idxs:
                valid_index = valid_index.intersection(index)
            value = value.loc[valid_index]

        # append
        for k, v in d.items():
            dc = data_columns if k == selector else None

            # compute the val
            val = value.reindex(v, axis=axis)

            self.append(k, val, data_columns=dc, **kwargs)


Instruction:
Write a Python 3 function for
creating a pytables index on the table with the given key.

Response:
def create_table_index(self, key, **kwargs):
        """ Create a pytables index on the table
        Parameters
        ----------
        key : object (the node to index)

        Exceptions
        ----------
        raises if the node is not a table

        """

        # version requirements
        _tables()
        s = self.get_storer(key)
        if s is None:
            return

        if not s.is_table:
            raise TypeError(
                "cannot create table index on a Fixed format store")
        s.create_index(**kwargs)


Instruction:
Can you tell what is the following Python 3 function doing
def groups(self):
        _tables()
        self._check_if_open()
        return [
            g for g in self._handle.walk_groups()
            if (not isinstance(g, _table_mod.link.Link) and
                (getattr(g._v_attrs, 'pandas_type', None) or
                 getattr(g, 'table', None) or
                (isinstance(g, _table_mod.table.Table) and
                 g._v_name != 'table')))
        ]

Response:
return a list of all the top - level nodes that are not themselves a
        pandas storage object


Instruction:
Can you generate a brief explanation for the following Python 3 code
def walk(self, where="/"):
        _tables()
        self._check_if_open()
        for g in self._handle.walk_groups(where):
            if getattr(g._v_attrs, 'pandas_type', None) is not None:
                continue

            groups = []
            leaves = []
            for child in g._v_children.values():
                pandas_type = getattr(child._v_attrs, 'pandas_type', None)
                if pandas_type is None:
                    if isinstance(child, _table_mod.group.Group):
                        groups.append(child._v_name)
                else:
                    leaves.append(child._v_name)

            yield (g._v_pathname.rstrip('/'), groups, leaves)

Response: Walk the group hierarchy for pandas objects and return the group path subgroups and pandas object names for each group.


Instruction:
How would you explain what the following Python 3 function does
def get_node(self, key):
        self._check_if_open()
        try:
            if not key.startswith('/'):
                key = '/' + key
            return self._handle.get_node(self.root, key)
        except _table_mod.exceptions.NoSuchNodeError:
            return None

Response: get the node with the key


Instruction:
Can you create a Python 3 function that
returns the storer object for a key raise if not in the file

Response:
def get_storer(self, key):
        """ return the storer object for a key, raise if not in the file """
        group = self.get_node(key)
        if group is None:
            raise KeyError('No object named {key} in the file'.format(key=key))

        s = self._create_storer(group)
        s.infer_axes()
        return s


Instruction:
Given the following Python 3 function, write the documentation
def copy(self, file, mode='w', propindexes=True, keys=None, complib=None,
             complevel=None, fletcher32=False, overwrite=True):
        """ copy the existing store to a new file, upgrading in place

            Parameters
            ----------
            propindexes: restore indexes in copied file (defaults to True)
            keys       : list of keys to include in the copy (defaults to all)
            overwrite  : overwrite (remove and replace) existing nodes in the
                new store (default is True)
            mode, complib, complevel, fletcher32 same as in HDFStore.__init__

            Returns
            -------
            open file handle of the new store

        """
        new_store = HDFStore(
            file,
            mode=mode,
            complib=complib,
            complevel=complevel,
            fletcher32=fletcher32)
        if keys is None:
            keys = list(self.keys())
        if not isinstance(keys, (tuple, list)):
            keys = [keys]
        for k in keys:
            s = self.get_storer(k)
            if s is not None:

                if k in new_store:
                    if overwrite:
                        new_store.remove(k)

                data = self.select(k)
                if s.is_table:

                    index = False
                    if propindexes:
                        index = [a.name for a in s.axes if a.is_indexed]
                    new_store.append(
                        k, data, index=index,
                        data_columns=getattr(s, 'data_columns', None),
                        encoding=s.encoding
                    )
                else:
                    new_store.put(k, data, encoding=s.encoding)

        return new_store

Response: copy the existing store to a new file upgrading in place


Instruction:
Can you implement a function in Python 3 that
prints detailed information on the store.

Response:
def info(self):
        """
        Print detailed information on the store.

        .. versionadded:: 0.21.0
        """
        output = '{type}\nFile path: {path}\n'.format(
            type=type(self), path=pprint_thing(self._path))
        if self.is_open:
            lkeys = sorted(list(self.keys()))
            if len(lkeys):
                keys = []
                values = []

                for k in lkeys:
                    try:
                        s = self.get_storer(k)
                        if s is not None:
                            keys.append(pprint_thing(s.pathname or k))
                            values.append(
                                pprint_thing(s or 'invalid_HDFStore node'))
                    except Exception as detail:
                        keys.append(k)
                        values.append(
                            "[invalid_HDFStore node: {detail}]".format(
                                detail=pprint_thing(detail)))

                output += adjoin(12, keys, values)
            else:
                output += 'Empty'
        else:
            output += "File is CLOSED"

        return output


Instruction:
Here you have a function in Python 3, explain what it does
def _validate_format(self, format, kwargs):
        kwargs = kwargs.copy()

        # validate
        try:
            kwargs['format'] = _FORMAT_MAP[format.lower()]
        except KeyError:
            raise TypeError("invalid HDFStore format specified [{0}]"
                            .format(format))

        return kwargs

Response: validate / deprecate formats; return the new kwargs


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _create_storer(self, group, format=None, value=None, append=False,
                       **kwargs):
        """ return a suitable class to operate """

        def error(t):
            raise TypeError(
                "cannot properly create the storer for: [{t}] [group->"
                "{group},value->{value},format->{format},append->{append},"
                "kwargs->{kwargs}]".format(t=t, group=group,
                                           value=type(value), format=format,
                                           append=append, kwargs=kwargs))

        pt = _ensure_decoded(getattr(group._v_attrs, 'pandas_type', None))
        tt = _ensure_decoded(getattr(group._v_attrs, 'table_type', None))

        # infer the pt from the passed value
        if pt is None:
            if value is None:

                _tables()
                if (getattr(group, 'table', None) or
                        isinstance(group, _table_mod.table.Table)):
                    pt = 'frame_table'
                    tt = 'generic_table'
                else:
                    raise TypeError(
                        "cannot create a storer if the object is not existing "
                        "nor a value are passed")
            else:

                try:
                    pt = _TYPE_MAP[type(value)]
                except KeyError:
                    error('_TYPE_MAP')

                # we are actually a table
                if format == 'table':
                    pt += '_table'

        # a storer node
        if 'table' not in pt:
            try:
                return globals()[_STORER_MAP[pt]](self, group, **kwargs)
            except KeyError:
                error('_STORER_MAP')

        # existing node (and must be a table)
        if tt is None:

            # if we are a writer, determine the tt
            if value is not None:

                if pt == 'series_table':
                    index = getattr(value, 'index', None)
                    if index is not None:
                        if index.nlevels == 1:
                            tt = 'appendable_series'
                        elif index.nlevels > 1:
                            tt = 'appendable_multiseries'
                elif pt == 'frame_table':
                    index = getattr(value, 'index', None)
                    if index is not None:
                        if index.nlevels == 1:
                            tt = 'appendable_frame'
                        elif index.nlevels > 1:
                            tt = 'appendable_multiframe'
                elif pt == 'wide_table':
                    tt = 'appendable_panel'
                elif pt == 'ndim_table':
                    tt = 'appendable_ndim'

            else:

                # distiguish between a frame/table
                tt = 'legacy_panel'
                try:
                    fields = group.table._v_attrs.fields
                    if len(fields) == 1 and fields[0] == 'value':
                        tt = 'legacy_frame'
                except IndexError:
                    pass

        try:
            return globals()[_TABLE_MAP[tt]](self, group, **kwargs)
        except KeyError:
            error('_TABLE_MAP')

Response: Create a new instance of the appropriate storer class.


Instruction:
How would you explain what the following Python 3 function does
def set_name(self, name, kind_attr=None):
        self.name = name
        self.kind_attr = kind_attr or "{name}_kind".format(name=name)
        if self.cname is None:
            self.cname = name

        return self

Response: set the name of this indexer


Instruction:
Here you have a function in Python 3, explain what it does
def set_pos(self, pos):
        self.pos = pos
        if pos is not None and self.typ is not None:
            self.typ._v_pos = pos
        return self

Response: set the position of this column in the Table


Instruction:
Given the following Python 3 function, write the documentation
def is_indexed(self):
        try:
            return getattr(self.table.cols, self.cname).is_indexed
        except AttributeError:
            False

Response: return whether I am an indexed column


Instruction:
Write a Python 3 function for
inferring this column from the table

Response:
def infer(self, handler):
        """infer this column from the table: create and return a new object"""
        table = handler.table
        new_self = self.copy()
        new_self.set_table(table)
        new_self.get_attr()
        new_self.read_metadata(handler)
        return new_self


Instruction:
Implement a Python 3 function for
converting the values from this selection to the index instance

Response:
def convert(self, values, nan_rep, encoding, errors):
        """ set the values from this selection: take = take ownership """

        # values is a recarray
        if values.dtype.fields is not None:
            values = values[self.cname]

        values = _maybe_convert(values, self.kind, encoding, errors)

        kwargs = dict()
        if self.freq is not None:
            kwargs['freq'] = _ensure_decoded(self.freq)
        if self.index_name is not None:
            kwargs['name'] = _ensure_decoded(self.index_name)
        # making an Index instance could throw a number of different errors
        try:
            self.values = Index(values, **kwargs)
        except Exception:  # noqa: E722

            # if the output freq is different that what we recorded,
            # it should be None (see also 'doc example part 2')
            if 'freq' in kwargs:
                kwargs['freq'] = None
            self.values = Index(values, **kwargs)

        self.values = _set_tz(self.values, self.tz)

        return self


Instruction:
Explain what the following Python 3 code does
def validate_col(self, itemsize=None):

        # validate this column for string truncation (or reset to the max size)
        if _ensure_decoded(self.kind) == 'string':
            c = self.col
            if c is not None:
                if itemsize is None:
                    itemsize = self.itemsize
                if c.itemsize < itemsize:
                    raise ValueError(
                        "Trying to store a string with len [{itemsize}] in "
                        "[{cname}] column but\nthis column has a limit of "
                        "[{c_itemsize}]!\nConsider using min_itemsize to "
                        "preset the sizes on these columns".format(
                            itemsize=itemsize, cname=self.cname,
                            c_itemsize=c.itemsize))
                return c.itemsize

        return None

Response: validate this column return the compared against itemsize


Instruction:
Write a Python 3 script to
set the info for this indexable with the key - value pair

Response:
def update_info(self, info):
        """ set/update the info for this indexable with the key/value
            if there is a conflict raise/warn as needed """

        for key in self._info_fields:

            value = getattr(self, key, None)
            idx = _get_info(info, self.name)

            existing_value = idx.get(key)
            if key in idx and value is not None and existing_value != value:

                # frequency/name just warn
                if key in ['freq', 'index_name']:
                    ws = attribute_conflict_doc % (key, existing_value, value)
                    warnings.warn(ws, AttributeConflictWarning, stacklevel=6)

                    # reset
                    idx[key] = None
                    setattr(self, key, None)

                else:
                    raise ValueError(
                        "invalid info for [{name}] for [{key}], "
                        "existing_value [{existing_value}] conflicts with "
                        "new value [{value}]".format(
                            name=self.name, key=key,
                            existing_value=existing_value, value=value))
            else:
                if value is not None or existing_value is not None:
                    idx[key] = value

        return self


Instruction:
Create a Python 3 function for
setting my state from the passed info

Response:
def set_info(self, info):
        """ set my state from the passed info """
        idx = info.get(self.name)
        if idx is not None:
            self.__dict__.update(idx)


Instruction:
Here you have a function in Python 3, explain what it does
def validate_metadata(self, handler):
        if self.meta == 'category':
            new_metadata = self.metadata
            cur_metadata = handler.read_metadata(self.cname)
            if (new_metadata is not None and cur_metadata is not None and
                    not array_equivalent(new_metadata, cur_metadata)):
                raise ValueError("cannot append a categorical with "
                                 "different categories to the existing")

Response: validate that the metadata of the current object is not changed the categories


Instruction:
How would you implement a function in Python 3 that
sets the meta data for this object

Response:
def write_metadata(self, handler):
        """ set the meta data """
        if self.metadata is not None:
            handler.write_metadata(self.cname, self.metadata)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def convert(self, values, nan_rep, encoding, errors):

        self.values = Int64Index(np.arange(self.table.nrows))
        return self

Response: convert the values from this selection to Int64Index


Instruction:
Make a summary of the following Python 3 code
def create_for_block(
            cls, i=None, name=None, cname=None, version=None, **kwargs):
        """ return a new datacol with the block i """

        if cname is None:
            cname = name or 'values_block_{idx}'.format(idx=i)
        if name is None:
            name = cname

        # prior to 0.10.1, we named values blocks like: values_block_0 an the
        # name values_0
        try:
            if version[0] == 0 and version[1] <= 10 and version[2] == 0:
                m = re.search(r"values_block_(\d+)", name)
                if m:
                    name = "values_{group}".format(group=m.groups()[0])
        except IndexError:
            pass

        return cls(name=name, cname=cname, **kwargs)

Response: create a new datacol with the block i


Instruction:
Can you tell what is the following Python 3 function doing
def set_atom(self, block, block_items, existing_col, min_itemsize,
                 nan_rep, info, encoding=None, errors='strict'):
        """ create and setup my atom from the block b """

        self.values = list(block_items)

        # short-cut certain block types
        if block.is_categorical:
            return self.set_atom_categorical(block, items=block_items,
                                             info=info)
        elif block.is_datetimetz:
            return self.set_atom_datetime64tz(block, info=info)
        elif block.is_datetime:
            return self.set_atom_datetime64(block)
        elif block.is_timedelta:
            return self.set_atom_timedelta64(block)
        elif block.is_complex:
            return self.set_atom_complex(block)

        dtype = block.dtype.name
        inferred_type = lib.infer_dtype(block.values, skipna=False)

        if inferred_type == 'date':
            raise TypeError(
                "[date] is not implemented as a table column")
        elif inferred_type == 'datetime':
            # after 8260
            # this only would be hit for a mutli-timezone dtype
            # which is an error

            raise TypeError(
                "too many timezones in this block, create separate "
                "data columns"
            )
        elif inferred_type == 'unicode':
            raise TypeError(
                "[unicode] is not implemented as a table column")

        # this is basically a catchall; if say a datetime64 has nans then will
        # end up here ###
        elif inferred_type == 'string' or dtype == 'object':
            self.set_atom_string(
                block, block_items,
                existing_col,
                min_itemsize,
                nan_rep,
                encoding,
                errors)

        # set as a data block
        else:
            self.set_atom_data(block)

Response: set the atom from the block b


Instruction:
Create a Python 3 function to
return the PyTables column class for this column

Response:
def get_atom_coltype(self, kind=None):
        """ return the PyTables column class for this column """
        if kind is None:
            kind = self.kind
        if self.kind.startswith('uint'):
            col_name = "UInt{name}Col".format(name=kind[4:])
        else:
            col_name = "{name}Col".format(name=kind.capitalize())

        return getattr(_tables(), col_name)


Instruction:
Make a summary of the following Python 3 code
def validate_attr(self, append):
        if append:
            existing_fields = getattr(self.attrs, self.kind_attr, None)
            if (existing_fields is not None and
                    existing_fields != list(self.values)):
                raise ValueError("appended items do not match existing items"
                                 " in table!")

            existing_dtype = getattr(self.attrs, self.dtype_attr, None)
            if (existing_dtype is not None and
                    existing_dtype != self.dtype):
                raise ValueError("appended items dtype do not match existing "
                                 "items dtype in table!")

Response: validate that we have the same order as the existing & same dtype


Instruction:
Create a Python 3 function for
converting the data from this selection to the correct dtype

Response:
def convert(self, values, nan_rep, encoding, errors):
        """set the data from this selection (and convert to the correct dtype
        if we can)
        """

        # values is a recarray
        if values.dtype.fields is not None:
            values = values[self.cname]

        self.set_data(values)

        # use the meta if needed
        meta = _ensure_decoded(self.meta)

        # convert to the correct dtype
        if self.dtype is not None:
            dtype = _ensure_decoded(self.dtype)

            # reverse converts
            if dtype == 'datetime64':

                # recreate with tz if indicated
                self.data = _set_tz(self.data, self.tz, coerce=True)

            elif dtype == 'timedelta64':
                self.data = np.asarray(self.data, dtype='m8[ns]')
            elif dtype == 'date':
                try:
                    self.data = np.asarray(
                        [date.fromordinal(v) for v in self.data], dtype=object)
                except ValueError:
                    self.data = np.asarray(
                        [date.fromtimestamp(v) for v in self.data],
                        dtype=object)
            elif dtype == 'datetime':
                self.data = np.asarray(
                    [datetime.fromtimestamp(v) for v in self.data],
                    dtype=object)

            elif meta == 'category':

                # we have a categorical
                categories = self.metadata
                codes = self.data.ravel()

                # if we have stored a NaN in the categories
                # then strip it; in theory we could have BOTH
                # -1s in the codes and nulls :<
                if categories is None:
                    # Handle case of NaN-only categorical columns in which case
                    # the categories are an empty array; when this is stored,
                    # pytables cannot write a zero-len array, so on readback
                    # the categories would be None and `read_hdf()` would fail.
                    categories = Index([], dtype=np.float64)
                else:
                    mask = isna(categories)
                    if mask.any():
                        categories = categories[~mask]
                        codes[codes != -1] -= mask.astype(int).cumsum().values

                self.data = Categorical.from_codes(codes,
                                                   categories=categories,
                                                   ordered=self.ordered)

            else:

                try:
                    self.data = self.data.astype(dtype, copy=False)
                except TypeError:
                    self.data = self.data.astype('O', copy=False)

        # convert nans / decode
        if _ensure_decoded(self.kind) == 'string':
            self.data = _unconvert_string_array(
                self.data, nan_rep=nan_rep, encoding=encoding, errors=errors)

        return self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_attr(self):
        self.values = getattr(self.attrs, self.kind_attr, None)
        self.dtype = getattr(self.attrs, self.dtype_attr, None)
        self.meta = getattr(self.attrs, self.meta_attr, None)
        self.set_kind()

Response: get the data for this column


Instruction:
Write a Python 3 script for
setting the data for this column

Response:
def set_attr(self):
        """ set the data for this column """
        setattr(self.attrs, self.kind_attr, self.values)
        setattr(self.attrs, self.meta_attr, self.meta)
        if self.dtype is not None:
            setattr(self.attrs, self.dtype_attr, self.dtype)


Instruction:
How would you implement a function in Python 3 that
computes and set our version

Response:
def set_version(self):
        """ compute and set our version """
        version = _ensure_decoded(
            getattr(self.group._v_attrs, 'pandas_version', None))
        try:
            self.version = tuple(int(x) for x in version.split('.'))
            if len(self.version) == 2:
                self.version = self.version + (0,)
        except AttributeError:
            self.version = (0, 0, 0)


Instruction:
Create a Python 3 function for
setting my pandas type & version

Response:
def set_object_info(self):
        """ set my pandas type & version """
        self.attrs.pandas_type = str(self.pandas_kind)
        self.attrs.pandas_version = str(_version)
        self.set_version()


Instruction:
Write a Python 3 script for
inferring the axes of my storer return a boolean indicating if we have a valid storer

Response:
def infer_axes(self):
        """ infer the axes of my storer
              return a boolean indicating if we have a valid storer or not """

        s = self.storable
        if s is None:
            return False
        self.get_attrs()
        return True


Instruction:
Implement a function in Python 3 to
delete a node from the store

Response:
def delete(self, where=None, start=None, stop=None, **kwargs):
        """
        support fully deleting the node in its entirety (only) - where
        specification must be None
        """
        if com._all_none(where, start, stop):
            self._handle.remove_node(self.group, recursive=True)
            return None

        raise TypeError("cannot delete on an abstract storer")


Instruction:
Can you implement a function in Python 3 that
validates that the table keywords are passed in kwargs and return the kwargs

Response:
def validate_read(self, kwargs):
        """
        remove table keywords from kwargs and return
        raise if any keywords are passed which are not-None
        """
        kwargs = copy.copy(kwargs)

        columns = kwargs.pop('columns', None)
        if columns is not None:
            raise TypeError("cannot pass a column specification when reading "
                            "a Fixed format store. this store must be "
                            "selected in its entirety")
        where = kwargs.pop('where', None)
        if where is not None:
            raise TypeError("cannot pass a where specification when reading "
                            "from a Fixed format store. this store must be "
                            "selected in its entirety")
        return kwargs


Instruction:
Can you generate the documentation for the following Python 3 function
def set_attrs(self):
        self.attrs.encoding = self.encoding
        self.attrs.errors = self.errors

Response: set our object attributes


Instruction:
Write a Python 3 function for
reading an array for the specified node

Response:
def read_array(self, key, start=None, stop=None):
        """ read an array for the specified node (off of group """
        import tables
        node = getattr(self.group, key)
        attrs = node._v_attrs

        transposed = getattr(attrs, 'transposed', False)

        if isinstance(node, tables.VLArray):
            ret = node[0][start:stop]
        else:
            dtype = getattr(attrs, 'value_type', None)
            shape = getattr(attrs, 'shape', None)

            if shape is not None:
                # length 0 axis
                ret = np.empty(shape, dtype=dtype)
            else:
                ret = node[start:stop]

            if dtype == 'datetime64':

                # reconstruct a timezone if indicated
                ret = _set_tz(ret, getattr(attrs, 'tz', None), coerce=True)

            elif dtype == 'timedelta64':
                ret = np.asarray(ret, dtype='m8[ns]')

        if transposed:
            return ret.T
        else:
            return ret


Instruction:
Implement a function in Python 3 to
write an empty array

Response:
def write_array_empty(self, key, value):
        """ write a 0-len array """

        # ugly hack for length 0 axes
        arr = np.empty((1,) * value.ndim)
        self._handle.create_array(self.group, key, arr)
        getattr(self.group, key)._v_attrs.value_type = str(value.dtype)
        getattr(self.group, key)._v_attrs.shape = value.shape


Instruction:
Make a summary of the following Python 3 code
def validate_read(self, kwargs):
        kwargs = super().validate_read(kwargs)
        if 'start' in kwargs or 'stop' in kwargs:
            raise NotImplementedError("start and/or stop are not supported "
                                      "in fixed Sparse reading")
        return kwargs

Response: Validate that start and stop keywords are not None


Instruction:
Given the following Python 3 function, write the documentation
def write(self, obj, **kwargs):
        super().write(obj, **kwargs)
        for name, ss in obj.items():
            key = 'sparse_series_{name}'.format(name=name)
            if key not in self.group._v_children:
                node = self._handle.create_group(self.group, key)
            else:
                node = getattr(self.group, key)
            s = SparseSeriesFixed(self.parent, node)
            s.write(ss)
        self.attrs.default_fill_value = obj.default_fill_value
        self.attrs.default_kind = obj.default_kind
        self.write_index('columns', obj.columns)

Response: write it as a collection of individual sparse series


Instruction:
Create a Python 3 function to
validate against an existing table

Response:
def validate(self, other):
        """ validate against an existing table """
        if other is None:
            return

        if other.table_type != self.table_type:
            raise TypeError(
                "incompatible table_type with existing "
                "[{other} - {self}]".format(
                    other=other.table_type, self=self.table_type))

        for c in ['index_axes', 'non_index_axes', 'values_axes']:
            sv = getattr(self, c, None)
            ov = getattr(other, c, None)
            if sv != ov:

                # show the error for the specific axes
                for i, sax in enumerate(sv):
                    oax = ov[i]
                    if sax != oax:
                        raise ValueError(
                            "invalid combinate of [{c}] on appending data "
                            "[{sax}] vs current table [{oax}]".format(
                                c=c, sax=sax, oax=oax))

                # should never get here
                raise Exception(
                    "invalid combinate of [{c}] on appending data [{sv}] vs "
                    "current table [{ov}]".format(c=c, sv=sv, ov=ov))


Instruction:
How would you explain what the following Python 3 function does
def validate_metadata(self, existing):
        self.metadata = [
            c.name for c in self.values_axes if c.metadata is not None]

Response: create and validate metadata


Instruction:
Given the following Python 3 function, write the documentation
def validate_multiindex(self, obj):
        levels = [l if l is not None else "level_{0}".format(i)
                  for i, l in enumerate(obj.index.names)]
        try:
            return obj.reset_index(), levels
        except ValueError:
            raise ValueError("duplicate names/columns in the multi-index when "
                             "storing as a table")

Response:
validate that we can store the multi - index ; reset and return the the
        new object


Instruction:
Can you generate a brief explanation for the following Python 3 code
def nrows_expected(self):
        return np.prod([i.cvalues.shape[0] for i in self.index_axes])

Response: compute the expected nrows


Instruction:
Create a Python 3 function to
return a tuple of my permutated axes non_indexable at the front

Response:
def data_orientation(self):
        """return a tuple of my permutated axes, non_indexable at the front"""
        return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes],
                                     [int(a.axis) for a in self.index_axes]))


Instruction:
Implement a Python 3 function for
returning a dict of the kinds allowable columns for this object

Response:
def queryables(self):
        """ return a dict of the kinds allowable columns for this object """

        # compute the values_axes queryables
        return dict(
            [(a.cname, a) for a in self.index_axes] +
            [(self.storage_obj_type._AXIS_NAMES[axis], None)
             for axis, values in self.non_index_axes] +
            [(v.cname, v) for v in self.values_axes
             if v.name in set(self.data_columns)]
        )


Instruction:
Make a summary of the following Python 3 code
def _get_metadata_path(self, key):
        return "{group}/meta/{key}/meta".format(group=self.group._v_pathname,
                                                key=key)

Response: return the metadata pathname for this key


Instruction:
Write a Python 3 function that can
write out a meta data array to the key as a fixed - format Series

Response:
def write_metadata(self, key, values):
        """
        write out a meta data array to the key as a fixed-format Series

        Parameters
        ----------
        key : string
        values : ndarray

        """
        values = Series(values)
        self.parent.put(self._get_metadata_path(key), values, format='table',
                        encoding=self.encoding, errors=self.errors,
                        nan_rep=self.nan_rep)


Instruction:
Write a Python 3 script for
returning the meta data array for this key

Response:
def read_metadata(self, key):
        """ return the meta data array for this key """
        if getattr(getattr(self.group, 'meta', None), key, None) is not None:
            return self.parent.select(self._get_metadata_path(key))
        return None


Instruction:
Can you tell what is the following Python 3 function doing
def set_attrs(self):
        self.attrs.table_type = str(self.table_type)
        self.attrs.index_cols = self.index_cols()
        self.attrs.values_cols = self.values_cols()
        self.attrs.non_index_axes = self.non_index_axes
        self.attrs.data_columns = self.data_columns
        self.attrs.nan_rep = self.nan_rep
        self.attrs.encoding = self.encoding
        self.attrs.errors = self.errors
        self.attrs.levels = self.levels
        self.attrs.metadata = self.metadata
        self.set_info()

Response: set our table type & indexables


Instruction:
How would you explain what the following Python 3 function does
def validate_version(self, where=None):
        if where is not None:
            if (self.version[0] <= 0 and self.version[1] <= 10 and
                    self.version[2] < 1):
                ws = incompatibility_doc % '.'.join(
                    [str(x) for x in self.version])
                warnings.warn(ws, IncompatibilityWarning)

Response: Validate that the version of the resource is valid.


Instruction:
Write a Python 3 script to
validate the min_itemisze has the items that are not in the data_columns

Response:
def validate_min_itemsize(self, min_itemsize):
        """validate the min_itemisze doesn't contain items that are not in the
        axes this needs data_columns to be defined
        """
        if min_itemsize is None:
            return
        if not isinstance(min_itemsize, dict):
            return

        q = self.queryables()
        for k, v in min_itemsize.items():

            # ok, apply generally
            if k == 'values':
                continue
            if k not in q:
                raise ValueError(
                    "min_itemsize has the key [{key}] which is not an axis or "
                    "data_column".format(key=k))


Instruction:
Explain what the following Python 3 code does
def indexables(self):
        if self._indexables is None:

            self._indexables = []

            # index columns
            self._indexables.extend([
                IndexCol(name=name, axis=axis, pos=i)
                for i, (axis, name) in enumerate(self.attrs.index_cols)
            ])

            # values columns
            dc = set(self.data_columns)
            base_pos = len(self._indexables)

            def f(i, c):
                klass = DataCol
                if c in dc:
                    klass = DataIndexableCol
                return klass.create_for_block(i=i, name=c, pos=base_pos + i,
                                              version=self.version)

            self._indexables.extend(
                [f(i, c) for i, c in enumerate(self.attrs.values_cols)])

        return self._indexables

Response: create the indexables if they don t exist


Instruction:
Can you generate the documentation for the following Python 3 function
def create_index(self, columns=None, optlevel=None, kind=None):

        if not self.infer_axes():
            return
        if columns is False:
            return

        # index all indexables and data_columns
        if columns is None or columns is True:
            columns = [a.cname for a in self.axes if a.is_data_indexable]
        if not isinstance(columns, (tuple, list)):
            columns = [columns]

        kw = dict()
        if optlevel is not None:
            kw['optlevel'] = optlevel
        if kind is not None:
            kw['kind'] = kind

        table = self.table
        for c in columns:
            v = getattr(table.cols, c, None)
            if v is not None:

                # remove the index if the kind/optlevel have changed
                if v.is_indexed:
                    index = v.index
                    cur_optlevel = index.optlevel
                    cur_kind = index.kind

                    if kind is not None and cur_kind != kind:
                        v.remove_index()
                    else:
                        kw['kind'] = cur_kind

                    if optlevel is not None and cur_optlevel != optlevel:
                        v.remove_index()
                    else:
                        kw['optlevel'] = cur_optlevel

                # create the index
                if not v.is_indexed:
                    if v.type.startswith('complex'):
                        raise TypeError(
                            'Columns containing complex values can be stored '
                            'but cannot'
                            ' be indexed when using table format. Either use '
                            'fixed format, set index=False, or do not include '
                            'the columns containing complex values to '
                            'data_columns when initializing the table.')
                    v.create_index(**kw)

Response: Create a pytables index on the specified columns.


Instruction:
Create a Python 3 function to
create and return the axes sniffed from the table return True if success otherwise False

Response:
def read_axes(self, where, **kwargs):
        """create and return the axes sniffed from the table: return boolean
        for success
        """

        # validate the version
        self.validate_version(where)

        # infer the data kind
        if not self.infer_axes():
            return False

        # create the selection
        self.selection = Selection(self, where=where, **kwargs)
        values = self.selection.select()

        # convert the data
        for a in self.axes:
            a.set_info(self.info)
            a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding,
                      errors=self.errors)

        return True


Instruction:
How would you explain what the following Python 3 function does
def validate_data_columns(self, data_columns, min_itemsize):

        if not len(self.non_index_axes):
            return []

        axis, axis_labels = self.non_index_axes[0]
        info = self.info.get(axis, dict())
        if info.get('type') == 'MultiIndex' and data_columns:
            raise ValueError("cannot use a multi-index on axis [{0}] with "
                             "data_columns {1}".format(axis, data_columns))

        # evaluate the passed data_columns, True == use all columns
        # take only valide axis labels
        if data_columns is True:
            data_columns = list(axis_labels)
        elif data_columns is None:
            data_columns = []

        # if min_itemsize is a dict, add the keys (exclude 'values')
        if isinstance(min_itemsize, dict):

            existing_data_columns = set(data_columns)
            data_columns.extend([
                k for k in min_itemsize.keys()
                if k != 'values' and k not in existing_data_columns
            ])

        # return valid columns in the order of our axis
        return [c for c in data_columns if c in axis_labels]

Response:
take the input data_columns and min_itemize and create a data
            columns spec


Instruction:
Write a Python 3 function that can
create and return the axes for the new leagcy tables

Response:
def create_axes(self, axes, obj, validate=True, nan_rep=None,
                    data_columns=None, min_itemsize=None, **kwargs):
        """ create and return the axes
        leagcy tables create an indexable column, indexable index,
        non-indexable fields

            Parameters:
            -----------
            axes: a list of the axes in order to create (names or numbers of
                the axes)
            obj : the object to create axes on
            validate: validate the obj against an existing object already
                written
            min_itemsize: a dict of the min size for a column in bytes
            nan_rep : a values to use for string column nan_rep
            encoding : the encoding for string values
            data_columns : a list of columns that we want to create separate to
                allow indexing (or True will force all columns)

        """

        # set the default axes if needed
        if axes is None:
            try:
                axes = _AXES_MAP[type(obj)]
            except KeyError:
                raise TypeError(
                    "cannot properly create the storer for: [group->{group},"
                    "value->{value}]".format(
                        group=self.group._v_name, value=type(obj)))

        # map axes to numbers
        axes = [obj._get_axis_number(a) for a in axes]

        # do we have an existing table (if so, use its axes & data_columns)
        if self.infer_axes():
            existing_table = self.copy()
            existing_table.infer_axes()
            axes = [a.axis for a in existing_table.index_axes]
            data_columns = existing_table.data_columns
            nan_rep = existing_table.nan_rep
            self.encoding = existing_table.encoding
            self.errors = existing_table.errors
            self.info = copy.copy(existing_table.info)
        else:
            existing_table = None

        # currently support on ndim-1 axes
        if len(axes) != self.ndim - 1:
            raise ValueError(
                "currently only support ndim-1 indexers in an AppendableTable")

        # create according to the new data
        self.non_index_axes = []
        self.data_columns = []

        # nan_representation
        if nan_rep is None:
            nan_rep = 'nan'

        self.nan_rep = nan_rep

        # create axes to index and non_index
        index_axes_map = dict()
        for i, a in enumerate(obj.axes):

            if i in axes:
                name = obj._AXIS_NAMES[i]
                index_axes_map[i] = _convert_index(
                    a, self.encoding, self.errors, self.format_type
                ).set_name(name).set_axis(i)
            else:

                # we might be able to change the axes on the appending data if
                # necessary
                append_axis = list(a)
                if existing_table is not None:
                    indexer = len(self.non_index_axes)
                    exist_axis = existing_table.non_index_axes[indexer][1]
                    if not array_equivalent(np.array(append_axis),
                                            np.array(exist_axis)):

                        # ahah! -> reindex
                        if array_equivalent(np.array(sorted(append_axis)),
                                            np.array(sorted(exist_axis))):
                            append_axis = exist_axis

                # the non_index_axes info
                info = _get_info(self.info, i)
                info['names'] = list(a.names)
                info['type'] = a.__class__.__name__

                self.non_index_axes.append((i, append_axis))

        # set axis positions (based on the axes)
        self.index_axes = [
            index_axes_map[a].set_pos(j).update_info(self.info)
            for j, a in enumerate(axes)
        ]
        j = len(self.index_axes)

        # check for column conflicts
        for a in self.axes:
            a.maybe_set_size(min_itemsize=min_itemsize)

        # reindex by our non_index_axes & compute data_columns
        for a in self.non_index_axes:
            obj = _reindex_axis(obj, a[0], a[1])

        def get_blk_items(mgr, blocks):
            return [mgr.items.take(blk.mgr_locs) for blk in blocks]

        # figure out data_columns and get out blocks
        block_obj = self.get_object(obj)._consolidate()
        blocks = block_obj._data.blocks
        blk_items = get_blk_items(block_obj._data, blocks)
        if len(self.non_index_axes):
            axis, axis_labels = self.non_index_axes[0]
            data_columns = self.validate_data_columns(
                data_columns, min_itemsize)
            if len(data_columns):
                mgr = block_obj.reindex(
                    Index(axis_labels).difference(Index(data_columns)),
                    axis=axis
                )._data

                blocks = list(mgr.blocks)
                blk_items = get_blk_items(mgr, blocks)
                for c in data_columns:
                    mgr = block_obj.reindex([c], axis=axis)._data
                    blocks.extend(mgr.blocks)
                    blk_items.extend(get_blk_items(mgr, mgr.blocks))

        # reorder the blocks in the same order as the existing_table if we can
        if existing_table is not None:
            by_items = {tuple(b_items.tolist()): (b, b_items)
                        for b, b_items in zip(blocks, blk_items)}
            new_blocks = []
            new_blk_items = []
            for ea in existing_table.values_axes:
                items = tuple(ea.values)
                try:
                    b, b_items = by_items.pop(items)
                    new_blocks.append(b)
                    new_blk_items.append(b_items)
                except (IndexError, KeyError):
                    raise ValueError(
                        "cannot match existing table structure for [{items}] "
                        "on appending data".format(
                            items=(','.join(pprint_thing(item) for
                                            item in items))))
            blocks = new_blocks
            blk_items = new_blk_items

        # add my values
        self.values_axes = []
        for i, (b, b_items) in enumerate(zip(blocks, blk_items)):

            # shape of the data column are the indexable axes
            klass = DataCol
            name = None

            # we have a data_column
            if (data_columns and len(b_items) == 1 and
                    b_items[0] in data_columns):
                klass = DataIndexableCol
                name = b_items[0]
                self.data_columns.append(name)

            # make sure that we match up the existing columns
            # if we have an existing table
            if existing_table is not None and validate:
                try:
                    existing_col = existing_table.values_axes[i]
                except (IndexError, KeyError):
                    raise ValueError(
                        "Incompatible appended table [{blocks}]"
                        "with existing table [{table}]".format(
                            blocks=blocks,
                            table=existing_table.values_axes))
            else:
                existing_col = None

            try:
                col = klass.create_for_block(
                    i=i, name=name, version=self.version)
                col.set_atom(block=b, block_items=b_items,
                             existing_col=existing_col,
                             min_itemsize=min_itemsize,
                             nan_rep=nan_rep,
                             encoding=self.encoding,
                             errors=self.errors,
                             info=self.info)
                col.set_pos(j)

                self.values_axes.append(col)
            except (NotImplementedError, ValueError, TypeError) as e:
                raise e
            except Exception as detail:
                raise Exception(
                    "cannot find the correct atom type -> "
                    "[dtype->{name},items->{items}] {detail!s}".format(
                        name=b.dtype.name, items=b_items, detail=detail))
            j += 1

        # validate our min_itemsize
        self.validate_min_itemsize(min_itemsize)

        # validate our metadata
        self.validate_metadata(existing_table)

        # validate the axes if we have an existing table
        if validate:
            self.validate(existing_table)


Instruction:
Can you implement a function in Python 3 that
processes axes and return the related record ID.

Response:
def process_axes(self, obj, columns=None):
        """ process axes filters """

        # make a copy to avoid side effects
        if columns is not None:
            columns = list(columns)

        # make sure to include levels if we have them
        if columns is not None and self.is_multi_index:
            for n in self.levels:
                if n not in columns:
                    columns.insert(0, n)

        # reorder by any non_index_axes & limit to the select columns
        for axis, labels in self.non_index_axes:
            obj = _reindex_axis(obj, axis, labels, columns)

        # apply the selection filters (but keep in the same order)
        if self.selection.filter is not None:
            for field, op, filt in self.selection.filter.format():

                def process_filter(field, filt):

                    for axis_name in obj._AXIS_NAMES.values():
                        axis_number = obj._get_axis_number(axis_name)
                        axis_values = obj._get_axis(axis_name)

                        # see if the field is the name of an axis
                        if field == axis_name:

                            # if we have a multi-index, then need to include
                            # the levels
                            if self.is_multi_index:
                                filt = filt.union(Index(self.levels))

                            takers = op(axis_values, filt)
                            return obj.loc._getitem_axis(takers,
                                                         axis=axis_number)

                        # this might be the name of a file IN an axis
                        elif field in axis_values:

                            # we need to filter on this dimension
                            values = ensure_index(getattr(obj, field).values)
                            filt = ensure_index(filt)

                            # hack until we support reversed dim flags
                            if isinstance(obj, DataFrame):
                                axis_number = 1 - axis_number
                            takers = op(values, filt)
                            return obj.loc._getitem_axis(takers,
                                                         axis=axis_number)

                    raise ValueError("cannot find the field [{field}] for "
                                     "filtering!".format(field=field))

                obj = process_filter(field, filt)

        return obj


Instruction:
How would you explain what the following Python 3 function does
def create_description(self, complib=None, complevel=None,
                           fletcher32=False, expectedrows=None):
        """ create the description of the table from the axes & values """

        # provided expected rows if its passed
        if expectedrows is None:
            expectedrows = max(self.nrows_expected, 10000)

        d = dict(name='table', expectedrows=expectedrows)

        # description from the axes & values
        d['description'] = {a.cname: a.typ for a in self.axes}

        if complib:
            if complevel is None:
                complevel = self._complevel or 9
            filters = _tables().Filters(
                complevel=complevel, complib=complib,
                fletcher32=fletcher32 or self._fletcher32)
            d['filters'] = filters
        elif self._filters is not None:
            d['filters'] = self._filters

        return d

Response: create the description of the table


Instruction:
Can you tell what is the following Python 3 function doing
def read_coordinates(self, where=None, start=None, stop=None, **kwargs):

        # validate the version
        self.validate_version(where)

        # infer the data kind
        if not self.infer_axes():
            return False

        # create the selection
        self.selection = Selection(
            self, where=where, start=start, stop=stop, **kwargs)
        coords = self.selection.select_coords()
        if self.selection.filter is not None:
            for field, op, filt in self.selection.filter.format():
                data = self.read_column(
                    field, start=coords.min(), stop=coords.max() + 1)
                coords = coords[
                    op(data.iloc[coords - coords.min()], filt).values]

        return Index(coords)

Response:
select coordinates from a table ; return the the
        coordinates object


Instruction:
How would you explain what the following Python 3 function does
def read_column(self, column, where=None, start=None, stop=None):

        # validate the version
        self.validate_version()

        # infer the data kind
        if not self.infer_axes():
            return False

        if where is not None:
            raise TypeError("read_column does not currently accept a where "
                            "clause")

        # find the axes
        for a in self.axes:
            if column == a.name:

                if not a.is_data_indexable:
                    raise ValueError(
                        "column [{column}] can not be extracted individually; "
                        "it is not data indexable".format(column=column))

                # column must be an indexable or a data column
                c = getattr(self.table.cols, column)
                a.set_info(self.info)
                return Series(_set_tz(a.convert(c[start:stop],
                                                nan_rep=self.nan_rep,
                                                encoding=self.encoding,
                                                errors=self.errors
                                                ).take_data(),
                                      a.tz, True), name=column)

        raise KeyError(
            "column [{column}] not found in the table".format(column=column))

Response:
return a single column from the table generally only indexables
        are interesting


Instruction:
Can you generate the documentation for the following Python 3 function
def read(self, where=None, columns=None, **kwargs):

        if not self.read_axes(where=where, **kwargs):
            return None

        raise NotImplementedError("Panel is removed in pandas 0.25.0")

Response: read the n indexable columns with an arbitrary number of data


Instruction:
How would you explain what the following Python 3 function does
def write_data(self, chunksize, dropna=False):

        names = self.dtype.names
        nrows = self.nrows_expected

        # if dropna==True, then drop ALL nan rows
        masks = []
        if dropna:

            for a in self.values_axes:

                # figure the mask: only do if we can successfully process this
                # column, otherwise ignore the mask
                mask = isna(a.data).all(axis=0)
                if isinstance(mask, np.ndarray):
                    masks.append(mask.astype('u1', copy=False))

        # consolidate masks
        if len(masks):
            mask = masks[0]
            for m in masks[1:]:
                mask = mask & m
            mask = mask.ravel()
        else:
            mask = None

        # broadcast the indexes if needed
        indexes = [a.cvalues for a in self.index_axes]
        nindexes = len(indexes)
        bindexes = []
        for i, idx in enumerate(indexes):

            # broadcast to all other indexes except myself
            if i > 0 and i < nindexes:
                repeater = np.prod(
                    [indexes[bi].shape[0] for bi in range(0, i)])
                idx = np.tile(idx, repeater)

            if i < nindexes - 1:
                repeater = np.prod([indexes[bi].shape[0]
                                    for bi in range(i + 1, nindexes)])
                idx = np.repeat(idx, repeater)

            bindexes.append(idx)

        # transpose the values so first dimension is last
        # reshape the values if needed
        values = [a.take_data() for a in self.values_axes]
        values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1))
                  for v in values]
        bvalues = []
        for i, v in enumerate(values):
            new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
            bvalues.append(values[i].reshape(new_shape))

        # write the chunks
        if chunksize is None:
            chunksize = 100000

        rows = np.empty(min(chunksize, nrows), dtype=self.dtype)
        chunks = int(nrows / chunksize) + 1
        for i in range(chunks):
            start_i = i * chunksize
            end_i = min((i + 1) * chunksize, nrows)
            if start_i >= end_i:
                break

            self.write_data_chunk(
                rows,
                indexes=[a[start_i:end_i] for a in bindexes],
                mask=mask[start_i:end_i] if mask is not None else None,
                values=[v[start_i:end_i] for v in bvalues])

Response: we form the data into a 2 - d including indexes values mask and write chunk - by - chunk


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_data_chunk(self, rows, indexes, mask, values):

        # 0 len
        for v in values:
            if not np.prod(v.shape):
                return

        try:
            nrows = indexes[0].shape[0]
            if nrows != len(rows):
                rows = np.empty(nrows, dtype=self.dtype)
            names = self.dtype.names
            nindexes = len(indexes)

            # indexes
            for i, idx in enumerate(indexes):
                rows[names[i]] = idx

            # values
            for i, v in enumerate(values):
                rows[names[i + nindexes]] = v

            # mask
            if mask is not None:
                m = ~mask.ravel().astype(bool, copy=False)
                if not m.all():
                    rows = rows[m]

        except Exception as detail:
            raise Exception(
                "cannot create row-data -> {detail}".format(detail=detail))

        try:
            if len(rows):
                self.table.append(rows)
                self.table.flush()
        except Exception as detail:
            raise TypeError(
                "tables cannot write this data -> {detail}".format(
                    detail=detail))

Response: Writes the data in a single chunk of the data table.


Instruction:
Can you tell what is the following Python 3 function doing
def write(self, obj, data_columns=None, **kwargs):
        if not isinstance(obj, DataFrame):
            name = obj.name or 'values'
            obj = DataFrame({name: obj}, index=obj.index)
            obj.columns = [name]
        return super().write(obj=obj, data_columns=obj.columns.tolist(),
                             **kwargs)

Response: write a single entry to the table


Instruction:
Write a Python 3 script to
write the object as a frame table

Response:
def write(self, obj, **kwargs):
        """ we are going to write this as a frame table """
        name = obj.name or 'values'
        obj, self.levels = self.validate_multiindex(obj)
        cols = list(self.levels)
        cols.append(name)
        obj.columns = cols
        return super().write(obj=obj, **kwargs)


Instruction:
Can you generate the documentation for the following Python 3 function
def indexables(self):
        if self._indexables is None:

            d = self.description

            # the index columns is just a simple index
            self._indexables = [GenericIndexCol(name='index', axis=0)]

            for i, n in enumerate(d._v_names):

                dc = GenericDataIndexableCol(
                    name=n, pos=i, values=[n], version=self.version)
                self._indexables.append(dc)

        return self._indexables

Response: create the indexables from the table description


Instruction:
Given the following Python 3 function, write the documentation
def generate(self, where):
        if where is None:
            return None

        q = self.table.queryables()
        try:
            return Expr(where, queryables=q, encoding=self.table.encoding)
        except NameError:
            # raise a nice message, suggesting that the user should use
            # data_columns
            raise ValueError(
                "The passed where expression: {0}\n"
                "            contains an invalid variable reference\n"
                "            all of the variable references must be a "
                "reference to\n"
                "            an axis (e.g. 'index' or 'columns'), or a "
                "data_column\n"
                "            The currently defined references are: {1}\n"
                .format(where, ','.join(q.keys()))
            )

Response: Generate a new instance of the class that is used to access the related object.


Instruction:
Can you tell what is the following Python 3 function doing
def select_coords(self):
        start, stop = self.start, self.stop
        nrows = self.table.nrows
        if start is None:
            start = 0
        elif start < 0:
            start += nrows
        if self.stop is None:
            stop = nrows
        elif stop < 0:
            stop += nrows

        if self.condition is not None:
            return self.table.table.get_where_list(self.condition.format(),
                                                   start=start, stop=stop,
                                                   sort=True)
        elif self.coordinates is not None:
            return self.coordinates

        return np.arange(start, stop)

Response: generate the selection of the coordinates of the related object


Instruction:
Can you generate the documentation for the following Python 3 function
def astype(self, dtype, copy=True):
        return np.array(self, dtype=dtype, copy=copy)

Response: Cast to a NumPy array with the specified dtype.


Instruction:
Here you have a function in Python 3, explain what it does
def argsort(self, ascending=True, kind='quicksort', *args, **kwargs):
        # Implementor note: You have two places to override the behavior of
        # argsort.
        # 1. _values_for_argsort : construct the values passed to np.argsort
        # 2. argsort : total control over sorting.
        ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs)
        values = self._values_for_argsort()
        result = np.argsort(values, kind=kind, **kwargs)
        if not ascending:
            result = result[::-1]
        return result

Response: Return the indices that would sort this array.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fillna(self, value=None, method=None, limit=None):
        from pandas.api.types import is_array_like
        from pandas.util._validators import validate_fillna_kwargs
        from pandas.core.missing import pad_1d, backfill_1d

        value, method = validate_fillna_kwargs(value, method)

        mask = self.isna()

        if is_array_like(value):
            if len(value) != len(self):
                raise ValueError("Length of 'value' does not match. Got ({}) "
                                 " expected {}".format(len(value), len(self)))
            value = value[mask]

        if mask.any():
            if method is not None:
                func = pad_1d if method == 'pad' else backfill_1d
                new_values = func(self.astype(object), limit=limit,
                                  mask=mask)
                new_values = self._from_sequence(new_values, dtype=self.dtype)
            else:
                # fill with value
                new_values = self.copy()
                new_values[mask] = value
        else:
            new_values = self.copy()
        return new_values

Response: Fill missing values with the specified value.


Instruction:
Can you implement a function in Python 3 that
shifts the array by desired number of periods.

Response:
def shift(
            self,
            periods: int = 1,
            fill_value: object = None,
    ) -> ABCExtensionArray:
        """
        Shift values by desired number.

        Newly introduced missing values are filled with
        ``self.dtype.na_value``.

        .. versionadded:: 0.24.0

        Parameters
        ----------
        periods : int, default 1
            The number of periods to shift. Negative values are allowed
            for shifting backwards.

        fill_value : object, optional
            The scalar value to use for newly introduced missing values.
            The default is ``self.dtype.na_value``

            .. versionadded:: 0.24.0

        Returns
        -------
        shifted : ExtensionArray

        Notes
        -----
        If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
        returned.

        If ``periods > len(self)``, then an array of size
        len(self) is returned, with all values filled with
        ``self.dtype.na_value``.
        """
        # Note: this implementation assumes that `self.dtype.na_value` can be
        # stored in an instance of your ExtensionArray with `self.dtype`.
        if not len(self) or periods == 0:
            return self.copy()

        if isna(fill_value):
            fill_value = self.dtype.na_value

        empty = self._from_sequence(
            [fill_value] * min(abs(periods), len(self)),
            dtype=self.dtype
        )
        if periods > 0:
            a = empty
            b = self[:-periods]
        else:
            a = self[abs(periods):]
            b = empty
        return self._concat_same_type([a, b])


Instruction:
How would you code a function in Python 3 to
compute the ExtensionArray of unique values.

Response:
def unique(self):
        """
        Compute the ExtensionArray of unique values.

        Returns
        -------
        uniques : ExtensionArray
        """
        from pandas import unique

        uniques = unique(self.astype(object))
        return self._from_sequence(uniques, dtype=self.dtype)


Instruction:
Explain what the following Python 3 code does
def searchsorted(self, value, side="left", sorter=None):
        # Note: the base tests provided by pandas only test the basics.
        # We do not test
        # 1. Values outside the range of the `data_for_sorting` fixture
        # 2. Values between the values in the `data_for_sorting` fixture
        # 3. Missing values.
        arr = self.astype(object)
        return arr.searchsorted(value, side=side, sorter=sorter)

Response: Return a sorted array of integers where each element in value is inserted into the corresponding array.


Instruction:
Can you write a function in Python 3 where it
returns an array and missing value suitable for factorization.

Response:
def _values_for_factorize(self) -> Tuple[np.ndarray, Any]:
        """
        Return an array and missing value suitable for factorization.

        Returns
        -------
        values : ndarray

            An array suitable for factorization. This should maintain order
            and be a supported dtype (Float64, Int64, UInt64, String, Object).
            By default, the extension array is cast to object dtype.
        na_value : object
            The value in `values` to consider missing. This will be treated
            as NA in the factorization routines, so it will be coded as
            `na_sentinal` and not included in `uniques`. By default,
            ``np.nan`` is used.

        Notes
        -----
        The values returned by this method are also used in
        :func:`pandas.util.hash_pandas_object`.
        """
        return self.astype(object), np.nan


Instruction:
Write a Python 3 function that can
return the internal factorization of the internal array.

Response:
def factorize(
            self,
            na_sentinel: int = -1,
    ) -> Tuple[np.ndarray, ABCExtensionArray]:
        """
        Encode the extension array as an enumerated type.

        Parameters
        ----------
        na_sentinel : int, default -1
            Value to use in the `labels` array to indicate missing values.

        Returns
        -------
        labels : ndarray
            An integer NumPy array that's an indexer into the original
            ExtensionArray.
        uniques : ExtensionArray
            An ExtensionArray containing the unique values of `self`.

            .. note::

               uniques will *not* contain an entry for the NA value of
               the ExtensionArray if there are any missing values present
               in `self`.

        See Also
        --------
        pandas.factorize : Top-level factorize method that dispatches here.

        Notes
        -----
        :meth:`pandas.factorize` offers a `sort` keyword as well.
        """
        # Impelmentor note: There are two ways to override the behavior of
        # pandas.factorize
        # 1. _values_for_factorize and _from_factorize.
        #    Specify the values passed to pandas' internal factorization
        #    routines, and how to convert from those values back to the
        #    original ExtensionArray.
        # 2. ExtensionArray.factorize.
        #    Complete control over factorization.
        from pandas.core.algorithms import _factorize_array

        arr, na_value = self._values_for_factorize()

        labels, uniques = _factorize_array(arr, na_sentinel=na_sentinel,
                                           na_value=na_value)

        uniques = self._from_factorized(uniques, self)
        return labels, uniques


Instruction:
Explain what the following Python 3 code does
def take(
            self,
            indices: Sequence[int],
            allow_fill: bool = False,
            fill_value: Any = None
    ) -> ABCExtensionArray:
        """
        Take elements from an array.

        Parameters
        ----------
        indices : sequence of integers
            Indices to be taken.
        allow_fill : bool, default False
            How to handle negative values in `indices`.

            * False: negative values in `indices` indicate positional indices
              from the right (the default). This is similar to
              :func:`numpy.take`.

            * True: negative values in `indices` indicate
              missing values. These values are set to `fill_value`. Any other
              other negative values raise a ``ValueError``.

        fill_value : any, optional
            Fill value to use for NA-indices when `allow_fill` is True.
            This may be ``None``, in which case the default NA value for
            the type, ``self.dtype.na_value``, is used.

            For many ExtensionArrays, there will be two representations of
            `fill_value`: a user-facing "boxed" scalar, and a low-level
            physical NA value. `fill_value` should be the user-facing version,
            and the implementation should handle translating that to the
            physical version for processing the take if necessary.

        Returns
        -------
        ExtensionArray

        Raises
        ------
        IndexError
            When the indices are out of bounds for the array.
        ValueError
            When `indices` contains negative values other than ``-1``
            and `allow_fill` is True.

        Notes
        -----
        ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
        ``iloc``, when `indices` is a sequence of values. Additionally,
        it's called by :meth:`Series.reindex`, or any other method
        that causes realignment, with a `fill_value`.

        See Also
        --------
        numpy.take
        pandas.api.extensions.take

        Examples
        --------
        Here's an example implementation, which relies on casting the
        extension array to object dtype. This uses the helper method
        :func:`pandas.api.extensions.take`.

        .. code-block:: python

           def take(self, indices, allow_fill=False, fill_value=None):
               from pandas.core.algorithms import take

               # If the ExtensionArray is backed by an ndarray, then
               # just pass that here instead of coercing to object.
               data = self.astype(object)

               if allow_fill and fill_value is None:
                   fill_value = self.dtype.na_value

               # fill value should always be translated from the scalar
               # type for the array, to the physical storage type for
               # the data, before passing to take.

               result = take(data, indices, fill_value=fill_value,
                             allow_fill=allow_fill)
               return self._from_sequence(result, dtype=self.dtype)
        """
        # Implementer note: The `fill_value` parameter should be a user-facing
        # value, an instance of self.dtype.type. When passed `fill_value=None`,
        # the default of `self.dtype.na_value` should be used.
        # This may differ from the physical storage type your ExtensionArray
        # uses. In this case, your implementation is responsible for casting
        # the user-facing type to the storage type, before using
        # pandas.api.extensions.take
        raise AbstractMethodError(self)

Response: Take elements from an array.


Instruction:
Can you tell what is the following Python 3 function doing
def _formatter(
            self,
            boxed: bool = False,
    ) -> Callable[[Any], Optional[str]]:
        """Formatting function for scalar values.

        This is used in the default '__repr__'. The returned formatting
        function receives instances of your scalar type.

        Parameters
        ----------
        boxed: bool, default False
            An indicated for whether or not your array is being printed
            within a Series, DataFrame, or Index (True), or just by
            itself (False). This may be useful if you want scalar values
            to appear differently within a Series versus on its own (e.g.
            quoted or not).

        Returns
        -------
        Callable[[Any], str]
            A callable that gets instances of the scalar type and
            returns a string. By default, :func:`repr` is used
            when ``boxed=False`` and :func:`str` is used when
            ``boxed=True``.
        """
        if boxed:
            return str
        return repr

Response: Returns a function that returns a string representation of the array.


Instruction:
How would you implement a function in Python 3 that
returns a scalar result of performing the reduction operation.

Response:
def _reduce(self, name, skipna=True, **kwargs):
        """
        Return a scalar result of performing the reduction operation.

        Parameters
        ----------
        name : str
            Name of the function, supported values are:
            { any, all, min, max, sum, mean, median, prod,
            std, var, sem, kurt, skew }.
        skipna : bool, default True
            If True, skip NaN values.
        **kwargs
            Additional keyword arguments passed to the reduction function.
            Currently, `ddof` is the only supported kwarg.

        Returns
        -------
        scalar

        Raises
        ------
        TypeError : subclass does not define reductions
        """
        raise TypeError("cannot perform {name} with type {dtype}".format(
            name=name, dtype=self.dtype))


Instruction:
Can you create a Python 3 function that
makes an alias for a method of the underlying ExtensionArray. Parameters ---------- array_method : method on an Array class Returns ------- method

Response:
def ea_passthrough(array_method):
    """
    Make an alias for a method of the underlying ExtensionArray.

    Parameters
    ----------
    array_method : method on an Array class

    Returns
    -------
    method
    """

    def method(self, *args, **kwargs):
        return array_method(self._data, *args, **kwargs)

    method.__name__ = array_method.__name__
    method.__doc__ = array_method.__doc__
    return method


Instruction:
Can you tell what is the following Python 3 function doing
def _create_comparison_method(cls, op):
        def wrapper(self, other):
            if isinstance(other, ABCSeries):
                # the arrays defer to Series for comparison ops but the indexes
                #  don't, so we have to unwrap here.
                other = other._values

            result = op(self._data, maybe_unwrap_index(other))
            return result

        wrapper.__doc__ = op.__doc__
        wrapper.__name__ = '__{}__'.format(op.__name__)
        return wrapper

Response: Create a comparison method that dispatches to cls. values.


Instruction:
Write a Python 3 script to
determine if two Index objects contain the same elements.

Response:
def equals(self, other):
        """
        Determines if two Index objects contain the same elements.
        """
        if self.is_(other):
            return True

        if not isinstance(other, ABCIndexClass):
            return False
        elif not isinstance(other, type(self)):
            try:
                other = type(self)(other)
            except Exception:
                return False

        if not is_dtype_equal(self.dtype, other.dtype):
            # have different timezone
            return False

        elif is_period_dtype(self):
            if not is_period_dtype(other):
                return False
            if self.freq != other.freq:
                return False

        return np.array_equal(self.asi8, other.asi8)


Instruction:
Implement a function in Python 3 to
create the join wrapper methods.

Response:
def _join_i8_wrapper(joinf, dtype, with_indexers=True):
        """
        Create the join wrapper methods.
        """
        from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin

        @staticmethod
        def wrapper(left, right):
            if isinstance(left, (np.ndarray, ABCIndex, ABCSeries,
                                 DatetimeLikeArrayMixin)):
                left = left.view('i8')
            if isinstance(right, (np.ndarray, ABCIndex, ABCSeries,
                                  DatetimeLikeArrayMixin)):
                right = right.view('i8')
            results = joinf(left, right)
            if with_indexers:
                join_index, left_indexer, right_indexer = results
                join_index = join_index.view(dtype)
                return join_index, left_indexer, right_indexer
            return results

        return wrapper


Instruction:
Can you generate the documentation for the following Python 3 function
def sort_values(self, return_indexer=False, ascending=True):
        if return_indexer:
            _as = self.argsort()
            if not ascending:
                _as = _as[::-1]
            sorted_index = self.take(_as)
            return sorted_index, _as
        else:
            sorted_values = np.sort(self._ndarray_values)
            attribs = self._get_attributes_dict()
            freq = attribs['freq']

            if freq is not None and not is_period_dtype(self):
                if freq.n > 0 and not ascending:
                    freq = freq * -1
                elif freq.n < 0 and ascending:
                    freq = freq * -1
            attribs['freq'] = freq

            if not ascending:
                sorted_values = sorted_values[::-1]

            return self._simple_new(sorted_values, **attribs)

Response: Sort the values of the array.


Instruction:
Given the following Python 3 function, write the documentation
def min(self, axis=None, skipna=True, *args, **kwargs):
        nv.validate_min(args, kwargs)
        nv.validate_minmax_axis(axis)

        if not len(self):
            return self._na_value

        i8 = self.asi8
        try:
            # quick check
            if len(i8) and self.is_monotonic:
                if i8[0] != iNaT:
                    return self._box_func(i8[0])

            if self.hasnans:
                if skipna:
                    min_stamp = self[~self._isnan].asi8.min()
                else:
                    return self._na_value
            else:
                min_stamp = i8.min()
            return self._box_func(min_stamp)
        except ValueError:
            return self._na_value

Response: Return the minimum value of the Index or minimum along an axis.


Instruction:
Write a Python 3 script for
returning the indices of the minimum values along an axis.

Response:
def argmin(self, axis=None, skipna=True, *args, **kwargs):
        """
        Returns the indices of the minimum values along an axis.

        See `numpy.ndarray.argmin` for more information on the
        `axis` parameter.

        See Also
        --------
        numpy.ndarray.argmin
        """
        nv.validate_argmin(args, kwargs)
        nv.validate_minmax_axis(axis)

        i8 = self.asi8
        if self.hasnans:
            mask = self._isnan
            if mask.all() or not skipna:
                return -1
            i8 = i8.copy()
            i8[mask] = np.iinfo('int64').max
        return i8.argmin()


Instruction:
Write a Python 3 function that can
return the maximum value of the Index or maximum along an axis.

Response:
def max(self, axis=None, skipna=True, *args, **kwargs):
        """
        Return the maximum value of the Index or maximum along
        an axis.

        See Also
        --------
        numpy.ndarray.max
        Series.max : Return the maximum value in a Series.
        """
        nv.validate_max(args, kwargs)
        nv.validate_minmax_axis(axis)

        if not len(self):
            return self._na_value

        i8 = self.asi8
        try:
            # quick check
            if len(i8) and self.is_monotonic:
                if i8[-1] != iNaT:
                    return self._box_func(i8[-1])

            if self.hasnans:
                if skipna:
                    max_stamp = self[~self._isnan].asi8.max()
                else:
                    return self._na_value
            else:
                max_stamp = i8.max()
            return self._box_func(max_stamp)
        except ValueError:
            return self._na_value


Instruction:
Explain what the following Python 3 code does
def argmax(self, axis=None, skipna=True, *args, **kwargs):
        nv.validate_argmax(args, kwargs)
        nv.validate_minmax_axis(axis)

        i8 = self.asi8
        if self.hasnans:
            mask = self._isnan
            if mask.all() or not skipna:
                return -1
            i8 = i8.copy()
            i8[mask] = 0
        return i8.argmax()

Response: Returns the indices of the maximum values along an axis.


Instruction:
How would you implement a function in Python 3 that
returns a list of tuples of the attr formatted_value.

Response:
def _format_attrs(self):
        """
        Return a list of tuples of the (attr,formatted_value).
        """
        attrs = super()._format_attrs()
        for attrib in self._attributes:
            if attrib == 'freq':
                freq = self.freqstr
                if freq is not None:
                    freq = "'%s'" % freq
                attrs.append(('freq', freq))
        return attrs