text
stringlengths
81
112k
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) ...
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 ...
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 ...
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:]) el...
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 ...
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 ...
get the data for this column def get_attr(self): """ get the data for this column """ self.values = getattr(self.attrs, self.kind_attr, None) self.dtype = getattr(self.attrs, self.dtype_attr, None) self.meta = getattr(self.attrs, self.meta_attr, None) self.set_kind()
set the data for this column def set_attr(self): """ set the data for this column """ setattr(self.attrs, self.kind_attr, self.values) setattr(self.attrs, self.meta_attr, self.meta) if self.dtype is not None: setattr(self.attrs, self.dtype_attr, self.dtype)
compute and set our version def set_version(self): """ compute and set our version """ version = _ensure_decoded( getattr(self.group._v_attrs, 'pandas_version', None)) try: self.version = tuple(int(x) for x in version.split('.')) if len(self.version) == 2: ...
set my pandas type & version def set_object_info(self): """ set my pandas type & version """ self.attrs.pandas_type = str(self.pandas_kind) self.attrs.pandas_version = str(_version) self.set_version()
infer the axes of my storer return a boolean indicating if we have a valid storer or not def infer_axes(self): """ infer the axes of my storer return a boolean indicating if we have a valid storer or not """ s = self.storable if s is None: return False ...
support fully deleting the node in its entirety (only) - where specification must be None def delete(self, where=None, start=None, stop=None, **kwargs): """ support fully deleting the node in its entirety (only) - where specification must be None """ if com._all_none(whe...
remove table keywords from kwargs and return raise if any keywords are passed which are not-None def validate_read(self, kwargs): """ remove table keywords from kwargs and return raise if any keywords are passed which are not-None """ kwargs = copy.copy(kwargs) ...
set our object attributes def set_attrs(self): """ set our object attributes """ self.attrs.encoding = self.encoding self.attrs.errors = self.errors
retrieve our attributes def get_attrs(self): """ retrieve our attributes """ self.encoding = _ensure_encoding(getattr(self.attrs, 'encoding', None)) self.errors = _ensure_decoded(getattr(self.attrs, 'errors', 'strict')) for n in self.attributes: setattr(self, n, _ensure_deco...
read an array for the specified node (off of group def read_array(self, key, start=None, stop=None): """ read an array for the specified node (off of group """ import tables node = getattr(self.group, key) attrs = node._v_attrs transposed = getattr(attrs, 'transposed', False) ...
write a 0-len array def write_array_empty(self, key, value): """ write a 0-len array """ # ugly hack for length 0 axes arr = np.empty((1,) * value.ndim) self._handle.create_array(self.group, key, arr) getattr(self.group, key)._v_attrs.value_type = str(value.dtype) getat...
we don't support start, stop kwds in Sparse def validate_read(self, kwargs): """ we don't support start, stop kwds in Sparse """ kwargs = super().validate_read(kwargs) if 'start' in kwargs or 'stop' in kwargs: raise NotImplementedError("start and/or stop are not supp...
write it as a collection of individual sparse series def write(self, obj, **kwargs): """ write it as a collection of individual sparse series """ super().write(obj, **kwargs) for name, ss in obj.items(): key = 'sparse_series_{name}'.format(name=name) if key not in self.g...
validate against an existing table def validate(self, other): """ validate against an existing table """ if other is None: return if other.table_type != self.table_type: raise TypeError( "incompatible table_type with existing " "[{other} ...
create / validate metadata def validate_metadata(self, existing): """ create / validate metadata """ self.metadata = [ c.name for c in self.values_axes if c.metadata is not None]
validate that we can store the multi-index; reset and return the new object def validate_multiindex(self, obj): """validate that we can store the multi-index; reset and return the new object """ levels = [l if l is not None else "level_{0}".format(i) for i, l i...
based on our axes, compute the expected nrows def nrows_expected(self): """ based on our axes, compute the expected nrows """ return np.prod([i.cvalues.shape[0] for i in self.index_axes])
return a tuple of my permutated axes, non_indexable at the front def data_orientation(self): """return a tuple of my permutated axes, non_indexable at the front""" return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes], [int(a.axis) for a in self.inde...
return a dict of the kinds allowable columns for this object def queryables(self): """ return a dict of the kinds allowable columns for this object """ # compute the values_axes queryables return dict( [(a.cname, a) for a in self.index_axes] + [(self.storage_obj_type._A...
return the metadata pathname for this key def _get_metadata_path(self, key): """ return the metadata pathname for this key """ return "{group}/meta/{key}/meta".format(group=self.group._v_pathname, key=key)
write out a meta data array to the key as a fixed-format Series Parameters ---------- key : string values : ndarray def write_metadata(self, key, values): """ write out a meta data array to the key as a fixed-format Series Parameters ---------- ...
return the meta data array for this key def read_metadata(self, key): """ return the meta data array for this key """ if getattr(getattr(self.group, 'meta', None), key, None) is not None: return self.parent.select(self._get_metadata_path(key)) return None
set our table type & indexables def set_attrs(self): """ set our table type & indexables """ self.attrs.table_type = str(self.table_type) self.attrs.index_cols = self.index_cols() self.attrs.values_cols = self.values_cols() self.attrs.non_index_axes = self.non_index_axes ...
retrieve our attributes def get_attrs(self): """ retrieve our attributes """ self.non_index_axes = getattr( self.attrs, 'non_index_axes', None) or [] self.data_columns = getattr( self.attrs, 'data_columns', None) or [] self.info = getattr( self.attrs,...
are we trying to operate on an old version? def validate_version(self, where=None): """ are we trying to operate on an old version? """ if where is not None: if (self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1): ws = incompatibility...
validate the min_itemisze doesn't contain items that are not in the axes this needs data_columns to be defined def validate_min_itemsize(self, min_itemsize): """validate the min_itemisze doesn't contain items that are not in the axes this needs data_columns to be defined """ if ...
create/cache the indexables if they don't exist def indexables(self): """ create/cache the indexables if they don't exist """ if self._indexables is None: self._indexables = [] # index columns self._indexables.extend([ IndexCol(name=name, axis=axis,...
Create a pytables index on the specified columns note: cannot index Time64Col() or ComplexCol currently; PyTables must be >= 3.0 Parameters ---------- columns : False (don't create an index), True (create all columns index), None or list_like (the indexers to ind...
create and return the axes sniffed from the table: return boolean for success def read_axes(self, where, **kwargs): """create and return the axes sniffed from the table: return boolean for success """ # validate the version self.validate_version(where) # infer ...
take the input data_columns and min_itemize and create a data columns spec def validate_data_columns(self, data_columns, min_itemsize): """take the input data_columns and min_itemize and create a data columns spec """ if not len(self.non_index_axes): return [] ...
create and return the axes leagcy tables create an indexable column, indexable index, non-indexable fields Parameters: ----------- axes: a list of the axes in order to create (names or numbers of the axes) obj : the object to create axes o...
process axes filters def process_axes(self, obj, columns=None): """ process axes filters """ # make a copy to avoid side effects if columns is not None: columns = list(columns) # make sure to include levels if we have them if columns is not None and self.is_multi_i...
create the description of the table from the axes & values def create_description(self, complib=None, complevel=None, fletcher32=False, expectedrows=None): """ create the description of the table from the axes & values """ # provided expected rows if its passed if ex...
select coordinates (row numbers) from a table; return the coordinates object def read_coordinates(self, where=None, start=None, stop=None, **kwargs): """select coordinates (row numbers) from a table; return the coordinates object """ # validate the version self.validate...
return a single column from the table, generally only indexables are interesting def read_column(self, column, where=None, start=None, stop=None): """return a single column from the table, generally only indexables are interesting """ # validate the version self.validat...
we have n indexable columns, with an arbitrary number of data axes def read(self, where=None, columns=None, **kwargs): """we have n indexable columns, with an arbitrary number of data axes """ if not self.read_axes(where=where, **kwargs): return None raise ...
we form the data into a 2-d including indexes,values,mask write chunk-by-chunk def write_data(self, chunksize, dropna=False): """ we form the data into a 2-d including indexes,values,mask write chunk-by-chunk """ names = self.dtype.names nrows = self.nrows_expected ...
Parameters ---------- rows : an empty memory space where we are putting the chunk indexes : an array of the indexes mask : an array of the masks values : an array of the values def write_data_chunk(self, rows, indexes, mask, values): """ Parameters ------...
we are going to write this as a frame table def write(self, obj, data_columns=None, **kwargs): """ we are going to write this as a frame table """ if not isinstance(obj, DataFrame): name = obj.name or 'values' obj = DataFrame({name: obj}, index=obj.index) obj.columns...
we are going to write this as a frame table def write(self, obj, **kwargs): """ we are going to write this as a frame table """ name = obj.name or 'values' obj, self.levels = self.validate_multiindex(obj) cols = list(self.levels) cols.append(name) obj.columns = cols ...
retrieve our attributes def get_attrs(self): """ retrieve our attributes """ self.non_index_axes = [] self.nan_rep = None self.levels = [] self.index_axes = [a.infer(self) for a in self.indexables if a.is_an_indexable] self.values_axes = [a.in...
create the indexables from the table description def indexables(self): """ create the indexables from the table description """ if self._indexables is None: d = self.description # the index columns is just a simple index self._indexables = [GenericIndexCol(name='in...
where can be a : dict,list,tuple,string def generate(self, where): """ where can be a : dict,list,tuple,string """ if where is None: return None q = self.table.queryables() try: return Expr(where, queryables=q, encoding=self.table.encoding) except NameEr...
generate the selection def select(self): """ generate the selection """ if self.condition is not None: return self.table.table.read_where(self.condition.format(), start=self.start, ...
generate the selection def select_coords(self): """ generate the selection """ start, stop = self.start, self.stop nrows = self.table.nrows if start is None: start = 0 elif start < 0: start += nrows if self.stop is None: ...
Cast to a NumPy array with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If False, a copy is made only if the old dtype ...
Return the indices that would sort this array. Parameters ---------- ascending : bool, default True Whether the indices should result in an ascending or descending sort. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. ...
Fill NA/NaN values using the specified method. Parameters ---------- value : scalar, array-like If a scalar value is passed it is used to fill all missing values. Alternatively, an array-like 'value' can be given. It's expected that the array-like have the sa...
Shift values by desired number. Newly introduced missing values are filled with ``self.dtype.na_value``. .. versionadded:: 0.24.0 Parameters ---------- periods : int, default 1 The number of periods to shift. Negative values are allowed for shif...
Compute the ExtensionArray of unique values. Returns ------- uniques : ExtensionArray def unique(self): """ Compute the ExtensionArray of unique values. Returns ------- uniques : ExtensionArray """ from pandas import unique uniq...
Find indices where elements should be inserted to maintain order. .. versionadded:: 0.24.0 Find the indices into a sorted array `self` (a) such that, if the corresponding elements in `value` were inserted before the indices, the order of `self` would be preserved. Assuming tha...
Return an array and missing value suitable for factorization. Returns ------- values : ndarray An array suitable for factorization. This should maintain order and be a supported dtype (Float64, Int64, UInt64, String, Object). By default, the extension array ...
Encode the extension array as an enumerated type. Parameters ---------- na_sentinel : int, default -1 Value to use in the `labels` array to indicate missing values. Returns ------- labels : ndarray An integer NumPy array that's an indexer into th...
Take elements from an array. Parameters ---------- indices : sequence of integers Indices to be taken. allow_fill : bool, default False How to handle negative values in `indices`. * False: negative values in `indices` indicate positional indices ...
Formatting function for scalar values. This is used in the default '__repr__'. The returned formatting function receives instances of your scalar type. Parameters ---------- boxed: bool, default False An indicated for whether or not your array is being printed ...
Return a scalar result of performing the reduction operation. Parameters ---------- name : str Name of the function, supported values are: { any, all, min, max, sum, mean, median, prod, std, var, sem, kurt, skew }. skipna : bool, default True ...
A class method that returns a method that will correspond to an operator for an ExtensionArray subclass, by dispatching to the relevant operator defined on the individual elements of the ExtensionArray. Parameters ---------- op : function An operator that tak...
Make an alias for a method of the underlying ExtensionArray. Parameters ---------- array_method : method on an Array class Returns ------- method def ea_passthrough(array_method): """ Make an alias for a method of the underlying ExtensionArray. Parameters ---------- array...
Create a comparison method that dispatches to ``cls.values``. def _create_comparison_method(cls, op): """ Create a comparison method that dispatches to ``cls.values``. """ def wrapper(self, other): if isinstance(other, ABCSeries): # the arrays defer to Series...
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, ABCIndexClass): return False elif not ...
Create the join wrapper methods. def _join_i8_wrapper(joinf, dtype, with_indexers=True): """ Create the join wrapper methods. """ from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin @staticmethod def wrapper(left, right): if isinstance(left, (...
Return sorted copy of Index. def sort_values(self, return_indexer=False, ascending=True): """ Return sorted copy of Index. """ if return_indexer: _as = self.argsort() if not ascending: _as = _as[::-1] sorted_index = self.take(_as) ...
Return the minimum value of the Index or minimum along an axis. See Also -------- numpy.ndarray.min Series.min : Return the minimum value in a Series. def min(self, axis=None, skipna=True, *args, **kwargs): """ Return the minimum value of the Index or minimum al...
Returns the indices of the minimum values along an axis. See `numpy.ndarray.argmin` for more information on the `axis` parameter. See Also -------- numpy.ndarray.argmin def argmin(self, axis=None, skipna=True, *args, **kwargs): """ Returns the indices of the mi...
Return the maximum value of the Index or maximum along an axis. See Also -------- numpy.ndarray.max Series.max : Return the maximum value in a Series. def max(self, axis=None, skipna=True, *args, **kwargs): """ Return the maximum value of the Index or maximum al...
Returns the indices of the maximum values along an axis. See `numpy.ndarray.argmax` for more information on the `axis` parameter. See Also -------- numpy.ndarray.argmax def argmax(self, axis=None, skipna=True, *args, **kwargs): """ Returns the indices of the ma...
Return a list of tuples of the (attr,formatted_value). def _format_attrs(self): """ Return a list of tuples of the (attr,formatted_value). """ attrs = super()._format_attrs() for attrib in self._attributes: if attrib == 'freq': freq = self.freqstr ...
We don't allow integer or float indexing on datetime-like when using loc. Parameters ---------- key : label of the slice bound kind : {'ix', 'loc', 'getitem', 'iloc'} or None def _convert_scalar_indexer(self, key, kind=None): """ We don't allow integer or float ...
Add in the datetimelike methods (as we may have to override the superclass). def _add_datetimelike_methods(cls): """ Add in the datetimelike methods (as we may have to override the superclass). """ def __add__(self, other): # dispatch to ExtensionArray imple...
Compute boolean array of whether each index value is found in the passed set of values. Parameters ---------- values : set or sequence of values Returns ------- is_contained : ndarray (boolean dtype) def isin(self, values): """ Compute boolean a...
Return a summarized representation. Parameters ---------- name : str name to use in the summary representation Returns ------- String with a summarized representation of the index def _summary(self, name=None): """ Return a summarized repres...
Concatenate to_concat which has the same class. def _concat_same_dtype(self, to_concat, name): """ Concatenate to_concat which has the same class. """ attribs = self._get_attributes_dict() attribs['name'] = name # do not pass tz to set because tzlocal cannot be hashed ...
Shift index by desired number of time frequency increments. This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times. Parameters ---------- periods : int Number of periods (or increments) to shift by, ...
Replaces values in a Series using the fill method specified when no replacement value is given in the replace method def _single_replace(self, to_replace, method, inplace, limit): """ Replaces values in a Series using the fill method specified when no replacement value is given in the replace method ...
Return a tuple of the doc parms. def _doc_parms(cls): """Return a tuple of the doc parms.""" axis_descr = "{%s}" % ', '.join("{0} ({1})".format(a, i) for i, a in enumerate(cls._AXIS_ORDERS)) name = (cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else '...
passed a manager and a axes dict def _init_mgr(self, mgr, axes=None, dtype=None, copy=False): """ passed a manager and a axes dict """ for a, axe in axes.items(): if axe is not None: mgr = mgr.reindex_axis(axe, axis=self._get_block_mana...
validate the passed dtype def _validate_dtype(self, dtype): """ validate the passed dtype """ if dtype is not None: dtype = pandas_dtype(dtype) # a compound dtype if dtype.kind == 'V': raise NotImplementedError("compound dtypes are not implemented" ...
Provide axes setup for the major PandasObjects. Parameters ---------- axes : the names of the axes in order (lowest to highest) info_axis_num : the axis of the selector dimension (int) stat_axis_num : the number of axis for the default stats (int) aliases : other names f...
Return an axes dictionary for myself. def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d
Return an axes dictionary for the passed axes. def _construct_axes_dict_from(self, axes, **kwargs): """Return an axes dictionary for the passed axes.""" d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)} d.update(kwargs) return d
Return an axes dictionary for myself. def _construct_axes_dict_for_slice(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" d = {self._AXIS_SLICEMAP[a]: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d
Construct and returns axes if supplied in args/kwargs. If require_all, raise if all axis arguments are not supplied return a tuple of (axes, kwargs). sentinel specifies the default parameter when an axis is not supplied; useful to distinguish when a user explicitly passes None ...
Map the axis to the block_manager axis. def _get_block_manager_axis(cls, axis): """Map the axis to the block_manager axis.""" axis = cls._get_axis_number(axis) if cls._AXIS_REVERSED: m = cls._AXIS_LEN - 1 return m - axis return axis
Return the space character free column resolvers of a dataframe. Column names with spaces are 'cleaned up' so that they can be referred to by backtick quoting. Used in :meth:`DataFrame.eval`. def _get_space_character_free_column_resolvers(self): """Return the space character free colum...
Return a tuple of axis dimensions def shape(self): """ Return a tuple of axis dimensions """ return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)
Permute the dimensions of the %(klass)s Parameters ---------- args : %(args_transpose)s copy : boolean, default False Make a copy of the underlying data. Mixed-dtype data will always result in a copy **kwargs Additional keyword arguments will ...
Interchange axes and swap values axes appropriately. Returns ------- y : same as input def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately. Returns ------- y : same as input """ i = self._...
Return DataFrame with requested index / column level(s) removed. .. versionadded:: 0.24.0 Parameters ---------- level : int, str, or list-like If a string is given, must be the name of a level If list-like, elements must be names or positional indexes ...
Return item and drop from frame. Raise KeyError if not found. Parameters ---------- item : str Label of column to be popped. Returns ------- Series Examples -------- >>> df = pd.DataFrame([('falcon', 'bird', 389.0), ... ...
Squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged. This method is most useful when you don't know if your ...