Code
stringlengths
103
85.9k
Summary
listlengths
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(): ...
[ "\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_valu...
[ "\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 ...
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...
[ "\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]...
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)) ...
[ "\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 ...
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('-', '') != 'u...
[ "\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 ...
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': ra...
[ "\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, writi...
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: ...
[ "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 -...
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): ...
[ "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}]'.f...
[ "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 XPa...
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...
[ "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 -----...
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_...
[ "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 ``'http...
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 al...
[ "\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...
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 = [] ...
[ "\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 ...
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...
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 urlo...
[ "\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 ...
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): t...
[ "\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, SparseDataFr...
[ "\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...
[ "\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'...
[ "\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 ...
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_dt...
[ "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...
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('N...
[ "\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 : boolea...
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) ...
[ "\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 ...
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, ABCIndex...
[ "\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 isin...
[ "\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 ...
[ "\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 combin...
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...
[ "\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...
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 = arg...
[ "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,...
[ "\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.uu...
[ "\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: ...
[ "\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 ...
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 ha...
[ "\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 te...
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 p...
[ "\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 matte...
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 ...
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...
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 sca...
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._bac...
[ "\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...
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_th...
[ "\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 ...
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 ...
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 ...
[ "\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_l...
[ "\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`` o...
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}, def...
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}, def...
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...
[ "\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_te...
[ "\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...
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 ...
[ "\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, **kwar...
[ "\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 ...
[ "\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...
[ "\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, whe...
[ "\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_...
[ " 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 i...
[ "\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 Suppo...
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': ...
[ "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) ...
[ "\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...
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 ...
[ "\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...
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 encodin...
[ "\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 o...
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 [...
[ "\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 t...
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 f...
[ "\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 : i...
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, ...
[ "\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 sele...
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 ke...
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 = ...
[ " 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 ...
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=appe...
[ "\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 searchab...
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 ...
[ "\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 star...
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") ...
[ "\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 Tab...
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" ...
[ "\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 ind...
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 ind...
[ " 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 ...
[ "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 = [...
[ " 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 e...
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: ret...
[ " 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=comple...
[ " 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 re...
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 = [] ...
[ "\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}]" ...
[ " 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->{valu...
[ " 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() ...
[ " 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 ...
[ " 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: ...
[ " 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_val...
[ " 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 ...
[ " 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 ...
[ " 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 ...
[ " create and setup my atom from the block b " ]