INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Wraper for np.percentile that skips missing values, specialized to 1-dimensional case. Parameters ---------- values : array over which to find quantiles mask : ndarray[bool] locations in values that should be considered missing q : scalar or array of quantile indices to find na_valu...
def _nanpercentile_1d(values, mask, q, na_value, interpolation): """ Wraper for np.percentile that skips missing values, specialized to 1-dimensional case. Parameters ---------- values : array over which to find quantiles mask : ndarray[bool] locations in values that should be consi...
Wraper for np.percentile that skips missing values. Parameters ---------- values : array over which to find quantiles q : scalar or array of quantile indices to find axis : {0, 1} na_value : scalar value to return for empty or all-null values mask : ndarray[bool] locations i...
def nanpercentile(values, q, axis, na_value, mask, ndim, interpolation): """ Wraper for np.percentile that skips missing values. Parameters ---------- values : array over which to find quantiles q : scalar or array of quantile indices to find axis : {0, 1} na_value : scalar valu...
Method for writting a formatted <th> cell. If col_space is set on the formatter then that is used for the value of min-width. Parameters ---------- s : object The data to be written inside the cell. header : boolean, default False Set to True if ...
def write_th(self, s, header=False, indent=0, tags=None): """ Method for writting a formatted <th> cell. If col_space is set on the formatter then that is used for the value of min-width. Parameters ---------- s : object The data to be written inside...
r""" Read text from clipboard and pass to read_csv. See read_csv for the full argument list Parameters ---------- sep : str, default '\s+' A string or regex delimiter. The default of '\s+' denotes one or more whitespace characters. Returns ------- parsed : DataFrame
def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover r""" Read text from clipboard and pass to read_csv. See read_csv for the full argument list Parameters ---------- sep : str, default '\s+' A string or regex delimiter. The default of '\s+' denotes one or more whitespa...
Attempt to write text representation of object to the system clipboard The clipboard can be then pasted into Excel for example. Parameters ---------- obj : the object to write to the clipboard excel : boolean, defaults to True if True, use the provided separator, writing in a csv ...
def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover """ Attempt to write text representation of object to the system clipboard The clipboard can be then pasted into Excel for example. Parameters ---------- obj : the object to write to the clipboard excel : boolean, de...
Get an iterator given an integer, slice or container. Parameters ---------- skiprows : int, slice, container The iterator to use to skip rows; can also be a slice. Raises ------ TypeError * If `skiprows` is not a slice, integer, or Container Returns ------- it : it...
def _get_skiprows(skiprows): """Get an iterator given an integer, slice or container. Parameters ---------- skiprows : int, slice, container The iterator to use to skip rows; can also be a slice. Raises ------ TypeError * If `skiprows` is not a slice, integer, or Container ...
Try to read from a url, file or string. Parameters ---------- obj : str, unicode, or file-like Returns ------- raw_text : str
def _read(obj): """Try to read from a url, file or string. Parameters ---------- obj : str, unicode, or file-like Returns ------- raw_text : str """ if _is_url(obj): with urlopen(obj) as url: text = url.read() elif hasattr(obj, 'read'): text = obj.re...
Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- expr : unicode An XPath expression th...
def _build_xpath_expr(attrs): """Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- expr : u...
Choose the parser based on the input flavor. Parameters ---------- flavor : str The type of parser to use. This must be a valid backend. Returns ------- cls : _HtmlFrameParser subclass The parser class based on the requested input flavor. Raises ------ ValueError ...
def _parser_dispatch(flavor): """Choose the parser based on the input flavor. Parameters ---------- flavor : str The type of parser to use. This must be a valid backend. Returns ------- cls : _HtmlFrameParser subclass The parser class based on the requested input flavor. ...
r"""Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str or file-like A URL, a file-like object, or a raw string containing HTML. Note that lxml only accepts the http, ftp and file url protocols. If you have a URL that starts with ``'https'`` you...
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"...
Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables.
def parse_tables(self): """ Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables. """ tables = self._parse_tables(self._build_doc(), self.match, self.attrs) return (self._parse_thead_tbody_tfoo...
Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ----- Header and body are lists-of-lists. Top level list i...
def _parse_thead_tbody_tfoot(self, table_html): """ Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ...
Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s Returns ------- list of list Each returned row is a list of str text. Notes ----- Any cell with ``rowspan`` o...
def _expand_colspan_rowspan(self, rows): """ Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s Returns ------- list of list Each returned row is a list of str text. ...
Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of the accessor for retrieving HTML attributes Returns ...
def _handle_hidden_tables(self, tbl_list, attr_name): """ Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Nam...
Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet connection will fail. See...
def _build_doc(self): """ Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet ...
Parameters ---------- l : list of arrays Returns ------- a set of kinds that exist in this list of arrays
def get_dtype_kinds(l): """ Parameters ---------- l : list of arrays Returns ------- a set of kinds that exist in this list of arrays """ typs = set() for arr in l: dtype = arr.dtype if is_categorical_dtype(dtype): typ = 'category' elif is_s...
return appropriate class of Series concat input is either dict or array-like
def _get_series_result_type(result, objs=None): """ return appropriate class of Series concat input is either dict or array-like """ from pandas import SparseSeries, SparseDataFrame, DataFrame # concat Series with axis 1 if isinstance(result, dict): # concat Series with axis 1 ...
return appropriate class of DataFrame-like concat if all blocks are sparse, return SparseDataFrame otherwise, return 1st obj
def _get_frame_result_type(result, objs): """ return appropriate class of DataFrame-like concat if all blocks are sparse, return SparseDataFrame otherwise, return 1st obj """ if (result.blocks and ( any(isinstance(obj, ABCSparseDataFrame) for obj in objs))): from pandas.core...
provide concatenation of an array of arrays each of which is a single 'normalized' dtypes (in that for example, if it's object, then it is a non-datetimelike and provide a combined dtype for the resulting array that preserves the overall dtype if possible) Parameters ---------- to_concat : arra...
def _concat_compat(to_concat, axis=0): """ provide concatenation of an array of arrays each of which is a single 'normalized' dtypes (in that for example, if it's object, then it is a non-datetimelike and provide a combined dtype for the resulting array that preserves the overall dtype if possible) ...
Concatenate an object/categorical array of arrays, each of which is a single dtype Parameters ---------- to_concat : array of arrays axis : int Axis to provide concatenation in the current implementation this is always 0, e.g. we only have 1D categoricals Returns ------- ...
def _concat_categorical(to_concat, axis=0): """Concatenate an object/categorical array of arrays, each of which is a single dtype Parameters ---------- to_concat : array of arrays axis : int Axis to provide concatenation in the current implementation this is always 0, e.g. we on...
Combine list-like of Categorical-like, unioning categories. All categories must have the same dtype. .. versionadded:: 0.19.0 Parameters ---------- to_union : list-like of Categorical, CategoricalIndex, or Series with dtype='category' sort_categories : boolean, default False ...
def union_categoricals(to_union, sort_categories=False, ignore_order=False): """ Combine list-like of Categorical-like, unioning categories. All categories must have the same dtype. .. versionadded:: 0.19.0 Parameters ---------- to_union : list-like of Categorical, CategoricalIndex, ...
provide concatenation of an datetimelike array of arrays each of which is a single M8[ns], datetimet64[ns, tz] or m8[ns] dtype Parameters ---------- to_concat : array of arrays axis : axis to provide concatenation typs : set of to_concat dtypes Returns ------- a single array, prese...
def _concat_datetime(to_concat, axis=0, typs=None): """ provide concatenation of an datetimelike array of arrays each of which is a single M8[ns], datetimet64[ns, tz] or m8[ns] dtype Parameters ---------- to_concat : array of arrays axis : axis to provide concatenation typs : set of to_...
concat DatetimeIndex with the same tz all inputs must be DatetimeIndex it is used in DatetimeIndex.append also
def _concat_datetimetz(to_concat, name=None): """ concat DatetimeIndex with the same tz all inputs must be DatetimeIndex it is used in DatetimeIndex.append also """ # Right now, internals will pass a List[DatetimeArray] here # for reductions like quantile. I would like to disentangle # a...
concat all inputs as object. DatetimeIndex, TimedeltaIndex and PeriodIndex are converted to object dtype before concatenation
def _concat_index_asobject(to_concat, name=None): """ concat all inputs as object. DatetimeIndex, TimedeltaIndex and PeriodIndex are converted to object dtype before concatenation """ from pandas import Index from pandas.core.arrays import ExtensionArray klasses = (ABCDatetimeIndex, ABCTime...
provide concatenation of an sparse/dense array of arrays each of which is a single dtype Parameters ---------- to_concat : array of arrays axis : axis to provide concatenation typs : set of to_concat dtypes Returns ------- a single array, preserving the combined dtypes
def _concat_sparse(to_concat, axis=0, typs=None): """ provide concatenation of an sparse/dense array of arrays each of which is a single dtype Parameters ---------- to_concat : array of arrays axis : axis to provide concatenation typs : set of to_concat dtypes Returns ------- ...
Concatenates multiple RangeIndex instances. All members of "indexes" must be of type RangeIndex; result will be RangeIndex if possible, Int64Index otherwise. E.g.: indexes = [RangeIndex(3), RangeIndex(3, 6)] -> RangeIndex(6) indexes = [RangeIndex(3), RangeIndex(4, 6)] -> Int64Index([0,1,2,4,5])
def _concat_rangeindex_same_dtype(indexes): """ Concatenates multiple RangeIndex instances. All members of "indexes" must be of type RangeIndex; result will be RangeIndex if possible, Int64Index otherwise. E.g.: indexes = [RangeIndex(3), RangeIndex(3, 6)] -> RangeIndex(6) indexes = [RangeIndex(3...
Rewrite the message of an exception.
def rewrite_exception(old_name, new_name): """Rewrite the message of an exception.""" 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 ...
Given an index, find the level length for each element. Optional argument is a list of index positions which should not be visible. Result is a dictionary of (level, inital_position): span
def _get_level_lengths(index, hidden_elements=None): """ Given an index, find the level length for each element. Optional argument is a list of index positions which should not be visible. Result is a dictionary of (level, inital_position): span """ sentinel = object() levels = index.f...
Convert the DataFrame in `self.data` and the attrs from `_build_styles` into a dictionary of {head, body, uuid, cellstyle}.
def _translate(self): """ Convert the DataFrame in `self.data` and the attrs from `_build_styles` into a dictionary of {head, body, uuid, cellstyle}. """ table_styles = self.table_styles or [] caption = self.caption ctx = self.ctx precision = self.precisio...
Format the text display value of cells. .. versionadded:: 0.18.0 Parameters ---------- formatter : str, callable, or dict subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements ``formatter`` is applied to. Returns ...
def format(self, formatter, subset=None): """ Format the text display value of cells. .. versionadded:: 0.18.0 Parameters ---------- formatter : str, callable, or dict subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements...
Execute the style functions built up in `self._todo`. Relies on the conventions that all style functions go through .apply or .applymap. The append styles to apply as tuples of (application method, *args, **kwargs)
def _compute(self): """ Execute the style functions built up in `self._todo`. Relies on the conventions that all style functions go through .apply or .applymap. The append styles to apply as tuples of (application method, *args, **kwargs) """ r = self fo...
Update the state of the Styler. Collects a mapping of {index_label: ['<property>: <value>']}. attrs : Series or DataFrame should contain strings of '<property>: <value>;<prop2>: <val2>' Whitespace shouldn't matter and the final trailing ';' shouldn't matter.
def _update_ctx(self, attrs): """ Update the state of the Styler. Collects a mapping of {index_label: ['<property>: <value>']}. attrs : Series or DataFrame should contain strings of '<property>: <value>;<prop2>: <val2>' Whitespace shouldn't matter and the final trailing...
Apply a function column-wise, row-wise, or table-wise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a Series or DataFrame (depending on ``axis``), and return an object with the same shape. ...
def apply(self, func, axis=0, subset=None, **kwargs): """ Apply a function column-wise, row-wise, or table-wise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a Series or DataFrame (depending ...
Apply a function elementwise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a scalar and return a scalar subset : IndexSlice a valid indexer to limit ``data`` to *before* applying the ...
def applymap(self, func, subset=None, **kwargs): """ Apply a function elementwise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a scalar and return a scalar subset : IndexSlice ...
Apply a function elementwise, updating the HTML representation with a style which is selected in accordance with the return value of a function. .. versionadded:: 0.21.0 Parameters ---------- cond : callable ``cond`` should take a scalar and return a boolean...
def where(self, cond, value, other=None, subset=None, **kwargs): """ Apply a function elementwise, updating the HTML representation with a style which is selected in accordance with the return value of a function. .. versionadded:: 0.21.0 Parameters ---------- ...
Hide columns from rendering. .. versionadded:: 0.23.0 Parameters ---------- subset : IndexSlice An argument to ``DataFrame.loc`` that identifies which columns are hidden. Returns ------- self : Styler
def hide_columns(self, subset): """ Hide columns from rendering. .. versionadded:: 0.23.0 Parameters ---------- subset : IndexSlice An argument to ``DataFrame.loc`` that identifies which columns are hidden. Returns ------- ...
Shade the background ``null_color`` for missing values. Parameters ---------- null_color : str Returns ------- self : Styler
def highlight_null(self, null_color='red'): """ Shade the background ``null_color`` for missing values. Parameters ---------- null_color : str Returns ------- self : Styler """ self.applymap(self._highlight_null, null_color=null_color) ...
Color the background in a gradient according to the data in each column (optionally row). Requires matplotlib. Parameters ---------- cmap : str or colormap matplotlib colormap low, high : float compress the range by these values. axis : {...
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, subset=None, text_color_threshold=0.408): """ Color the background in a gradient according to the data in each column (optionally row). Requires matplotlib. Parameters --------...
Color background in a range according to the data.
def _background_gradient(s, cmap='PuBu', low=0, high=0, text_color_threshold=0.408): """ Color background in a range according to the data. """ if (not isinstance(text_color_threshold, (float, int)) or not 0 <= text_color_threshold <= 1): ...
Convenience method for setting one or more non-data dependent properties or each cell. Parameters ---------- subset : IndexSlice a valid slice for ``data`` to limit the style application to kwargs : dict property: value pairs to be set for each cell ...
def set_properties(self, subset=None, **kwargs): """ Convenience method for setting one or more non-data dependent properties or each cell. Parameters ---------- subset : IndexSlice a valid slice for ``data`` to limit the style application to kwargs :...
Draw bar chart in dataframe cells.
def _bar(s, align, colors, width=100, vmin=None, vmax=None): """ Draw bar chart in dataframe cells. """ # 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 e...
Highlight the maximum by shading the background. Parameters ---------- subset : IndexSlice, default None a valid slice for ``data`` to limit the style application to. color : str, default 'yellow' axis : {0 or 'index', 1 or 'columns', None}, default 0 app...
def highlight_max(self, subset=None, color='yellow', axis=0): """ Highlight the maximum by shading the background. Parameters ---------- subset : IndexSlice, default None a valid slice for ``data`` to limit the style application to. color : str, default 'yell...
Highlight the minimum by shading the background. Parameters ---------- subset : IndexSlice, default None a valid slice for ``data`` to limit the style application to. color : str, default 'yellow' axis : {0 or 'index', 1 or 'columns', None}, default 0 app...
def highlight_min(self, subset=None, color='yellow', axis=0): """ Highlight the minimum by shading the background. Parameters ---------- subset : IndexSlice, default None a valid slice for ``data`` to limit the style application to. color : str, default 'yell...
Highlight the min or max in a Series or DataFrame.
def _highlight_extrema(data, color='yellow', max_=True): """ Highlight the min or max in a Series or DataFrame. """ attr = 'background-color: {0}'.format(color) if data.ndim == 1: # Series from .apply if max_: extrema = data == data.max() ...
Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates name : str Name of your custom template to use for re...
def from_custom_template(cls, searchpath, name): """ Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates ...
Parameters ---------- dtype : ExtensionDtype
def register(self, dtype): """ Parameters ---------- dtype : ExtensionDtype """ if not issubclass(dtype, (PandasExtensionDtype, ExtensionDtype)): raise ValueError("can only register pandas extension dtypes") self.dtypes.append(dtype)
Parameters ---------- dtype : PandasExtensionDtype or string Returns ------- return the first matching dtype, otherwise return None
def find(self, dtype): """ Parameters ---------- dtype : PandasExtensionDtype or string Returns ------- return the first matching dtype, otherwise return None """ if not isinstance(dtype, str): dtype_type = dtype if not isi...
provide compat for construction of strings to numpy datetime64's with tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation warning, when need to pass '2015-01-01 09:00:00'
def np_datetime64_compat(s, *args, **kwargs): """ provide compat for construction of strings to numpy datetime64's with tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation warning, when need to pass '2015-01-01 09:00:00' """ s = tz_replacer(s) return np.datetime64(s, *args...
provide compat for construction of an array of strings to a np.array(..., dtype=np.datetime64(..)) tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation warning, when need to pass '2015-01-01 09:00:00'
def np_array_datetime64_compat(arr, *args, **kwargs): """ provide compat for construction of an array of strings to a np.array(..., dtype=np.datetime64(..)) tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation warning, when need to pass '2015-01-01 09:00:00' """ # is_list_l...
Ensure incoming data can be represented as ints.
def _assert_safe_casting(cls, data, subarr): """ Ensure incoming data can be represented as ints. """ if not issubclass(data.dtype.type, np.signedinteger): if not np.array_equal(data, subarr): raise TypeError('Unsafe NumPy casting, you must ' ...
we always want to get an index value, never a value
def get_value(self, series, key): """ we always want to get an index value, never a value """ 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_val...
Determines if two Index objects contain the same elements.
def equals(self, other): """ Determines if two Index objects contain the same elements. """ 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 ...
if we have bytes, decode them to unicode
def _ensure_decoded(s): """ if we have bytes, decode them to unicode """ if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s
ensure that the where is a Term or a list of Term this makes sure that we are capturing the scope of variables that are passed create the terms here with a frame_level=2 (we are 2 levels down)
def _ensure_term(where, scope_level): """ ensure that the where is a Term or a list of Term this makes sure that we are capturing the scope of variables that are passed create the terms here with a frame_level=2 (we are 2 levels down) """ # only consider list/tuple here as an ndarray is aut...
Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : string, buffer or path object Path to the file to open, or an open :class:`pandas.HDFStore` object. Supports any object imple...
def read_hdf(path_or_buf, key=None, mode='r', **kwargs): """ Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : string, buffer or path object Path to the file to open, or an op...
store this object, close it if we opened it
def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, append=None, **kwargs): """ store this object, close it if we opened it """ if append: f = lambda store: store.append(key, value, **kwargs) else: f = lambda store: store.put(key, value, **kwargs) pa...
Check if a given group is a metadata group for a given parent_group.
def _is_metadata_of(group, parent_group): """Check if a given group is a metadata group for a given 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 curr...
get/create the info for this name
def _get_info(info, name): """ get/create the info for this name """ try: idx = info[name] except KeyError: idx = info[name] = dict() return idx
coerce the values to a DatetimeIndex if tz is set preserve the input shape if possible Parameters ---------- values : ndarray tz : string/pickled tz object preserve_UTC : boolean, preserve the UTC of the result coerce : if we do not have a passed timezone, coerce to M8[ns] ndarray
def _set_tz(values, tz, preserve_UTC=False, coerce=False): """ coerce the values to a DatetimeIndex if tz is set preserve the input shape if possible Parameters ---------- values : ndarray tz : string/pickled tz object preserve_UTC : boolean, preserve the UTC of the result c...
for a tz-aware type, return an encoded zone
def _get_tz(tz): """ for a tz-aware type, return an encoded zone """ zone = timezones.get_timezone(tz) if zone is None: zone = tz.utcoffset().total_seconds() return zone
we take a string-like that is object dtype and coerce to a fixed size string type Parameters ---------- data : a numpy array of object dtype encoding : None or string-encoding errors : handler for encoding errors itemsize : integer, optional, defaults to the max length of the strings R...
def _convert_string_array(data, encoding, errors, itemsize=None): """ we take a string-like that is object dtype and coerce to a fixed size string type Parameters ---------- data : a numpy array of object dtype encoding : None or string-encoding errors : handler for encoding errors ...
inverse of _convert_string_array Parameters ---------- data : fixed length string dtyped array nan_rep : the storage repr of NaN, optional encoding : the encoding of the data, optional errors : handler for encoding errors, default 'strict' Returns ------- an object array of the dec...
def _unconvert_string_array(data, nan_rep=None, encoding=None, errors='strict'): """ inverse of _convert_string_array Parameters ---------- data : fixed length string dtyped array nan_rep : the storage repr of NaN, optional encoding : the encoding of the data, op...
Open the file in the specified mode Parameters ---------- mode : {'a', 'w', 'r', 'r+'}, default 'a' See HDFStore docstring or tables.open_file for info about modes
def open(self, mode='a', **kwargs): """ Open the file in the specified mode Parameters ---------- mode : {'a', 'w', 'r', 'r+'}, default 'a' See HDFStore docstring or tables.open_file for info about modes """ tables = _tables() if self._mode !...
Force all buffered modifications to be written to disk. Parameters ---------- fsync : bool (default False) call ``os.fsync()`` on the file handle to force writing to disk. Notes ----- Without ``fsync=True``, flushing may not guarantee that the OS writes ...
def flush(self, fsync=False): """ Force all buffered modifications to be written to disk. Parameters ---------- fsync : bool (default False) call ``os.fsync()`` on the file handle to force writing to disk. Notes ----- Without ``fsync=True``, fl...
Retrieve pandas object stored in file Parameters ---------- key : object Returns ------- obj : same type as object stored in file
def get(self, key): """ Retrieve pandas object stored in file Parameters ---------- key : object Returns ------- obj : same type as object stored in file """ group = self.get_node(key) if group is None: raise KeyError(...
Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- key : object where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to Non...
def select(self, key, where=None, start=None, stop=None, columns=None, iterator=False, chunksize=None, auto_close=False, **kwargs): """ Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- key : object whe...
return a single column from the table. This is generally only useful to select an indexable Parameters ---------- key : object column: the column of interest Exceptions ---------- raises KeyError if the column is not found (or key is not a valid ...
def select_column(self, key, column, **kwargs): """ return a single column from the table. This is generally only useful to select an indexable Parameters ---------- key : object column: the column of interest Exceptions ---------- raises...
Retrieve pandas objects from multiple tables Parameters ---------- keys : a list of the tables selector : the table to apply the where criteria (defaults to keys[0] if not supplied) columns : the columns I want back start : integer (defaults to None), row num...
def select_as_multiple(self, keys, where=None, selector=None, columns=None, start=None, stop=None, iterator=False, chunksize=None, auto_close=False, **kwargs): """ Retrieve pandas objects from multiple tables Parameters ---------- ke...
return the selection as an Index Parameters ---------- key : object where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection
def select_as_coordinates( self, key, where=None, start=None, stop=None, **kwargs): """ return the selection as an Index Parameters ---------- key : object where : list of Term (or convertible) objects, optional start : integer (defaults to None), row...
Store object in HDFStore Parameters ---------- key : object value : {Series, DataFrame} format : 'fixed(f)|table(t)', default is 'fixed' fixed(f) : Fixed format Fast writing/reading. Not-appendable, nor searchable table(t)...
def put(self, key, value, format=None, append=False, **kwargs): """ Store object in HDFStore Parameters ---------- key : object value : {Series, DataFrame} format : 'fixed(f)|table(t)', default is 'fixed' fixed(f) : Fixed format ...
Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection st...
def remove(self, key, where=None, start=None, stop=None): """ Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional ...
Append to Table in file. Node must already exist and be Table format. Parameters ---------- key : object value : {Series, DataFrame} format : 'table' is the default table(t) : table format Write as a PyTables Table structure which may p...
def append(self, key, value, format=None, append=True, columns=None, dropna=None, **kwargs): """ Append to Table in file. Node must already exist and be Table format. Parameters ---------- key : object value : {Series, DataFrame} format : '...
Append to multiple tables Parameters ---------- d : a dict of table_name to table_columns, None is acceptable as the values of one node (this will get all the remaining columns) value : a pandas object selector : a string that designates the indexable table; all of i...
def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, dropna=False, **kwargs): """ Append to multiple tables Parameters ---------- d : a dict of table_name to table_columns, None is acceptable as the values of one n...
Create a pytables index on the table Parameters ---------- key : object (the node to index) Exceptions ---------- raises if the node is not a table
def create_table_index(self, key, **kwargs): """ Create a pytables index on the table Parameters ---------- key : object (the node to index) Exceptions ---------- raises if the node is not a table """ # version requirements _tables() ...
return a list of all the top-level nodes (that are not themselves a pandas storage object)
def groups(self): """return a list of all the top-level nodes (that are not themselves a pandas storage object) """ _tables() self._check_if_open() return [ g for g in self._handle.walk_groups() if (not isinstance(g, _table_mod.link.Link) and ...
Walk the pytables group hierarchy for pandas objects This generator will yield the group path, subgroups and pandas object names for each group. Any non-pandas PyTables objects that are not a group will be ignored. The `where` group itself is listed first (preorder), then each of its ...
def walk(self, where="/"): """ Walk the pytables group hierarchy for pandas objects This generator will yield the group path, subgroups and pandas object names for each group. Any non-pandas PyTables objects that are not a group will be ignored. The `where` group itself is list...
return the node with the key or None if it does not exist
def get_node(self, key): """ return the node with the key or None if it does not exist """ self._check_if_open() try: if not key.startswith('/'): key = '/' + key return self._handle.get_node(self.root, key) except _table_mod.exceptions.NoSuchNodeEr...
return the storer object for a key, raise if not in the file
def get_storer(self, key): """ return the storer object for a key, raise if not in the file """ group = self.get_node(key) if group is None: raise KeyError('No object named {key} in the file'.format(key=key)) s = self._create_storer(group) s.infer_axes() retu...
copy the existing store to a new file, upgrading in place Parameters ---------- propindexes: restore indexes in copied file (defaults to True) keys : list of keys to include in the copy (defaults to all) overwrite : overwrite (remove and replace) exist...
def copy(self, file, mode='w', propindexes=True, keys=None, complib=None, complevel=None, fletcher32=False, overwrite=True): """ copy the existing store to a new file, upgrading in place Parameters ---------- propindexes: restore indexes in copied file (defaults...
Print detailed information on the store. .. versionadded:: 0.21.0
def info(self): """ Print detailed information on the store. .. versionadded:: 0.21.0 """ output = '{type}\nFile path: {path}\n'.format( type=type(self), path=pprint_thing(self._path)) if self.is_open: lkeys = sorted(list(self.keys())) ...
validate / deprecate formats; return the new kwargs
def _validate_format(self, format, kwargs): """ validate / deprecate formats; return the new kwargs """ kwargs = kwargs.copy() # validate try: kwargs['format'] = _FORMAT_MAP[format.lower()] except KeyError: raise TypeError("invalid HDFStore format specifi...
return a suitable class to operate
def _create_storer(self, group, format=None, value=None, append=False, **kwargs): """ return a suitable class to operate """ def error(t): raise TypeError( "cannot properly create the storer for: [{t}] [group->" "{group},value->{value},...
set the name of this indexer
def set_name(self, name, kind_attr=None): """ set the name of this indexer """ 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 position of this column in the Table
def set_pos(self, pos): """ set the position of this column in the Table """ self.pos = pos if pos is not None and self.typ is not None: self.typ._v_pos = pos return self
return whether I am an indexed column
def is_indexed(self): """ return whether I am an indexed column """ try: return getattr(self.table.cols, self.cname).is_indexed except AttributeError: False
infer this column from the table: create and return a new object
def infer(self, handler): """infer this column from the table: create and return a new object""" table = handler.table new_self = self.copy() new_self.set_table(table) new_self.get_attr() new_self.read_metadata(handler) return new_self
set the values from this selection: take = take ownership
def convert(self, values, nan_rep, encoding, errors): """ set the values from this selection: take = take ownership """ # values is a recarray if values.dtype.fields is not None: values = values[self.cname] values = _maybe_convert(values, self.kind, encoding, errors) ...
maybe set a string col itemsize: min_itemsize can be an integer or a dict with this columns name with an integer size
def maybe_set_size(self, min_itemsize=None): """ maybe set a string col itemsize: min_itemsize can be an integer or a dict with this columns name with an integer size """ if _ensure_decoded(self.kind) == 'string': if isinstance(min_itemsize, dict): ...
validate this column: return the compared against itemsize
def validate_col(self, itemsize=None): """ validate this column: return the compared against itemsize """ # 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 ...
set/update the info for this indexable with the key/value if there is a conflict raise/warn as needed
def update_info(self, info): """ set/update the info for this indexable with the key/value if there is a conflict raise/warn as needed """ for key in self._info_fields: value = getattr(self, key, None) idx = _get_info(info, self.name) existing_value = i...
set my state from the passed info
def set_info(self, info): """ set my state from the passed info """ idx = info.get(self.name) if idx is not None: self.__dict__.update(idx)
validate that kind=category does not change the categories
def validate_metadata(self, handler): """ validate that kind=category does not change the categories """ 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...
set the meta data
def write_metadata(self, handler): """ set the meta data """ if self.metadata is not None: handler.write_metadata(self.cname, self.metadata)
set the values from this selection: take = take ownership
def convert(self, values, nan_rep, encoding, errors): """ set the values from this selection: take = take ownership """ self.values = Int64Index(np.arange(self.table.nrows)) return self
return a new datacol with the block i
def create_for_block( cls, i=None, name=None, cname=None, version=None, **kwargs): """ return a new datacol with the block i """ if cname is None: cname = name or 'values_block_{idx}'.format(idx=i) if name is None: name = cname # prior to 0.10.1, we ...
record the metadata
def set_metadata(self, metadata): """ record the metadata """ if metadata is not None: metadata = np.array(metadata, copy=False).ravel() self.metadata = metadata
create and setup my atom from the block b
def set_atom(self, block, block_items, existing_col, min_itemsize, nan_rep, info, encoding=None, errors='strict'): """ create and setup my atom from the block b """ self.values = list(block_items) # short-cut certain block types if block.is_categorical: ret...
return the PyTables column class for this column
def get_atom_coltype(self, kind=None): """ return the PyTables column class for this column """ if kind is None: kind = self.kind if self.kind.startswith('uint'): col_name = "UInt{name}Col".format(name=kind[4:]) else: col_name = "{name}Col".format(name...
validate that we have the same order as the existing & same dtype
def validate_attr(self, append): """validate that we have the same order as the existing & same dtype""" if append: existing_fields = getattr(self.attrs, self.kind_attr, None) if (existing_fields is not None and existing_fields != list(self.values)): ...
set the data from this selection (and convert to the correct dtype if we can)
def convert(self, values, nan_rep, encoding, errors): """set the data from this selection (and convert to the correct dtype if we can) """ # values is a recarray if values.dtype.fields is not None: values = values[self.cname] self.set_data(values) #...