Code
stringlengths 103
85.9k
| Summary
sequencelengths 0
94
|
---|---|
Please provide a description of the function:def nancorr(a, b, method='pearson', min_periods=None):
if len(a) != len(b):
raise AssertionError('Operands to nancorr must have same size')
if min_periods is None:
min_periods = 1
valid = notna(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
f = get_corr_func(method)
return f(a, b) | [
"\n a, b: ndarrays\n "
] |
Please provide a description of the function:def _nanpercentile_1d(values, mask, q, na_value, interpolation):
# mask is Union[ExtensionArray, ndarray]
values = values[~mask]
if len(values) == 0:
if lib.is_scalar(q):
return na_value
else:
return np.array([na_value] * len(q),
dtype=values.dtype)
return np.percentile(values, q, interpolation=interpolation) | [
"\n Wraper for np.percentile that skips missing values, specialized to\n 1-dimensional case.\n\n Parameters\n ----------\n values : array over which to find quantiles\n mask : ndarray[bool]\n locations in values that should be considered missing\n q : scalar or array of quantile indices to find\n na_value : scalar\n value to return for empty or all-null values\n interpolation : str\n\n Returns\n -------\n quantiles : scalar or array\n "
] |
Please provide a description of the function:def nanpercentile(values, q, axis, na_value, mask, ndim, interpolation):
if not lib.is_scalar(mask) and mask.any():
if ndim == 1:
return _nanpercentile_1d(values, mask, q, na_value,
interpolation=interpolation)
else:
# for nonconsolidatable blocks mask is 1D, but values 2D
if mask.ndim < values.ndim:
mask = mask.reshape(values.shape)
if axis == 0:
values = values.T
mask = mask.T
result = [_nanpercentile_1d(val, m, q, na_value,
interpolation=interpolation)
for (val, m) in zip(list(values), list(mask))]
result = np.array(result, dtype=values.dtype, copy=False).T
return result
else:
return np.percentile(values, q, axis=axis, interpolation=interpolation) | [
"\n Wraper for np.percentile that skips missing values.\n\n Parameters\n ----------\n values : array over which to find quantiles\n q : scalar or array of quantile indices to find\n axis : {0, 1}\n na_value : scalar\n value to return for empty or all-null values\n mask : ndarray[bool]\n locations in values that should be considered missing\n ndim : {1, 2}\n interpolation : str\n\n Returns\n -------\n quantiles : scalar or array\n "
] |
Please provide a description of the function:def write_th(self, s, header=False, indent=0, tags=None):
if header and self.fmt.col_space is not None:
tags = (tags or "")
tags += ('style="min-width: {colspace};"'
.format(colspace=self.fmt.col_space))
return self._write_cell(s, kind='th', indent=indent, tags=tags) | [
"\n Method for writting a formatted <th> cell.\n\n If col_space is set on the formatter then that is used for\n the value of min-width.\n\n Parameters\n ----------\n s : object\n The data to be written inside the cell.\n header : boolean, default False\n Set to True if the <th> is for use inside <thead>. This will\n cause min-width to be set if there is one.\n indent : int, default 0\n The indentation level of the cell.\n tags : string, default None\n Tags to include in the cell.\n\n Returns\n -------\n A written <th> cell.\n "
] |
Please provide a description of the function:def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover
r
encoding = kwargs.pop('encoding', 'utf-8')
# only utf-8 is valid for passed value because that's what clipboard
# supports
if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
raise NotImplementedError(
'reading from clipboard only supports utf-8 encoding')
from pandas.io.clipboard import clipboard_get
from pandas.io.parsers import read_csv
text = clipboard_get()
# Try to decode (if needed, as "text" might already be a string here).
try:
text = text.decode(kwargs.get('encoding')
or get_option('display.encoding'))
except AttributeError:
pass
# Excel copies into clipboard with \t separation
# inspect no more then the 10 first lines, if they
# all contain an equal number (>0) of tabs, infer
# that this came from excel and set 'sep' accordingly
lines = text[:10000].split('\n')[:-1][:10]
# Need to remove leading white space, since read_csv
# accepts:
# a b
# 0 1 2
# 1 3 4
counts = {x.lstrip().count('\t') for x in lines}
if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0:
sep = '\t'
# Edge case where sep is specified to be None, return to default
if sep is None and kwargs.get('delim_whitespace') is None:
sep = r'\s+'
# Regex separator currently only works with python engine.
# Default to python if separator is multi-character (regex)
if len(sep) > 1 and kwargs.get('engine') is None:
kwargs['engine'] = 'python'
elif len(sep) > 1 and kwargs.get('engine') == 'c':
warnings.warn('read_clipboard with regex separator does not work'
' properly with c engine')
return read_csv(StringIO(text), sep=sep, **kwargs) | [
"\n Read text from clipboard and pass to read_csv. See read_csv for the\n full argument list\n\n Parameters\n ----------\n sep : str, default '\\s+'\n A string or regex delimiter. The default of '\\s+' denotes\n one or more whitespace characters.\n\n Returns\n -------\n parsed : DataFrame\n "
] |
Please provide a description of the function:def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover
encoding = kwargs.pop('encoding', 'utf-8')
# testing if an invalid encoding is passed to clipboard
if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
raise ValueError('clipboard only supports utf-8 encoding')
from pandas.io.clipboard import clipboard_set
if excel is None:
excel = True
if excel:
try:
if sep is None:
sep = '\t'
buf = StringIO()
# clipboard_set (pyperclip) expects unicode
obj.to_csv(buf, sep=sep, encoding='utf-8', **kwargs)
text = buf.getvalue()
clipboard_set(text)
return
except TypeError:
warnings.warn('to_clipboard in excel mode requires a single '
'character separator.')
elif sep is not None:
warnings.warn('to_clipboard with excel=False ignores the sep argument')
if isinstance(obj, ABCDataFrame):
# str(df) has various unhelpful defaults, like truncation
with option_context('display.max_colwidth', 999999):
objstr = obj.to_string(**kwargs)
else:
objstr = str(obj)
clipboard_set(objstr) | [
"\n Attempt to write text representation of object to the system clipboard\n The clipboard can be then pasted into Excel for example.\n\n Parameters\n ----------\n obj : the object to write to the clipboard\n excel : boolean, defaults to True\n if True, use the provided separator, writing in a csv\n format for allowing easy pasting into excel.\n if False, write a string representation of the object\n to the clipboard\n sep : optional, defaults to tab\n other keywords are passed to to_csv\n\n Notes\n -----\n Requirements for your platform\n - Linux: xclip, or xsel (with gtk or PyQt4 modules)\n - Windows:\n - OS X:\n "
] |
Please provide a description of the function:def _get_skiprows(skiprows):
if isinstance(skiprows, slice):
return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
return skiprows
elif skiprows is None:
return 0
raise TypeError('%r is not a valid type for skipping rows' %
type(skiprows).__name__) | [
"Get an iterator given an integer, slice or container.\n\n Parameters\n ----------\n skiprows : int, slice, container\n The iterator to use to skip rows; can also be a slice.\n\n Raises\n ------\n TypeError\n * If `skiprows` is not a slice, integer, or Container\n\n Returns\n -------\n it : iterable\n A proper iterator to use to skip rows of a DataFrame.\n "
] |
Please provide a description of the function:def _read(obj):
if _is_url(obj):
with urlopen(obj) as url:
text = url.read()
elif hasattr(obj, 'read'):
text = obj.read()
elif isinstance(obj, (str, bytes)):
text = obj
try:
if os.path.isfile(text):
with open(text, 'rb') as f:
return f.read()
except (TypeError, ValueError):
pass
else:
raise TypeError("Cannot read object of type %r" % type(obj).__name__)
return text | [
"Try to read from a url, file or string.\n\n Parameters\n ----------\n obj : str, unicode, or file-like\n\n Returns\n -------\n raw_text : str\n "
] |
Please provide a description of the function:def _build_xpath_expr(attrs):
# give class attribute as class_ because class is a python keyword
if 'class_' in attrs:
attrs['class'] = attrs.pop('class_')
s = ["@{key}={val!r}".format(key=k, val=v) for k, v in attrs.items()]
return '[{expr}]'.format(expr=' and '.join(s)) | [
"Build an xpath expression to simulate bs4's ability to pass in kwargs to\n search for attributes when using the lxml parser.\n\n Parameters\n ----------\n attrs : dict\n A dict of HTML attributes. These are NOT checked for validity.\n\n Returns\n -------\n expr : unicode\n An XPath expression that checks for the given HTML attributes.\n "
] |
Please provide a description of the function:def _parser_dispatch(flavor):
valid_parsers = list(_valid_parsers.keys())
if flavor not in valid_parsers:
raise ValueError('{invalid!r} is not a valid flavor, valid flavors '
'are {valid}'
.format(invalid=flavor, valid=valid_parsers))
if flavor in ('bs4', 'html5lib'):
if not _HAS_HTML5LIB:
raise ImportError("html5lib not found, please install it")
if not _HAS_BS4:
raise ImportError(
"BeautifulSoup4 (bs4) not found, please install it")
import bs4
if LooseVersion(bs4.__version__) <= LooseVersion('4.2.0'):
raise ValueError("A minimum version of BeautifulSoup 4.2.1 "
"is required")
else:
if not _HAS_LXML:
raise ImportError("lxml not found, please install it")
return _valid_parsers[flavor] | [
"Choose the parser based on the input flavor.\n\n Parameters\n ----------\n flavor : str\n The type of parser to use. This must be a valid backend.\n\n Returns\n -------\n cls : _HtmlFrameParser subclass\n The parser class based on the requested input flavor.\n\n Raises\n ------\n ValueError\n * If `flavor` is not a valid backend.\n ImportError\n * If you do not have the requested `flavor`\n "
] |
Please provide a description of the function:def read_html(io, match='.+', flavor=None, header=None, index_col=None,
skiprows=None, attrs=None, parse_dates=False,
tupleize_cols=None, thousands=',', encoding=None,
decimal='.', converters=None, na_values=None,
keep_default_na=True, displayed_only=True):
r
_importers()
# Type check here. We don't want to parse only to fail because of an
# invalid value of an integer skiprows.
if isinstance(skiprows, numbers.Integral) and skiprows < 0:
raise ValueError('cannot skip rows starting from the end of the '
'data (you passed a negative value)')
_validate_header_arg(header)
return _parse(flavor=flavor, io=io, match=match, header=header,
index_col=index_col, skiprows=skiprows,
parse_dates=parse_dates, tupleize_cols=tupleize_cols,
thousands=thousands, attrs=attrs, encoding=encoding,
decimal=decimal, converters=converters, na_values=na_values,
keep_default_na=keep_default_na,
displayed_only=displayed_only) | [
"Read HTML tables into a ``list`` of ``DataFrame`` objects.\n\n Parameters\n ----------\n io : str or file-like\n A URL, a file-like object, or a raw string containing HTML. Note that\n lxml only accepts the http, ftp and file url protocols. If you have a\n URL that starts with ``'https'`` you might try removing the ``'s'``.\n\n match : str or compiled regular expression, optional\n The set of tables containing text matching this regex or string will be\n returned. Unless the HTML is extremely simple you will probably need to\n pass a non-empty string here. Defaults to '.+' (match any non-empty\n string). The default value will return all tables contained on a page.\n This value is converted to a regular expression so that there is\n consistent behavior between Beautiful Soup and lxml.\n\n flavor : str or None, container of strings\n The parsing engine to use. 'bs4' and 'html5lib' are synonymous with\n each other, they are both there for backwards compatibility. The\n default of ``None`` tries to use ``lxml`` to parse and if that fails it\n falls back on ``bs4`` + ``html5lib``.\n\n header : int or list-like or None, optional\n The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to\n make the columns headers.\n\n index_col : int or list-like or None, optional\n The column (or list of columns) to use to create the index.\n\n skiprows : int or list-like or slice or None, optional\n 0-based. Number of rows to skip after parsing the column integer. If a\n sequence of integers or a slice is given, will skip the rows indexed by\n that sequence. Note that a single element sequence means 'skip the nth\n row' whereas an integer means 'skip n rows'.\n\n attrs : dict or None, optional\n This is a dictionary of attributes that you can pass to use to identify\n the table in the HTML. These are not checked for validity before being\n passed to lxml or Beautiful Soup. However, these attributes must be\n valid HTML table attributes to work correctly. For example, ::\n\n attrs = {'id': 'table'}\n\n is a valid attribute dictionary because the 'id' HTML tag attribute is\n a valid HTML attribute for *any* HTML tag as per `this document\n <http://www.w3.org/TR/html-markup/global-attributes.html>`__. ::\n\n attrs = {'asdf': 'table'}\n\n is *not* a valid attribute dictionary because 'asdf' is not a valid\n HTML attribute even if it is a valid XML attribute. Valid HTML 4.01\n table attributes can be found `here\n <http://www.w3.org/TR/REC-html40/struct/tables.html#h-11.2>`__. A\n working draft of the HTML 5 spec can be found `here\n <http://www.w3.org/TR/html-markup/table.html>`__. It contains the\n latest information on table attributes for the modern web.\n\n parse_dates : bool, optional\n See :func:`~read_csv` for more details.\n\n tupleize_cols : bool, optional\n If ``False`` try to parse multiple header rows into a\n :class:`~pandas.MultiIndex`, otherwise return raw tuples. Defaults to\n ``False``.\n\n .. deprecated:: 0.21.0\n This argument will be removed and will always convert to MultiIndex\n\n thousands : str, optional\n Separator to use to parse thousands. Defaults to ``','``.\n\n encoding : str or None, optional\n The encoding used to decode the web page. Defaults to ``None``.``None``\n preserves the previous encoding behavior, which depends on the\n underlying parser library (e.g., the parser library will try to use\n the encoding provided by the document).\n\n decimal : str, default '.'\n Character to recognize as decimal point (e.g. use ',' for European\n data).\n\n .. versionadded:: 0.19.0\n\n converters : dict, default None\n Dict of functions for converting values in certain columns. Keys can\n either be integers or column labels, values are functions that take one\n input argument, the cell (not column) content, and return the\n transformed content.\n\n .. versionadded:: 0.19.0\n\n na_values : iterable, default None\n Custom NA values\n\n .. versionadded:: 0.19.0\n\n keep_default_na : bool, default True\n If na_values are specified and keep_default_na is False the default NaN\n values are overridden, otherwise they're appended to\n\n .. versionadded:: 0.19.0\n\n displayed_only : bool, default True\n Whether elements with \"display: none\" should be parsed\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n dfs : list of DataFrames\n\n See Also\n --------\n read_csv\n\n Notes\n -----\n Before using this function you should read the :ref:`gotchas about the\n HTML parsing libraries <io.html.gotchas>`.\n\n Expect to do some cleanup after you call this function. For example, you\n might need to manually assign column names if the column names are\n converted to NaN when you pass the `header=0` argument. We try to assume as\n little as possible about the structure of the table and push the\n idiosyncrasies of the HTML contained in the table to the user.\n\n This function searches for ``<table>`` elements and only for ``<tr>``\n and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>``\n element in the table. ``<td>`` stands for \"table data\". This function\n attempts to properly handle ``colspan`` and ``rowspan`` attributes.\n If the function has a ``<thead>`` argument, it is used to construct\n the header, otherwise the function attempts to find the header within\n the body (by putting rows with only ``<th>`` elements into the header).\n\n .. versionadded:: 0.21.0\n\n Similar to :func:`~read_csv` the `header` argument is applied\n **after** `skiprows` is applied.\n\n This function will *always* return a list of :class:`DataFrame` *or*\n it will fail, e.g., it will *not* return an empty list.\n\n Examples\n --------\n See the :ref:`read_html documentation in the IO section of the docs\n <io.read_html>` for some examples of reading in HTML tables.\n "
] |
Please provide a description of the function:def parse_tables(self):
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
return (self._parse_thead_tbody_tfoot(table) for table in tables) | [
"\n Parse and return all tables from the DOM.\n\n Returns\n -------\n list of parsed (header, body, footer) tuples from tables.\n "
] |
Please provide a description of the function:def _parse_thead_tbody_tfoot(self, table_html):
header_rows = self._parse_thead_tr(table_html)
body_rows = self._parse_tbody_tr(table_html)
footer_rows = self._parse_tfoot_tr(table_html)
def row_is_all_th(row):
return all(self._equals_tag(t, 'th') for t in
self._parse_td(row))
if not header_rows:
# The table has no <thead>. Move the top all-<th> rows from
# body_rows to header_rows. (This is a common case because many
# tables in the wild have no <thead> or <tfoot>
while body_rows and row_is_all_th(body_rows[0]):
header_rows.append(body_rows.pop(0))
header = self._expand_colspan_rowspan(header_rows)
body = self._expand_colspan_rowspan(body_rows)
footer = self._expand_colspan_rowspan(footer_rows)
return header, body, footer | [
"\n Given a table, return parsed header, body, and foot.\n\n Parameters\n ----------\n table_html : node-like\n\n Returns\n -------\n tuple of (header, body, footer), each a list of list-of-text rows.\n\n Notes\n -----\n Header and body are lists-of-lists. Top level list is a list of\n rows. Each row is a list of str text.\n\n Logic: Use <thead>, <tbody>, <tfoot> elements to identify\n header, body, and footer, otherwise:\n - Put all rows into body\n - Move rows from top of body to header only if\n all elements inside row are <th>\n - Move rows from bottom of body to footer only if\n all elements inside row are <th>\n "
] |
Please provide a description of the function:def _expand_colspan_rowspan(self, rows):
all_texts = [] # list of rows, each a list of str
remainder = [] # list of (index, text, nrows)
for tr in rows:
texts = [] # the output for this row
next_remainder = []
index = 0
tds = self._parse_td(tr)
for td in tds:
# Append texts from previous rows with rowspan>1 that come
# before this <td>
while remainder and remainder[0][0] <= index:
prev_i, prev_text, prev_rowspan = remainder.pop(0)
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
index += 1
# Append the text from this <td>, colspan times
text = _remove_whitespace(self._text_getter(td))
rowspan = int(self._attr_getter(td, 'rowspan') or 1)
colspan = int(self._attr_getter(td, 'colspan') or 1)
for _ in range(colspan):
texts.append(text)
if rowspan > 1:
next_remainder.append((index, text, rowspan - 1))
index += 1
# Append texts from previous rows at the final position
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
# Append rows that only appear because the previous row had non-1
# rowspan
while remainder:
next_remainder = []
texts = []
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
return all_texts | [
"\n Given a list of <tr>s, return a list of text rows.\n\n Parameters\n ----------\n rows : list of node-like\n List of <tr>s\n\n Returns\n -------\n list of list\n Each returned row is a list of str text.\n\n Notes\n -----\n Any cell with ``rowspan`` or ``colspan`` will have its contents copied\n to subsequent cells.\n "
] |
Please provide a description of the function:def _handle_hidden_tables(self, tbl_list, attr_name):
if not self.displayed_only:
return tbl_list
return [x for x in tbl_list if "display:none" not in
getattr(x, attr_name).get('style', '').replace(" ", "")] | [
"\n Return list of tables, potentially removing hidden elements\n\n Parameters\n ----------\n tbl_list : list of node-like\n Type of list elements will vary depending upon parser used\n attr_name : str\n Name of the accessor for retrieving HTML attributes\n\n Returns\n -------\n list of node-like\n Return type matches `tbl_list`\n "
] |
Please provide a description of the function:def _build_doc(self):
from lxml.html import parse, fromstring, HTMLParser
from lxml.etree import XMLSyntaxError
parser = HTMLParser(recover=True, encoding=self.encoding)
try:
if _is_url(self.io):
with urlopen(self.io) as f:
r = parse(f, parser=parser)
else:
# try to parse the input in the simplest way
r = parse(self.io, parser=parser)
try:
r = r.getroot()
except AttributeError:
pass
except (UnicodeDecodeError, IOError) as e:
# if the input is a blob of html goop
if not _is_url(self.io):
r = fromstring(self.io, parser=parser)
try:
r = r.getroot()
except AttributeError:
pass
else:
raise e
else:
if not hasattr(r, 'text_content'):
raise XMLSyntaxError("no text parsed from document", 0, 0, 0)
return r | [
"\n Raises\n ------\n ValueError\n * If a URL that lxml cannot parse is passed.\n\n Exception\n * Any other ``Exception`` thrown. For example, trying to parse a\n URL that is syntactically correct on a machine with no internet\n connection will fail.\n\n See Also\n --------\n pandas.io.html._HtmlFrameParser._build_doc\n "
] |
Please provide a description of the function:def get_dtype_kinds(l):
typs = set()
for arr in l:
dtype = arr.dtype
if is_categorical_dtype(dtype):
typ = 'category'
elif is_sparse(arr):
typ = 'sparse'
elif isinstance(arr, ABCRangeIndex):
typ = 'range'
elif is_datetime64tz_dtype(arr):
# if to_concat contains different tz,
# the result must be object dtype
typ = str(arr.dtype)
elif is_datetime64_dtype(dtype):
typ = 'datetime'
elif is_timedelta64_dtype(dtype):
typ = 'timedelta'
elif is_object_dtype(dtype):
typ = 'object'
elif is_bool_dtype(dtype):
typ = 'bool'
elif is_extension_array_dtype(dtype):
typ = str(arr.dtype)
else:
typ = dtype.kind
typs.add(typ)
return typs | [
"\n Parameters\n ----------\n l : list of arrays\n\n Returns\n -------\n a set of kinds that exist in this list of arrays\n "
] |
Please provide a description of the function:def _get_series_result_type(result, objs=None):
from pandas import SparseSeries, SparseDataFrame, DataFrame
# concat Series with axis 1
if isinstance(result, dict):
# concat Series with axis 1
if all(isinstance(c, (SparseSeries, SparseDataFrame))
for c in result.values()):
return SparseDataFrame
else:
return DataFrame
# otherwise it is a SingleBlockManager (axis = 0)
if result._block.is_sparse:
return SparseSeries
else:
return objs[0]._constructor | [
"\n return appropriate class of Series concat\n input is either dict or array-like\n "
] |
Please provide a description of the function:def _get_frame_result_type(result, objs):
if (result.blocks and (
any(isinstance(obj, ABCSparseDataFrame) for obj in objs))):
from pandas.core.sparse.api import SparseDataFrame
return SparseDataFrame
else:
return next(obj for obj in objs if not isinstance(obj,
ABCSparseDataFrame)) | [
"\n return appropriate class of DataFrame-like concat\n if all blocks are sparse, return SparseDataFrame\n otherwise, return 1st obj\n "
] |
Please provide a description of the function:def _concat_compat(to_concat, axis=0):
# filter empty arrays
# 1-d dtypes always are included here
def is_nonempty(x):
try:
return x.shape[axis] > 0
except Exception:
return True
# If all arrays are empty, there's nothing to convert, just short-cut to
# the concatenation, #3121.
#
# Creating an empty array directly is tempting, but the winnings would be
# marginal given that it would still require shape & dtype calculation and
# np.concatenate which has them both implemented is compiled.
typs = get_dtype_kinds(to_concat)
_contains_datetime = any(typ.startswith('datetime') for typ in typs)
_contains_period = any(typ.startswith('period') for typ in typs)
if 'category' in typs:
# this must be priort to _concat_datetime,
# to support Categorical + datetime-like
return _concat_categorical(to_concat, axis=axis)
elif _contains_datetime or 'timedelta' in typs or _contains_period:
return _concat_datetime(to_concat, axis=axis, typs=typs)
# these are mandated to handle empties as well
elif 'sparse' in typs:
return _concat_sparse(to_concat, axis=axis, typs=typs)
all_empty = all(not is_nonempty(x) for x in to_concat)
if any(is_extension_array_dtype(x) for x in to_concat) and axis == 1:
to_concat = [np.atleast_2d(x.astype('object')) for x in to_concat]
if all_empty:
# we have all empties, but may need to coerce the result dtype to
# object if we have non-numeric type operands (numpy would otherwise
# cast this to float)
typs = get_dtype_kinds(to_concat)
if len(typs) != 1:
if (not len(typs - {'i', 'u', 'f'}) or
not len(typs - {'bool', 'i', 'u'})):
# let numpy coerce
pass
else:
# coerce to object
to_concat = [x.astype('object') for x in to_concat]
return np.concatenate(to_concat, axis=axis) | [
"\n provide concatenation of an array of arrays each of which is a single\n 'normalized' dtypes (in that for example, if it's object, then it is a\n non-datetimelike and provide a combined dtype for the resulting array that\n preserves the overall dtype if possible)\n\n Parameters\n ----------\n to_concat : array of arrays\n axis : axis to provide concatenation\n\n Returns\n -------\n a single array, preserving the combined dtypes\n "
] |
Please provide a description of the function:def _concat_categorical(to_concat, axis=0):
# we could have object blocks and categoricals here
# if we only have a single categoricals then combine everything
# else its a non-compat categorical
categoricals = [x for x in to_concat if is_categorical_dtype(x.dtype)]
# validate the categories
if len(categoricals) != len(to_concat):
pass
else:
# when all categories are identical
first = to_concat[0]
if all(first.is_dtype_equal(other) for other in to_concat[1:]):
return union_categoricals(categoricals)
# extract the categoricals & coerce to object if needed
to_concat = [x.get_values() if is_categorical_dtype(x.dtype)
else np.asarray(x).ravel() if not is_datetime64tz_dtype(x)
else np.asarray(x.astype(object)) for x in to_concat]
result = _concat_compat(to_concat)
if axis == 1:
result = result.reshape(1, len(result))
return result | [
"Concatenate an object/categorical array of arrays, each of which is a\n single dtype\n\n Parameters\n ----------\n to_concat : array of arrays\n axis : int\n Axis to provide concatenation in the current implementation this is\n always 0, e.g. we only have 1D categoricals\n\n Returns\n -------\n Categorical\n A single array, preserving the combined dtypes\n "
] |
Please provide a description of the function:def union_categoricals(to_union, sort_categories=False, ignore_order=False):
from pandas import Index, Categorical, CategoricalIndex, Series
from pandas.core.arrays.categorical import _recode_for_categories
if len(to_union) == 0:
raise ValueError('No Categoricals to union')
def _maybe_unwrap(x):
if isinstance(x, (CategoricalIndex, Series)):
return x.values
elif isinstance(x, Categorical):
return x
else:
raise TypeError("all components to combine must be Categorical")
to_union = [_maybe_unwrap(x) for x in to_union]
first = to_union[0]
if not all(is_dtype_equal(other.categories.dtype, first.categories.dtype)
for other in to_union[1:]):
raise TypeError("dtype of categories must be the same")
ordered = False
if all(first.is_dtype_equal(other) for other in to_union[1:]):
# identical categories - fastpath
categories = first.categories
ordered = first.ordered
if all(first.categories.equals(other.categories)
for other in to_union[1:]):
new_codes = np.concatenate([c.codes for c in to_union])
else:
codes = [first.codes] + [_recode_for_categories(other.codes,
other.categories,
first.categories)
for other in to_union[1:]]
new_codes = np.concatenate(codes)
if sort_categories and not ignore_order and ordered:
raise TypeError("Cannot use sort_categories=True with "
"ordered Categoricals")
if sort_categories and not categories.is_monotonic_increasing:
categories = categories.sort_values()
indexer = categories.get_indexer(first.categories)
from pandas.core.algorithms import take_1d
new_codes = take_1d(indexer, new_codes, fill_value=-1)
elif ignore_order or all(not c.ordered for c in to_union):
# different categories - union and recode
cats = first.categories.append([c.categories for c in to_union[1:]])
categories = Index(cats.unique())
if sort_categories:
categories = categories.sort_values()
new_codes = [_recode_for_categories(c.codes, c.categories, categories)
for c in to_union]
new_codes = np.concatenate(new_codes)
else:
# ordered - to show a proper error message
if all(c.ordered for c in to_union):
msg = ("to union ordered Categoricals, "
"all categories must be the same")
raise TypeError(msg)
else:
raise TypeError('Categorical.ordered must be the same')
if ignore_order:
ordered = False
return Categorical(new_codes, categories=categories, ordered=ordered,
fastpath=True) | [
"\n Combine list-like of Categorical-like, unioning categories. All\n categories must have the same dtype.\n\n .. versionadded:: 0.19.0\n\n Parameters\n ----------\n to_union : list-like of Categorical, CategoricalIndex,\n or Series with dtype='category'\n sort_categories : boolean, default False\n If true, resulting categories will be lexsorted, otherwise\n they will be ordered as they appear in the data.\n ignore_order : boolean, default False\n If true, the ordered attribute of the Categoricals will be ignored.\n Results in an unordered categorical.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n result : Categorical\n\n Raises\n ------\n TypeError\n - all inputs do not have the same dtype\n - all inputs do not have the same ordered property\n - all inputs are ordered and their categories are not identical\n - sort_categories=True and Categoricals are ordered\n ValueError\n Empty list of categoricals passed\n\n Notes\n -----\n\n To learn more about categories, see `link\n <http://pandas.pydata.org/pandas-docs/stable/categorical.html#unioning>`__\n\n Examples\n --------\n\n >>> from pandas.api.types import union_categoricals\n\n If you want to combine categoricals that do not necessarily have\n the same categories, `union_categoricals` will combine a list-like\n of categoricals. The new categories will be the union of the\n categories being combined.\n\n >>> a = pd.Categorical([\"b\", \"c\"])\n >>> b = pd.Categorical([\"a\", \"b\"])\n >>> union_categoricals([a, b])\n [b, c, a, b]\n Categories (3, object): [b, c, a]\n\n By default, the resulting categories will be ordered as they appear\n in the `categories` of the data. If you want the categories to be\n lexsorted, use `sort_categories=True` argument.\n\n >>> union_categoricals([a, b], sort_categories=True)\n [b, c, a, b]\n Categories (3, object): [a, b, c]\n\n `union_categoricals` also works with the case of combining two\n categoricals of the same categories and order information (e.g. what\n you could also `append` for).\n\n >>> a = pd.Categorical([\"a\", \"b\"], ordered=True)\n >>> b = pd.Categorical([\"a\", \"b\", \"a\"], ordered=True)\n >>> union_categoricals([a, b])\n [a, b, a, b, a]\n Categories (2, object): [a < b]\n\n Raises `TypeError` because the categories are ordered and not identical.\n\n >>> a = pd.Categorical([\"a\", \"b\"], ordered=True)\n >>> b = pd.Categorical([\"a\", \"b\", \"c\"], ordered=True)\n >>> union_categoricals([a, b])\n TypeError: to union ordered Categoricals, all categories must be the same\n\n New in version 0.20.0\n\n Ordered categoricals with different categories or orderings can be\n combined by using the `ignore_ordered=True` argument.\n\n >>> a = pd.Categorical([\"a\", \"b\", \"c\"], ordered=True)\n >>> b = pd.Categorical([\"c\", \"b\", \"a\"], ordered=True)\n >>> union_categoricals([a, b], ignore_order=True)\n [a, b, c, c, b, a]\n Categories (3, object): [a, b, c]\n\n `union_categoricals` also works with a `CategoricalIndex`, or `Series`\n containing categorical data, but note that the resulting array will\n always be a plain `Categorical`\n\n >>> a = pd.Series([\"b\", \"c\"], dtype='category')\n >>> b = pd.Series([\"a\", \"b\"], dtype='category')\n >>> union_categoricals([a, b])\n [b, c, a, b]\n Categories (3, object): [b, c, a]\n "
] |
Please provide a description of the function:def _concat_datetime(to_concat, axis=0, typs=None):
if typs is None:
typs = get_dtype_kinds(to_concat)
# multiple types, need to coerce to object
if len(typs) != 1:
return _concatenate_2d([_convert_datetimelike_to_object(x)
for x in to_concat],
axis=axis)
# must be single dtype
if any(typ.startswith('datetime') for typ in typs):
if 'datetime' in typs:
to_concat = [x.astype(np.int64, copy=False) for x in to_concat]
return _concatenate_2d(to_concat, axis=axis).view(_NS_DTYPE)
else:
# when to_concat has different tz, len(typs) > 1.
# thus no need to care
return _concat_datetimetz(to_concat)
elif 'timedelta' in typs:
return _concatenate_2d([x.view(np.int64) for x in to_concat],
axis=axis).view(_TD_DTYPE)
elif any(typ.startswith('period') for typ in typs):
assert len(typs) == 1
cls = to_concat[0]
new_values = cls._concat_same_type(to_concat)
return new_values | [
"\n provide concatenation of an datetimelike array of arrays each of which is a\n single M8[ns], datetimet64[ns, tz] or m8[ns] dtype\n\n Parameters\n ----------\n to_concat : array of arrays\n axis : axis to provide concatenation\n typs : set of to_concat dtypes\n\n Returns\n -------\n a single array, preserving the combined dtypes\n "
] |
Please provide a description of the function:def _concat_datetimetz(to_concat, name=None):
# Right now, internals will pass a List[DatetimeArray] here
# for reductions like quantile. I would like to disentangle
# all this before we get here.
sample = to_concat[0]
if isinstance(sample, ABCIndexClass):
return sample._concat_same_dtype(to_concat, name=name)
elif isinstance(sample, ABCDatetimeArray):
return sample._concat_same_type(to_concat) | [
"\n concat DatetimeIndex with the same tz\n all inputs must be DatetimeIndex\n it is used in DatetimeIndex.append also\n "
] |
Please provide a description of the function:def _concat_index_asobject(to_concat, name=None):
from pandas import Index
from pandas.core.arrays import ExtensionArray
klasses = (ABCDatetimeIndex, ABCTimedeltaIndex, ABCPeriodIndex,
ExtensionArray)
to_concat = [x.astype(object) if isinstance(x, klasses) else x
for x in to_concat]
self = to_concat[0]
attribs = self._get_attributes_dict()
attribs['name'] = name
to_concat = [x._values if isinstance(x, Index) else x
for x in to_concat]
return self._shallow_copy_with_infer(np.concatenate(to_concat), **attribs) | [
"\n concat all inputs as object. DatetimeIndex, TimedeltaIndex and\n PeriodIndex are converted to object dtype before concatenation\n "
] |
Please provide a description of the function:def _concat_sparse(to_concat, axis=0, typs=None):
from pandas.core.arrays import SparseArray
fill_values = [x.fill_value for x in to_concat
if isinstance(x, SparseArray)]
fill_value = fill_values[0]
# TODO: Fix join unit generation so we aren't passed this.
to_concat = [x if isinstance(x, SparseArray)
else SparseArray(x.squeeze(), fill_value=fill_value)
for x in to_concat]
return SparseArray._concat_same_type(to_concat) | [
"\n provide concatenation of an sparse/dense array of arrays each of which is a\n single dtype\n\n Parameters\n ----------\n to_concat : array of arrays\n axis : axis to provide concatenation\n typs : set of to_concat dtypes\n\n Returns\n -------\n a single array, preserving the combined dtypes\n "
] |
Please provide a description of the function:def _concat_rangeindex_same_dtype(indexes):
from pandas import Int64Index, RangeIndex
start = step = next = None
# Filter the empty indexes
non_empty_indexes = [obj for obj in indexes if len(obj)]
for obj in non_empty_indexes:
if start is None:
# This is set by the first non-empty index
start = obj._start
if step is None and len(obj) > 1:
step = obj._step
elif step is None:
# First non-empty index had only one element
if obj._start == start:
return _concat_index_same_dtype(indexes, klass=Int64Index)
step = obj._start - start
non_consecutive = ((step != obj._step and len(obj) > 1) or
(next is not None and obj._start != next))
if non_consecutive:
return _concat_index_same_dtype(indexes, klass=Int64Index)
if step is not None:
next = obj[-1] + step
if non_empty_indexes:
# Get the stop value from "next" or alternatively
# from the last non-empty index
stop = non_empty_indexes[-1]._stop if next is None else next
return RangeIndex(start, stop, step)
# Here all "indexes" had 0 length, i.e. were empty.
# In this case return an empty range index.
return RangeIndex(0, 0) | [
"\n Concatenates multiple RangeIndex instances. All members of \"indexes\" must\n be of type RangeIndex; result will be RangeIndex if possible, Int64Index\n otherwise. E.g.:\n indexes = [RangeIndex(3), RangeIndex(3, 6)] -> RangeIndex(6)\n indexes = [RangeIndex(3), RangeIndex(4, 6)] -> Int64Index([0,1,2,4,5])\n "
] |
Please provide a description of the function:def rewrite_exception(old_name, new_name):
try:
yield
except Exception as e:
msg = e.args[0]
msg = msg.replace(old_name, new_name)
args = (msg,)
if len(e.args) > 1:
args = args + e.args[1:]
e.args = args
raise | [
"Rewrite the message of an exception."
] |
Please provide a description of the function:def _get_level_lengths(index, hidden_elements=None):
sentinel = object()
levels = index.format(sparsify=sentinel, adjoin=False, names=False)
if hidden_elements is None:
hidden_elements = []
lengths = {}
if index.nlevels == 1:
for i, value in enumerate(levels):
if(i not in hidden_elements):
lengths[(0, i)] = 1
return lengths
for i, lvl in enumerate(levels):
for j, row in enumerate(lvl):
if not get_option('display.multi_sparse'):
lengths[(i, j)] = 1
elif (row != sentinel) and (j not in hidden_elements):
last_label = j
lengths[(i, last_label)] = 1
elif (row != sentinel):
# even if its hidden, keep track of it in case
# length >1 and later elements are visible
last_label = j
lengths[(i, last_label)] = 0
elif(j not in hidden_elements):
lengths[(i, last_label)] += 1
non_zero_lengths = {
element: length for element, length in lengths.items() if length >= 1}
return non_zero_lengths | [
"\n Given an index, find the level length for each element.\n\n Optional argument is a list of index positions which\n should not be visible.\n\n Result is a dictionary of (level, inital_position): span\n "
] |
Please provide a description of the function:def _translate(self):
table_styles = self.table_styles or []
caption = self.caption
ctx = self.ctx
precision = self.precision
hidden_index = self.hidden_index
hidden_columns = self.hidden_columns
uuid = self.uuid or str(uuid1()).replace("-", "_")
ROW_HEADING_CLASS = "row_heading"
COL_HEADING_CLASS = "col_heading"
INDEX_NAME_CLASS = "index_name"
DATA_CLASS = "data"
BLANK_CLASS = "blank"
BLANK_VALUE = ""
def format_attr(pair):
return "{key}={value}".format(**pair)
# for sparsifying a MultiIndex
idx_lengths = _get_level_lengths(self.index)
col_lengths = _get_level_lengths(self.columns, hidden_columns)
cell_context = dict()
n_rlvls = self.data.index.nlevels
n_clvls = self.data.columns.nlevels
rlabels = self.data.index.tolist()
clabels = self.data.columns.tolist()
if n_rlvls == 1:
rlabels = [[x] for x in rlabels]
if n_clvls == 1:
clabels = [[x] for x in clabels]
clabels = list(zip(*clabels))
cellstyle = []
head = []
for r in range(n_clvls):
# Blank for Index columns...
row_es = [{"type": "th",
"value": BLANK_VALUE,
"display_value": BLANK_VALUE,
"is_visible": not hidden_index,
"class": " ".join([BLANK_CLASS])}] * (n_rlvls - 1)
# ... except maybe the last for columns.names
name = self.data.columns.names[r]
cs = [BLANK_CLASS if name is None else INDEX_NAME_CLASS,
"level{lvl}".format(lvl=r)]
name = BLANK_VALUE if name is None else name
row_es.append({"type": "th",
"value": name,
"display_value": name,
"class": " ".join(cs),
"is_visible": not hidden_index})
if clabels:
for c, value in enumerate(clabels[r]):
cs = [COL_HEADING_CLASS, "level{lvl}".format(lvl=r),
"col{col}".format(col=c)]
cs.extend(cell_context.get(
"col_headings", {}).get(r, {}).get(c, []))
es = {
"type": "th",
"value": value,
"display_value": value,
"class": " ".join(cs),
"is_visible": _is_visible(c, r, col_lengths),
}
colspan = col_lengths.get((r, c), 0)
if colspan > 1:
es["attributes"] = [
format_attr({"key": "colspan", "value": colspan})
]
row_es.append(es)
head.append(row_es)
if (self.data.index.names and
com._any_not_none(*self.data.index.names) and
not hidden_index):
index_header_row = []
for c, name in enumerate(self.data.index.names):
cs = [INDEX_NAME_CLASS,
"level{lvl}".format(lvl=c)]
name = '' if name is None else name
index_header_row.append({"type": "th", "value": name,
"class": " ".join(cs)})
index_header_row.extend(
[{"type": "th",
"value": BLANK_VALUE,
"class": " ".join([BLANK_CLASS])
}] * (len(clabels[0]) - len(hidden_columns)))
head.append(index_header_row)
body = []
for r, idx in enumerate(self.data.index):
row_es = []
for c, value in enumerate(rlabels[r]):
rid = [ROW_HEADING_CLASS, "level{lvl}".format(lvl=c),
"row{row}".format(row=r)]
es = {
"type": "th",
"is_visible": (_is_visible(r, c, idx_lengths) and
not hidden_index),
"value": value,
"display_value": value,
"id": "_".join(rid[1:]),
"class": " ".join(rid)
}
rowspan = idx_lengths.get((c, r), 0)
if rowspan > 1:
es["attributes"] = [
format_attr({"key": "rowspan", "value": rowspan})
]
row_es.append(es)
for c, col in enumerate(self.data.columns):
cs = [DATA_CLASS, "row{row}".format(row=r),
"col{col}".format(col=c)]
cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
formatter = self._display_funcs[(r, c)]
value = self.data.iloc[r, c]
row_dict = {"type": "td",
"value": value,
"class": " ".join(cs),
"display_value": formatter(value),
"is_visible": (c not in hidden_columns)}
# only add an id if the cell has a style
if (self.cell_ids or
not(len(ctx[r, c]) == 1 and ctx[r, c][0] == '')):
row_dict["id"] = "_".join(cs[1:])
row_es.append(row_dict)
props = []
for x in ctx[r, c]:
# have to handle empty styles like ['']
if x.count(":"):
props.append(x.split(":"))
else:
props.append(['', ''])
cellstyle.append({'props': props,
'selector': "row{row}_col{col}"
.format(row=r, col=c)})
body.append(row_es)
table_attr = self.table_attributes
use_mathjax = get_option("display.html.use_mathjax")
if not use_mathjax:
table_attr = table_attr or ''
if 'class="' in table_attr:
table_attr = table_attr.replace('class="',
'class="tex2jax_ignore ')
else:
table_attr += ' class="tex2jax_ignore"'
return dict(head=head, cellstyle=cellstyle, body=body, uuid=uuid,
precision=precision, table_styles=table_styles,
caption=caption, table_attributes=table_attr) | [
"\n Convert the DataFrame in `self.data` and the attrs from `_build_styles`\n into a dictionary of {head, body, uuid, cellstyle}.\n "
] |
Please provide a description of the function:def format(self, formatter, subset=None):
if subset is None:
row_locs = range(len(self.data))
col_locs = range(len(self.data.columns))
else:
subset = _non_reducing_slice(subset)
if len(subset) == 1:
subset = subset, self.data.columns
sub_df = self.data.loc[subset]
row_locs = self.data.index.get_indexer_for(sub_df.index)
col_locs = self.data.columns.get_indexer_for(sub_df.columns)
if is_dict_like(formatter):
for col, col_formatter in formatter.items():
# formatter must be callable, so '{}' are converted to lambdas
col_formatter = _maybe_wrap_formatter(col_formatter)
col_num = self.data.columns.get_indexer_for([col])[0]
for row_num in row_locs:
self._display_funcs[(row_num, col_num)] = col_formatter
else:
# single scalar to format all cells with
locs = product(*(row_locs, col_locs))
for i, j in locs:
formatter = _maybe_wrap_formatter(formatter)
self._display_funcs[(i, j)] = formatter
return self | [
"\n Format the text display value of cells.\n\n .. versionadded:: 0.18.0\n\n Parameters\n ----------\n formatter : str, callable, or dict\n subset : IndexSlice\n An argument to ``DataFrame.loc`` that restricts which elements\n ``formatter`` is applied to.\n\n Returns\n -------\n self : Styler\n\n Notes\n -----\n\n ``formatter`` is either an ``a`` or a dict ``{column name: a}`` where\n ``a`` is one of\n\n - str: this will be wrapped in: ``a.format(x)``\n - callable: called with the value of an individual cell\n\n The default display value for numeric values is the \"general\" (``g``)\n format with ``pd.options.display.precision`` precision.\n\n Examples\n --------\n\n >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])\n >>> df.style.format(\"{:.2%}\")\n >>> df['c'] = ['a', 'b', 'c', 'd']\n >>> df.style.format({'c': str.upper})\n "
] |
Please provide a description of the function:def render(self, **kwargs):
self._compute()
# TODO: namespace all the pandas keys
d = self._translate()
# filter out empty styles, every cell will have a class
# but the list of props may just be [['', '']].
# so we have the neested anys below
trimmed = [x for x in d['cellstyle']
if any(any(y) for y in x['props'])]
d['cellstyle'] = trimmed
d.update(kwargs)
return self.template.render(**d) | [
"\n Render the built up styles to HTML.\n\n Parameters\n ----------\n **kwargs\n Any additional keyword arguments are passed\n through to ``self.template.render``.\n This is useful when you need to provide\n additional variables for a custom template.\n\n .. versionadded:: 0.20\n\n Returns\n -------\n rendered : str\n The rendered HTML.\n\n Notes\n -----\n ``Styler`` objects have defined the ``_repr_html_`` method\n which automatically calls ``self.render()`` when it's the\n last item in a Notebook cell. When calling ``Styler.render()``\n directly, wrap the result in ``IPython.display.HTML`` to view\n the rendered HTML in the notebook.\n\n Pandas uses the following keys in render. Arguments passed\n in ``**kwargs`` take precedence, so think carefully if you want\n to override them:\n\n * head\n * cellstyle\n * body\n * uuid\n * precision\n * table_styles\n * caption\n * table_attributes\n "
] |
Please provide a description of the function:def _update_ctx(self, attrs):
for row_label, v in attrs.iterrows():
for col_label, col in v.iteritems():
i = self.index.get_indexer([row_label])[0]
j = self.columns.get_indexer([col_label])[0]
for pair in col.rstrip(";").split(";"):
self.ctx[(i, j)].append(pair) | [
"\n Update the state of the Styler.\n\n Collects a mapping of {index_label: ['<property>: <value>']}.\n\n attrs : Series or DataFrame\n should contain strings of '<property>: <value>;<prop2>: <val2>'\n Whitespace shouldn't matter and the final trailing ';' shouldn't\n matter.\n "
] |
Please provide a description of the function:def _compute(self):
r = self
for func, args, kwargs in self._todo:
r = func(self)(*args, **kwargs)
return r | [
"\n Execute the style functions built up in `self._todo`.\n\n Relies on the conventions that all style functions go through\n .apply or .applymap. The append styles to apply as tuples of\n\n (application method, *args, **kwargs)\n "
] |
Please provide a description of the function:def apply(self, func, axis=0, subset=None, **kwargs):
self._todo.append((lambda instance: getattr(instance, '_apply'),
(func, axis, subset), kwargs))
return self | [
"\n Apply a function column-wise, row-wise, or table-wise,\n updating the HTML representation with the result.\n\n Parameters\n ----------\n func : function\n ``func`` should take a Series or DataFrame (depending\n on ``axis``), and return an object with the same shape.\n Must return a DataFrame with identical index and\n column labels when ``axis=None``\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n apply to each column (``axis=0`` or ``'index'``), to each row\n (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n with ``axis=None``.\n subset : IndexSlice\n a valid indexer to limit ``data`` to *before* applying the\n function. Consider using a pandas.IndexSlice\n kwargs : dict\n pass along to ``func``\n\n Returns\n -------\n self : Styler\n\n Notes\n -----\n The output shape of ``func`` should match the input, i.e. if\n ``x`` is the input row, column, or table (depending on ``axis``),\n then ``func(x).shape == x.shape`` should be true.\n\n This is similar to ``DataFrame.apply``, except that ``axis=None``\n applies the function to the entire DataFrame at once,\n rather than column-wise or row-wise.\n\n Examples\n --------\n >>> def highlight_max(x):\n ... return ['background-color: yellow' if v == x.max() else ''\n for v in x]\n ...\n >>> df = pd.DataFrame(np.random.randn(5, 2))\n >>> df.style.apply(highlight_max)\n "
] |
Please provide a description of the function:def applymap(self, func, subset=None, **kwargs):
self._todo.append((lambda instance: getattr(instance, '_applymap'),
(func, subset), kwargs))
return self | [
"\n Apply a function elementwise, updating the HTML\n representation with the result.\n\n Parameters\n ----------\n func : function\n ``func`` should take a scalar and return a scalar\n subset : IndexSlice\n a valid indexer to limit ``data`` to *before* applying the\n function. Consider using a pandas.IndexSlice\n kwargs : dict\n pass along to ``func``\n\n Returns\n -------\n self : Styler\n\n See Also\n --------\n Styler.where\n "
] |
Please provide a description of the function:def where(self, cond, value, other=None, subset=None, **kwargs):
if other is None:
other = ''
return self.applymap(lambda val: value if cond(val) else other,
subset=subset, **kwargs) | [
"\n Apply a function elementwise, updating the HTML\n representation with a style which is selected in\n accordance with the return value of a function.\n\n .. versionadded:: 0.21.0\n\n Parameters\n ----------\n cond : callable\n ``cond`` should take a scalar and return a boolean\n value : str\n applied when ``cond`` returns true\n other : str\n applied when ``cond`` returns false\n subset : IndexSlice\n a valid indexer to limit ``data`` to *before* applying the\n function. Consider using a pandas.IndexSlice\n kwargs : dict\n pass along to ``cond``\n\n Returns\n -------\n self : Styler\n\n See Also\n --------\n Styler.applymap\n "
] |
Please provide a description of the function:def hide_columns(self, subset):
subset = _non_reducing_slice(subset)
hidden_df = self.data.loc[subset]
self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
return self | [
"\n Hide columns from rendering.\n\n .. versionadded:: 0.23.0\n\n Parameters\n ----------\n subset : IndexSlice\n An argument to ``DataFrame.loc`` that identifies which columns\n are hidden.\n\n Returns\n -------\n self : Styler\n "
] |
Please provide a description of the function:def highlight_null(self, null_color='red'):
self.applymap(self._highlight_null, null_color=null_color)
return self | [
"\n Shade the background ``null_color`` for missing values.\n\n Parameters\n ----------\n null_color : str\n\n Returns\n -------\n self : Styler\n "
] |
Please provide a description of the function:def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
subset=None, text_color_threshold=0.408):
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(self._background_gradient, cmap=cmap, subset=subset,
axis=axis, low=low, high=high,
text_color_threshold=text_color_threshold)
return self | [
"\n Color the background in a gradient according to\n the data in each column (optionally row).\n\n Requires matplotlib.\n\n Parameters\n ----------\n cmap : str or colormap\n matplotlib colormap\n low, high : float\n compress the range by these values.\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n apply to each column (``axis=0`` or ``'index'``), to each row\n (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n with ``axis=None``.\n subset : IndexSlice\n a valid slice for ``data`` to limit the style application to.\n text_color_threshold : float or int\n luminance threshold for determining text color. Facilitates text\n visibility across varying background colors. From 0 to 1.\n 0 = all text is dark colored, 1 = all text is light colored.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n self : Styler\n\n Raises\n ------\n ValueError\n If ``text_color_threshold`` is not a value from 0 to 1.\n\n Notes\n -----\n Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the\n text legible by not using the entire range of the color map. The range\n of the data is extended by ``low * (x.max() - x.min())`` and ``high *\n (x.max() - x.min())`` before normalizing.\n "
] |
Please provide a description of the function:def _background_gradient(s, cmap='PuBu', low=0, high=0,
text_color_threshold=0.408):
if (not isinstance(text_color_threshold, (float, int)) or
not 0 <= text_color_threshold <= 1):
msg = "`text_color_threshold` must be a value from 0 to 1."
raise ValueError(msg)
with _mpl(Styler.background_gradient) as (plt, colors):
smin = s.values.min()
smax = s.values.max()
rng = smax - smin
# extend lower / upper bounds, compresses color range
norm = colors.Normalize(smin - (rng * low), smax + (rng * high))
# matplotlib colors.Normalize modifies inplace?
# https://github.com/matplotlib/matplotlib/issues/5427
rgbas = plt.cm.get_cmap(cmap)(norm(s.values))
def relative_luminance(rgba):
r, g, b = (
x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4)
for x in rgba[:3]
)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def css(rgba):
dark = relative_luminance(rgba) < text_color_threshold
text_color = '#f1f1f1' if dark else '#000000'
return 'background-color: {b};color: {c};'.format(
b=colors.rgb2hex(rgba), c=text_color
)
if s.ndim == 1:
return [css(rgba) for rgba in rgbas]
else:
return pd.DataFrame(
[[css(rgba) for rgba in row] for row in rgbas],
index=s.index, columns=s.columns
) | [
"\n Color background in a range according to the data.\n ",
"\n Calculate relative luminance of a color.\n\n The calculation adheres to the W3C standards\n (https://www.w3.org/WAI/GL/wiki/Relative_luminance)\n\n Parameters\n ----------\n color : rgb or rgba tuple\n\n Returns\n -------\n float\n The relative luminance as a value from 0 to 1\n "
] |
Please provide a description of the function:def set_properties(self, subset=None, **kwargs):
values = ';'.join('{p}: {v}'.format(p=p, v=v)
for p, v in kwargs.items())
f = lambda x: values
return self.applymap(f, subset=subset) | [
"\n Convenience method for setting one or more non-data dependent\n properties or each cell.\n\n Parameters\n ----------\n subset : IndexSlice\n a valid slice for ``data`` to limit the style application to\n kwargs : dict\n property: value pairs to be set for each cell\n\n Returns\n -------\n self : Styler\n\n Examples\n --------\n >>> df = pd.DataFrame(np.random.randn(10, 4))\n >>> df.style.set_properties(color=\"white\", align=\"right\")\n >>> df.style.set_properties(**{'background-color': 'yellow'})\n "
] |
Please provide a description of the function:def _bar(s, align, colors, width=100, vmin=None, vmax=None):
# Get input value range.
smin = s.min() if vmin is None else vmin
if isinstance(smin, ABCSeries):
smin = smin.min()
smax = s.max() if vmax is None else vmax
if isinstance(smax, ABCSeries):
smax = smax.max()
if align == 'mid':
smin = min(0, smin)
smax = max(0, smax)
elif align == 'zero':
# For "zero" mode, we want the range to be symmetrical around zero.
smax = max(abs(smin), abs(smax))
smin = -smax
# Transform to percent-range of linear-gradient
normed = width * (s.values - smin) / (smax - smin + 1e-12)
zero = -width * smin / (smax - smin + 1e-12)
def css_bar(start, end, color):
css = 'width: 10em; height: 80%;'
if end > start:
css += 'background: linear-gradient(90deg,'
if start > 0:
css += ' transparent {s:.1f}%, {c} {s:.1f}%, '.format(
s=start, c=color
)
css += '{c} {e:.1f}%, transparent {e:.1f}%)'.format(
e=min(end, width), c=color,
)
return css
def css(x):
if pd.isna(x):
return ''
# avoid deprecated indexing `colors[x > zero]`
color = colors[1] if x > zero else colors[0]
if align == 'left':
return css_bar(0, x, color)
else:
return css_bar(min(x, zero), max(x, zero), color)
if s.ndim == 1:
return [css(x) for x in normed]
else:
return pd.DataFrame(
[[css(x) for x in row] for row in normed],
index=s.index, columns=s.columns
) | [
"\n Draw bar chart in dataframe cells.\n ",
"\n Generate CSS code to draw a bar from start to end.\n "
] |
Please provide a description of the function:def bar(self, subset=None, axis=0, color='#d65f5f', width=100,
align='left', vmin=None, vmax=None):
if align not in ('left', 'zero', 'mid'):
raise ValueError("`align` must be one of {'left', 'zero',' mid'}")
if not (is_list_like(color)):
color = [color, color]
elif len(color) == 1:
color = [color[0], color[0]]
elif len(color) > 2:
raise ValueError("`color` must be string or a list-like"
" of length 2: [`color_neg`, `color_pos`]"
" (eg: color=['#d65f5f', '#5fba7d'])")
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(self._bar, subset=subset, axis=axis,
align=align, colors=color, width=width,
vmin=vmin, vmax=vmax)
return self | [
"\n Draw bar chart in the cell backgrounds.\n\n Parameters\n ----------\n subset : IndexSlice, optional\n A valid slice for `data` to limit the style application to.\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n apply to each column (``axis=0`` or ``'index'``), to each row\n (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n with ``axis=None``.\n color : str or 2-tuple/list\n If a str is passed, the color is the same for both\n negative and positive numbers. If 2-tuple/list is used, the\n first element is the color_negative and the second is the\n color_positive (eg: ['#d65f5f', '#5fba7d']).\n width : float, default 100\n A number between 0 or 100. The largest value will cover `width`\n percent of the cell's width.\n align : {'left', 'zero',' mid'}, default 'left'\n How to align the bars with the cells.\n\n - 'left' : the min value starts at the left of the cell.\n - 'zero' : a value of zero is located at the center of the cell.\n - 'mid' : the center of the cell is at (max-min)/2, or\n if values are all negative (positive) the zero is aligned\n at the right (left) of the cell.\n\n .. versionadded:: 0.20.0\n\n vmin : float, optional\n Minimum bar value, defining the left hand limit\n of the bar drawing range, lower values are clipped to `vmin`.\n When None (default): the minimum value of the data will be used.\n\n .. versionadded:: 0.24.0\n\n vmax : float, optional\n Maximum bar value, defining the right hand limit\n of the bar drawing range, higher values are clipped to `vmax`.\n When None (default): the maximum value of the data will be used.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n self : Styler\n "
] |
Please provide a description of the function:def highlight_max(self, subset=None, color='yellow', axis=0):
return self._highlight_handler(subset=subset, color=color, axis=axis,
max_=True) | [
"\n Highlight the maximum by shading the background.\n\n Parameters\n ----------\n subset : IndexSlice, default None\n a valid slice for ``data`` to limit the style application to.\n color : str, default 'yellow'\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n apply to each column (``axis=0`` or ``'index'``), to each row\n (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n with ``axis=None``.\n\n Returns\n -------\n self : Styler\n "
] |
Please provide a description of the function:def highlight_min(self, subset=None, color='yellow', axis=0):
return self._highlight_handler(subset=subset, color=color, axis=axis,
max_=False) | [
"\n Highlight the minimum by shading the background.\n\n Parameters\n ----------\n subset : IndexSlice, default None\n a valid slice for ``data`` to limit the style application to.\n color : str, default 'yellow'\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n apply to each column (``axis=0`` or ``'index'``), to each row\n (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n with ``axis=None``.\n\n Returns\n -------\n self : Styler\n "
] |
Please provide a description of the function:def _highlight_extrema(data, color='yellow', max_=True):
attr = 'background-color: {0}'.format(color)
if data.ndim == 1: # Series from .apply
if max_:
extrema = data == data.max()
else:
extrema = data == data.min()
return [attr if v else '' for v in extrema]
else: # DataFrame from .tee
if max_:
extrema = data == data.max().max()
else:
extrema = data == data.min().min()
return pd.DataFrame(np.where(extrema, attr, ''),
index=data.index, columns=data.columns) | [
"\n Highlight the min or max in a Series or DataFrame.\n "
] |
Please provide a description of the function:def from_custom_template(cls, searchpath, name):
loader = ChoiceLoader([
FileSystemLoader(searchpath),
cls.loader,
])
class MyStyler(cls):
env = Environment(loader=loader)
template = env.get_template(name)
return MyStyler | [
"\n Factory function for creating a subclass of ``Styler``\n with a custom template and Jinja environment.\n\n Parameters\n ----------\n searchpath : str or list\n Path or paths of directories containing the templates\n name : str\n Name of your custom template to use for rendering\n\n Returns\n -------\n MyStyler : subclass of Styler\n Has the correct ``env`` and ``template`` class attributes set.\n "
] |
Please provide a description of the function:def register(self, dtype):
if not issubclass(dtype, (PandasExtensionDtype, ExtensionDtype)):
raise ValueError("can only register pandas extension dtypes")
self.dtypes.append(dtype) | [
"\n Parameters\n ----------\n dtype : ExtensionDtype\n "
] |
Please provide a description of the function:def find(self, dtype):
if not isinstance(dtype, str):
dtype_type = dtype
if not isinstance(dtype, type):
dtype_type = type(dtype)
if issubclass(dtype_type, ExtensionDtype):
return dtype
return None
for dtype_type in self.dtypes:
try:
return dtype_type.construct_from_string(dtype)
except TypeError:
pass
return None | [
"\n Parameters\n ----------\n dtype : PandasExtensionDtype or string\n\n Returns\n -------\n return the first matching dtype, otherwise return None\n "
] |
Please provide a description of the function:def np_datetime64_compat(s, *args, **kwargs):
s = tz_replacer(s)
return np.datetime64(s, *args, **kwargs) | [
"\n provide compat for construction of strings to numpy datetime64's with\n tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation\n warning, when need to pass '2015-01-01 09:00:00'\n "
] |
Please provide a description of the function:def np_array_datetime64_compat(arr, *args, **kwargs):
# is_list_like
if (hasattr(arr, '__iter__') and not isinstance(arr, (str, bytes))):
arr = [tz_replacer(s) for s in arr]
else:
arr = tz_replacer(arr)
return np.array(arr, *args, **kwargs) | [
"\n provide compat for construction of an array of strings to a\n np.array(..., dtype=np.datetime64(..))\n tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation\n warning, when need to pass '2015-01-01 09:00:00'\n "
] |
Please provide a description of the function:def _assert_safe_casting(cls, data, subarr):
if not issubclass(data.dtype.type, np.signedinteger):
if not np.array_equal(data, subarr):
raise TypeError('Unsafe NumPy casting, you must '
'explicitly cast') | [
"\n Ensure incoming data can be represented as ints.\n "
] |
Please provide a description of the function:def get_value(self, series, key):
if not is_scalar(key):
raise InvalidIndexError
k = com.values_from_object(key)
loc = self.get_loc(k)
new_values = com.values_from_object(series)[loc]
return new_values | [
" we always want to get an index value, never a value "
] |
Please provide a description of the function:def equals(self, other):
if self is other:
return True
if not isinstance(other, Index):
return False
# need to compare nans locations and make sure that they are the same
# since nans don't compare equal this is a bit tricky
try:
if not isinstance(other, Float64Index):
other = self._constructor(other)
if (not is_dtype_equal(self.dtype, other.dtype) or
self.shape != other.shape):
return False
left, right = self._ndarray_values, other._ndarray_values
return ((left == right) | (self._isnan & other._isnan)).all()
except (TypeError, ValueError):
return False | [
"\n Determines if two Index objects contain the same elements.\n "
] |
Please provide a description of the function:def _ensure_decoded(s):
if isinstance(s, np.bytes_):
s = s.decode('UTF-8')
return s | [
" if we have bytes, decode them to unicode "
] |
Please provide a description of the function:def _ensure_term(where, scope_level):
# only consider list/tuple here as an ndarray is automatically a coordinate
# list
level = scope_level + 1
if isinstance(where, (list, tuple)):
wlist = []
for w in filter(lambda x: x is not None, where):
if not maybe_expression(w):
wlist.append(w)
else:
wlist.append(Term(w, scope_level=level))
where = wlist
elif maybe_expression(where):
where = Term(where, scope_level=level)
return where | [
"\n ensure that the where is a Term or a list of Term\n this makes sure that we are capturing the scope of variables\n that are passed\n create the terms here with a frame_level=2 (we are 2 levels down)\n "
] |
Please provide a description of the function:def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
append=None, **kwargs):
if append:
f = lambda store: store.append(key, value, **kwargs)
else:
f = lambda store: store.put(key, value, **kwargs)
path_or_buf = _stringify_path(path_or_buf)
if isinstance(path_or_buf, str):
with HDFStore(path_or_buf, mode=mode, complevel=complevel,
complib=complib) as store:
f(store)
else:
f(path_or_buf) | [
" store this object, close it if we opened it "
] |
Please provide a description of the function:def read_hdf(path_or_buf, key=None, mode='r', **kwargs):
if mode not in ['r', 'r+', 'a']:
raise ValueError('mode {0} is not allowed while performing a read. '
'Allowed modes are r, r+ and a.'.format(mode))
# grab the scope
if 'where' in kwargs:
kwargs['where'] = _ensure_term(kwargs['where'], scope_level=1)
if isinstance(path_or_buf, HDFStore):
if not path_or_buf.is_open:
raise IOError('The HDFStore must be open for reading.')
store = path_or_buf
auto_close = False
else:
path_or_buf = _stringify_path(path_or_buf)
if not isinstance(path_or_buf, str):
raise NotImplementedError('Support for generic buffers has not '
'been implemented.')
try:
exists = os.path.exists(path_or_buf)
# if filepath is too long
except (TypeError, ValueError):
exists = False
if not exists:
raise FileNotFoundError(
'File {path} does not exist'.format(path=path_or_buf))
store = HDFStore(path_or_buf, mode=mode, **kwargs)
# can't auto open/close if we are using an iterator
# so delegate to the iterator
auto_close = True
try:
if key is None:
groups = store.groups()
if len(groups) == 0:
raise ValueError('No dataset in HDF5 file.')
candidate_only_group = groups[0]
# For the HDF file to have only one dataset, all other groups
# should then be metadata groups for that candidate group. (This
# assumes that the groups() method enumerates parent groups
# before their children.)
for group_to_check in groups[1:]:
if not _is_metadata_of(group_to_check, candidate_only_group):
raise ValueError('key must be provided when HDF5 file '
'contains multiple datasets.')
key = candidate_only_group._v_pathname
return store.select(key, auto_close=auto_close, **kwargs)
except (ValueError, TypeError, KeyError):
# if there is an error, close the store
try:
store.close()
except AttributeError:
pass
raise | [
"\n Read from the store, close it if we opened it.\n\n Retrieve pandas object stored in file, optionally based on where\n criteria\n\n Parameters\n ----------\n path_or_buf : string, buffer or path object\n Path to the file to open, or an open :class:`pandas.HDFStore` object.\n Supports any object implementing the ``__fspath__`` protocol.\n This includes :class:`pathlib.Path` and py._path.local.LocalPath\n objects.\n\n .. versionadded:: 0.19.0 support for pathlib, py.path.\n .. versionadded:: 0.21.0 support for __fspath__ protocol.\n\n key : object, optional\n The group identifier in the store. Can be omitted if the HDF file\n contains a single pandas object.\n mode : {'r', 'r+', 'a'}, optional\n Mode to use when opening the file. Ignored if path_or_buf is a\n :class:`pandas.HDFStore`. Default is 'r'.\n where : list, optional\n A list of Term (or convertible) objects.\n start : int, optional\n Row number to start selection.\n stop : int, optional\n Row number to stop selection.\n columns : list, optional\n A list of columns names to return.\n iterator : bool, optional\n Return an iterator object.\n chunksize : int, optional\n Number of rows to include in an iteration when using an iterator.\n errors : str, default 'strict'\n Specifies how encoding and decoding errors are to be handled.\n See the errors argument for :func:`open` for a full list\n of options.\n **kwargs\n Additional keyword arguments passed to HDFStore.\n\n Returns\n -------\n item : object\n The selected object. Return type depends on the object stored.\n\n See Also\n --------\n DataFrame.to_hdf : Write a HDF file from a DataFrame.\n HDFStore : Low-level access to HDF files.\n\n Examples\n --------\n >>> df = pd.DataFrame([[1, 1.0, 'a']], columns=['x', 'y', 'z'])\n >>> df.to_hdf('./store.h5', 'data')\n >>> reread = pd.read_hdf('./store.h5')\n "
] |
Please provide a description of the function:def _is_metadata_of(group, parent_group):
if group._v_depth <= parent_group._v_depth:
return False
current = group
while current._v_depth > 1:
parent = current._v_parent
if parent == parent_group and current._v_name == 'meta':
return True
current = current._v_parent
return False | [
"Check if a given group is a metadata group for a given parent_group."
] |
Please provide a description of the function:def _get_info(info, name):
try:
idx = info[name]
except KeyError:
idx = info[name] = dict()
return idx | [
" get/create the info for this name "
] |
Please provide a description of the function:def _get_tz(tz):
zone = timezones.get_timezone(tz)
if zone is None:
zone = tz.utcoffset().total_seconds()
return zone | [
" for a tz-aware type, return an encoded zone "
] |
Please provide a description of the function:def _set_tz(values, tz, preserve_UTC=False, coerce=False):
if tz is not None:
name = getattr(values, 'name', None)
values = values.ravel()
tz = timezones.get_timezone(_ensure_decoded(tz))
values = DatetimeIndex(values, name=name)
if values.tz is None:
values = values.tz_localize('UTC').tz_convert(tz)
if preserve_UTC:
if tz == 'UTC':
values = list(values)
elif coerce:
values = np.asarray(values, dtype='M8[ns]')
return values | [
"\n coerce the values to a DatetimeIndex if tz is set\n preserve the input shape if possible\n\n Parameters\n ----------\n values : ndarray\n tz : string/pickled tz object\n preserve_UTC : boolean,\n preserve the UTC of the result\n coerce : if we do not have a passed timezone, coerce to M8[ns] ndarray\n "
] |
Please provide a description of the function:def _convert_string_array(data, encoding, errors, itemsize=None):
# encode if needed
if encoding is not None and len(data):
data = Series(data.ravel()).str.encode(
encoding, errors).values.reshape(data.shape)
# create the sized dtype
if itemsize is None:
ensured = ensure_object(data.ravel())
itemsize = max(1, libwriters.max_len_string_array(ensured))
data = np.asarray(data, dtype="S{size}".format(size=itemsize))
return data | [
"\n we take a string-like that is object dtype and coerce to a fixed size\n string type\n\n Parameters\n ----------\n data : a numpy array of object dtype\n encoding : None or string-encoding\n errors : handler for encoding errors\n itemsize : integer, optional, defaults to the max length of the strings\n\n Returns\n -------\n data in a fixed-length string dtype, encoded to bytes if needed\n "
] |
Please provide a description of the function:def _unconvert_string_array(data, nan_rep=None, encoding=None,
errors='strict'):
shape = data.shape
data = np.asarray(data.ravel(), dtype=object)
# guard against a None encoding (because of a legacy
# where the passed encoding is actually None)
encoding = _ensure_encoding(encoding)
if encoding is not None and len(data):
itemsize = libwriters.max_len_string_array(ensure_object(data))
dtype = "U{0}".format(itemsize)
if isinstance(data[0], bytes):
data = Series(data).str.decode(encoding, errors=errors).values
else:
data = data.astype(dtype, copy=False).astype(object, copy=False)
if nan_rep is None:
nan_rep = 'nan'
data = libwriters.string_array_replace_from_nan_rep(data, nan_rep)
return data.reshape(shape) | [
"\n inverse of _convert_string_array\n\n Parameters\n ----------\n data : fixed length string dtyped array\n nan_rep : the storage repr of NaN, optional\n encoding : the encoding of the data, optional\n errors : handler for encoding errors, default 'strict'\n\n Returns\n -------\n an object array of the decoded data\n\n "
] |
Please provide a description of the function:def open(self, mode='a', **kwargs):
tables = _tables()
if self._mode != mode:
# if we are changing a write mode to read, ok
if self._mode in ['a', 'w'] and mode in ['r', 'r+']:
pass
elif mode in ['w']:
# this would truncate, raise here
if self.is_open:
raise PossibleDataLossError(
"Re-opening the file [{0}] with mode [{1}] "
"will delete the current file!"
.format(self._path, self._mode)
)
self._mode = mode
# close and reopen the handle
if self.is_open:
self.close()
if self._complevel and self._complevel > 0:
self._filters = _tables().Filters(self._complevel, self._complib,
fletcher32=self._fletcher32)
try:
self._handle = tables.open_file(self._path, self._mode, **kwargs)
except (IOError) as e: # pragma: no cover
if 'can not be written' in str(e):
print(
'Opening {path} in read-only mode'.format(path=self._path))
self._handle = tables.open_file(self._path, 'r', **kwargs)
else:
raise
except (ValueError) as e:
# trap PyTables >= 3.1 FILE_OPEN_POLICY exception
# to provide an updated message
if 'FILE_OPEN_POLICY' in str(e):
e = ValueError(
"PyTables [{version}] no longer supports opening multiple "
"files\n"
"even in read-only mode on this HDF5 version "
"[{hdf_version}]. You can accept this\n"
"and not open the same file multiple times at once,\n"
"upgrade the HDF5 version, or downgrade to PyTables 3.0.0 "
"which allows\n"
"files to be opened multiple times at once\n"
.format(version=tables.__version__,
hdf_version=tables.get_hdf5_version()))
raise e
except (Exception) as e:
# trying to read from a non-existent file causes an error which
# is not part of IOError, make it one
if self._mode == 'r' and 'Unable to open/create file' in str(e):
raise IOError(str(e))
raise | [
"\n Open the file in the specified mode\n\n Parameters\n ----------\n mode : {'a', 'w', 'r', 'r+'}, default 'a'\n See HDFStore docstring or tables.open_file for info about modes\n "
] |
Please provide a description of the function:def flush(self, fsync=False):
if self._handle is not None:
self._handle.flush()
if fsync:
try:
os.fsync(self._handle.fileno())
except OSError:
pass | [
"\n Force all buffered modifications to be written to disk.\n\n Parameters\n ----------\n fsync : bool (default False)\n call ``os.fsync()`` on the file handle to force writing to disk.\n\n Notes\n -----\n Without ``fsync=True``, flushing may not guarantee that the OS writes\n to disk. With fsync, the operation will block until the OS claims the\n file has been written; however, other caching layers may still\n interfere.\n "
] |
Please provide a description of the function:def get(self, key):
group = self.get_node(key)
if group is None:
raise KeyError('No object named {key} in the file'.format(key=key))
return self._read_group(group) | [
"\n Retrieve pandas object stored in file\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n obj : same type as object stored in file\n "
] |
Please provide a description of the function:def select(self, key, where=None, start=None, stop=None, columns=None,
iterator=False, chunksize=None, auto_close=False, **kwargs):
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() | [
"\n Retrieve pandas object stored in file, optionally based on where\n criteria\n\n Parameters\n ----------\n key : object\n where : list of Term (or convertible) objects, optional\n start : integer (defaults to None), row number to start selection\n stop : integer (defaults to None), row number to stop selection\n columns : a list of columns that if not None, will limit the return\n columns\n iterator : boolean, return an iterator, default False\n chunksize : nrows to include in iteration, return an iterator\n auto_close : boolean, should automatically close the store when\n finished, default is False\n\n Returns\n -------\n The selected object\n "
] |
Please provide a description of the function:def select_as_coordinates(
self, key, where=None, start=None, stop=None, **kwargs):
where = _ensure_term(where, scope_level=1)
return self.get_storer(key).read_coordinates(where=where, start=start,
stop=stop, **kwargs) | [
"\n return the selection as an Index\n\n Parameters\n ----------\n key : object\n where : list of Term (or convertible) objects, optional\n start : integer (defaults to None), row number to start selection\n stop : integer (defaults to None), row number to stop selection\n "
] |
Please provide a description of the function:def select_column(self, key, column, **kwargs):
return self.get_storer(key).read_column(column=column, **kwargs) | [
"\n return a single column from the table. This is generally only useful to\n select an indexable\n\n Parameters\n ----------\n key : object\n column: the column of interest\n\n Exceptions\n ----------\n raises KeyError if the column is not found (or key is not a valid\n store)\n raises ValueError if the column can not be extracted individually (it\n is part of a data block)\n\n "
] |
Please provide a description of the function:def select_as_multiple(self, keys, where=None, selector=None, columns=None,
start=None, stop=None, iterator=False,
chunksize=None, auto_close=False, **kwargs):
# 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) | [
" Retrieve pandas objects from multiple tables\n\n Parameters\n ----------\n keys : a list of the tables\n selector : the table to apply the where criteria (defaults to keys[0]\n if not supplied)\n columns : the columns I want back\n start : integer (defaults to None), row number to start selection\n stop : integer (defaults to None), row number to stop selection\n iterator : boolean, return an iterator, default False\n chunksize : nrows to include in iteration, return an iterator\n\n Exceptions\n ----------\n raises KeyError if keys or selector is not found or keys is empty\n raises TypeError if keys is not a list or tuple\n raises ValueError if the tables are not ALL THE SAME DIMENSIONS\n "
] |
Please provide a description of the function:def put(self, key, value, format=None, append=False, **kwargs):
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) | [
"\n Store object in HDFStore\n\n Parameters\n ----------\n key : object\n value : {Series, DataFrame}\n format : 'fixed(f)|table(t)', default is 'fixed'\n fixed(f) : Fixed format\n Fast writing/reading. Not-appendable, nor searchable\n table(t) : Table format\n Write as a PyTables Table structure which may perform\n worse but allow more flexible operations like searching\n / selecting subsets of the data\n append : boolean, default False\n This will force Table format, append the input data to the\n existing.\n data_columns : list of columns to create as data columns, or True to\n use all columns. See\n `here <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__ # noqa\n encoding : default None, provide an encoding for strings\n dropna : boolean, default False, do not write an ALL nan row to\n the store settable by the option 'io.hdf.dropna_table'\n "
] |
Please provide a description of the function: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) | [
"\n Remove pandas object partially by specifying the where condition\n\n Parameters\n ----------\n key : string\n Node to remove or delete rows from\n where : list of Term (or convertible) objects, optional\n start : integer (defaults to None), row number to start selection\n stop : integer (defaults to None), row number to stop selection\n\n Returns\n -------\n number of rows removed (or None if not a Table)\n\n Exceptions\n ----------\n raises KeyError if key is not a valid store\n\n "
] |
Please provide a description of the function:def append(self, key, value, format=None, append=True, columns=None,
dropna=None, **kwargs):
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) | [
"\n Append to Table in file. Node must already exist and be Table\n format.\n\n Parameters\n ----------\n key : object\n value : {Series, DataFrame}\n format : 'table' is the default\n table(t) : table format\n Write as a PyTables Table structure which may perform\n worse but allow more flexible operations like searching\n / selecting subsets of the data\n append : boolean, default True, append the input data to the\n existing\n data_columns : list of columns, or True, default None\n List of columns to create as indexed data columns for on-disk\n queries, or True to use all columns. By default only the axes\n of the object are indexed. See `here\n <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__.\n min_itemsize : dict of columns that specify minimum string sizes\n nan_rep : string to use as string nan represenation\n chunksize : size to chunk the writing\n expectedrows : expected TOTAL row size of this table\n encoding : default None, provide an encoding for strings\n dropna : boolean, default False, do not write an ALL nan row to\n the store settable by the option 'io.hdf.dropna_table'\n\n Notes\n -----\n Does *not* check if data being appended overlaps with existing\n data in the table, so be careful\n "
] |
Please provide a description of the function:def append_to_multiple(self, d, value, selector, data_columns=None,
axes=None, dropna=False, **kwargs):
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) | [
"\n Append to multiple tables\n\n Parameters\n ----------\n d : a dict of table_name to table_columns, None is acceptable as the\n values of one node (this will get all the remaining columns)\n value : a pandas object\n selector : a string that designates the indexable table; all of its\n columns will be designed as data_columns, unless data_columns is\n passed, in which case these are used\n data_columns : list of columns to create as data columns, or True to\n use all columns\n dropna : if evaluates to True, drop rows from all tables if any single\n row in each table has all NaN. Default False.\n\n Notes\n -----\n axes parameter is currently not accepted\n\n "
] |
Please provide a description of the function:def create_table_index(self, key, **kwargs):
# 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) | [
" Create a pytables index on the table\n Parameters\n ----------\n key : object (the node to index)\n\n Exceptions\n ----------\n raises if the node is not a table\n\n "
] |
Please provide a description of the function: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')))
] | [
"return a list of all the top-level nodes (that are not themselves a\n pandas storage object)\n "
] |
Please provide a description of the function: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) | [
" Walk the pytables group hierarchy for pandas objects\n\n This generator will yield the group path, subgroups and pandas object\n names for each group.\n Any non-pandas PyTables objects that are not a group will be ignored.\n\n The `where` group itself is listed first (preorder), then each of its\n child groups (following an alphanumerical order) is also traversed,\n following the same procedure.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n where : str, optional\n Group where to start walking.\n If not supplied, the root group is used.\n\n Yields\n ------\n path : str\n Full path to a group (without trailing '/')\n groups : list of str\n names of the groups contained in `path`\n leaves : list of str\n names of the pandas objects contained in `path`\n "
] |
Please provide a description of the function: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 | [
" return the node with the key or None if it does not exist "
] |
Please provide a description of the function:def get_storer(self, key):
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 | [
" return the storer object for a key, raise if not in the file "
] |
Please provide a description of the function:def copy(self, file, mode='w', propindexes=True, keys=None, complib=None,
complevel=None, fletcher32=False, overwrite=True):
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 | [
" copy the existing store to a new file, upgrading in place\n\n Parameters\n ----------\n propindexes: restore indexes in copied file (defaults to True)\n keys : list of keys to include in the copy (defaults to all)\n overwrite : overwrite (remove and replace) existing nodes in the\n new store (default is True)\n mode, complib, complevel, fletcher32 same as in HDFStore.__init__\n\n Returns\n -------\n open file handle of the new store\n\n "
] |
Please provide a description of the function:def info(self):
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 | [
"\n Print detailed information on the store.\n\n .. versionadded:: 0.21.0\n "
] |
Please provide a description of the function: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 | [
" validate / deprecate formats; return the new kwargs "
] |
Please provide a description of the function:def _create_storer(self, group, format=None, value=None, append=False,
**kwargs):
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') | [
" return a suitable class to operate "
] |
Please provide a description of the function: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 | [
" set the name of this indexer "
] |
Please provide a description of the function: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 | [
" set the position of this column in the Table "
] |
Please provide a description of the function:def is_indexed(self):
try:
return getattr(self.table.cols, self.cname).is_indexed
except AttributeError:
False | [
" return whether I am an indexed column "
] |
Please provide a description of the function:def infer(self, handler):
table = handler.table
new_self = self.copy()
new_self.set_table(table)
new_self.get_attr()
new_self.read_metadata(handler)
return new_self | [
"infer this column from the table: create and return a new object"
] |
Please provide a description of the function:def convert(self, values, nan_rep, encoding, errors):
# 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 | [
" set the values from this selection: take = take ownership "
] |
Please provide a description of the function:def maybe_set_size(self, min_itemsize=None):
if _ensure_decoded(self.kind) == 'string':
if isinstance(min_itemsize, dict):
min_itemsize = min_itemsize.get(self.name)
if min_itemsize is not None and self.typ.itemsize < min_itemsize:
self.typ = _tables(
).StringCol(itemsize=min_itemsize, pos=self.pos) | [
" maybe set a string col itemsize:\n min_itemsize can be an integer or a dict with this columns name\n with an integer size "
] |
Please provide a description of the function: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 | [
" validate this column: return the compared against itemsize "
] |
Please provide a description of the function:def update_info(self, info):
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 | [
" set/update the info for this indexable with the key/value\n if there is a conflict raise/warn as needed "
] |
Please provide a description of the function:def set_info(self, info):
idx = info.get(self.name)
if idx is not None:
self.__dict__.update(idx) | [
" set my state from the passed info "
] |
Please provide a description of the function: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") | [
" validate that kind=category does not change the categories "
] |
Please provide a description of the function:def write_metadata(self, handler):
if self.metadata is not None:
handler.write_metadata(self.cname, self.metadata) | [
" set the meta data "
] |
Please provide a description of the function:def convert(self, values, nan_rep, encoding, errors):
self.values = Int64Index(np.arange(self.table.nrows))
return self | [
" set the values from this selection: take = take ownership "
] |
Please provide a description of the function:def create_for_block(
cls, i=None, name=None, cname=None, version=None, **kwargs):
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) | [
" return a new datacol with the block i "
] |
Please provide a description of the function:def set_metadata(self, metadata):
if metadata is not None:
metadata = np.array(metadata, copy=False).ravel()
self.metadata = metadata | [
" record the metadata "
] |
Please provide a description of the function:def set_atom(self, block, block_items, existing_col, min_itemsize,
nan_rep, info, encoding=None, errors='strict'):
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) | [
" create and setup my atom from the block b "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.