INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Concatenate list of single blocks of the same type.
def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._concatenator([blk.values for blk in to_concat], axis=self.ndim - 1) return self.make_block_same_class( ...
Delete given loc(-s) from block in-place.
def delete(self, loc): """ Delete given loc(-s) from block in-place. """ self.values = np.delete(self.values, loc, 0) self.mgr_locs = self.mgr_locs.delete(loc)
apply the function to my values; return a block if we are not one
def apply(self, func, **kwargs): """ apply the function to my values; return a block if we are not one """ with np.errstate(all='ignore'): result = func(self.values, **kwargs) if not isinstance(result, Block): result = self.make_block(values=_block_shape(r...
fillna on the block with the value. If we fail, then convert to ObjectBlock and try again
def fillna(self, value, limit=None, inplace=False, downcast=None): """ fillna on the block with the value. If we fail, then convert to ObjectBlock and try again """ inplace = validate_bool_kwarg(inplace, 'inplace') if not self._can_hold_na: if inplace: ...
split the block per-column, and apply the callable f per-column, return a new block for each. Handle masking which will not change a block unless needed. Parameters ---------- mask : 2-d boolean mask f : callable accepting (1d-mask, 1d values, indexer) inplace : ...
def split_and_operate(self, mask, f, inplace): """ split the block per-column, and apply the callable f per-column, return a new block for each. Handle masking which will not change a block unless needed. Parameters ---------- mask : 2-d boolean mask f : ...
try to downcast each item to the dict of dtypes if present
def downcast(self, dtypes=None): """ try to downcast each item to the dict of dtypes if present """ # turn it off completely if dtypes is False: return self values = self.values # single block handling if self._is_single_block: # try to cast al...
Coerce to the new type Parameters ---------- dtype : str, dtype convertible copy : boolean, default False copy if indicated errors : str, {'raise', 'ignore'}, default 'ignore' - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress...
def _astype(self, dtype, copy=False, errors='raise', values=None, **kwargs): """Coerce to the new type Parameters ---------- dtype : str, dtype convertible copy : boolean, default False copy if indicated errors : str, {'raise', 'ignore'}, defa...
require the same dtype as ourselves
def _can_hold_element(self, element): """ require the same dtype as ourselves """ dtype = self.values.dtype.type tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, dtype) return isinstance(element, dtype)
try to cast the result to our original type, we may have roundtripped thru object in the mean-time
def _try_cast_result(self, result, dtype=None): """ try to cast the result to our original type, we may have roundtripped thru object in the mean-time """ if dtype is None: dtype = self.dtype if self.is_integer or self.is_bool or self.is_datetime: pass ...
provide coercion to our input arguments
def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if np.any(notna(other)) and not self._can_hold_element(other): # coercion issues # let higher levels handle raise TypeError("cannot convert {} to an {}".format( ...
convert to our native types format, slicing if desired
def to_native_types(self, slicer=None, na_rep='nan', quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.get_values() if slicer is not None: values = values[:, slicer] mask = isna(values) if ...
copy constructor
def copy(self, deep=True): """ copy constructor """ values = self.values if deep: values = values.copy() return self.make_block_same_class(values, ndim=self.ndim)
replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. It is used in ObjectBlocks. It is here for API compatibility.
def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True): """replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. It is used in ObjectBlocks. It is here for API comp...
Set the value inplace, returning a a maybe different typed block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Returns ------- Block Notes...
def setitem(self, indexer, value): """Set the value inplace, returning a a maybe different typed block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Return...
putmask the data to the block; it is possible that we may create a new dtype of block return the resulting block(s) Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True ...
def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; it is possible that we may create a new dtype of block return the resulting block(s) Parameters ---------- mask : the condition to respe...
coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block
def coerce_to_target_dtype(self, other): """ coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block """ # if we cannot then co...
fillna but using the interpolate machinery
def _interpolate_with_fill(self, method='pad', axis=0, inplace=False, limit=None, fill_value=None, coerce=False, downcast=None): """ fillna but using the interpolate machinery """ inplace = validate_bool_kwarg(inplace, 'inplace') # ...
interpolate using scipy wrappers
def _interpolate(self, method=None, index=None, values=None, fill_value=None, axis=0, limit=None, limit_direction='forward', limit_area=None, inplace=False, downcast=None, **kwargs): """ interpolate using scipy wrappers """ inplace = valida...
Take values according to indexer and return them as a block.bb
def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block.bb """ # algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock # so need to preserve types # sparse is treated like an ndarray,...
return block for the diff of the values
def diff(self, n, axis=1): """ return block for the diff of the values """ new_values = algos.diff(self.values, n, axis=axis) return [self.make_block(values=new_values)]
shift the block by periods, possibly upcast
def shift(self, periods, axis=0, fill_value=None): """ shift the block by periods, possibly upcast """ # convert integer to float if necessary. need to do a lot more than # that, handle boolean etc also new_values, fill_value = maybe_upcast(self.values, fill_value) # make sure ...
evaluate the block; return result block(s) from the result Parameters ---------- other : a ndarray/object cond : the condition to respect align : boolean, perform alignment on other/cond errors : str, {'raise', 'ignore'}, default 'raise' - ``raise`` : allow ...
def where(self, other, cond, align=True, errors='raise', try_cast=False, axis=0, transpose=False): """ evaluate the block; return result block(s) from the result Parameters ---------- other : a ndarray/object cond : the condition to respect align :...
Return a list of unstacked blocks of self Parameters ---------- unstacker_func : callable Partially applied unstacker. new_columns : Index All columns of the unstacked BlockManager. n_rows : int Only used in ExtensionBlock.unstack fill...
def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): """Return a list of unstacked blocks of self Parameters ---------- unstacker_func : callable Partially applied unstacker. new_columns : Index All columns of the unstacked BlockManager. ...
compute the quantiles of the Parameters ---------- qs: a scalar or list of the quantiles to be computed interpolation: type of interpolation, default 'linear' axis: axis to compute, default 0 Returns ------- Block
def quantile(self, qs, interpolation='linear', axis=0): """ compute the quantiles of the Parameters ---------- qs: a scalar or list of the quantiles to be computed interpolation: type of interpolation, default 'linear' axis: axis to compute, default 0 Re...
Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False ...
def _replace_coerce(self, to_replace, value, inplace=True, regex=False, convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scal...
putmask the data to the block; we must be a single block and not generate other blocks return the resulting block Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True ...
def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; we must be a single block and not generate other blocks return the resulting block Parameters ---------- mask : the condition to...
Get the placement, values, and mask for a Block unstack. This is shared between ObjectBlock and ExtensionBlock. They differ in that ObjectBlock passes the values, while ExtensionBlock passes the dummy ndarray of positions to be used by a take later. Parameters ---------...
def _get_unstack_items(self, unstacker, new_columns): """ Get the placement, values, and mask for a Block unstack. This is shared between ObjectBlock and ExtensionBlock. They differ in that ObjectBlock passes the values, while ExtensionBlock passes the dummy ndarray of positions...
Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns ------- ExtensionArray
def _maybe_coerce_values(self, values): """Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns...
Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change the dtype of the Block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object...
def setitem(self, indexer, value): """Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change the dtype of the Block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subse...
Take values according to indexer and return them as a block.
def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block. """ if fill_tuple is None: fill_value = None else: fill_value = fill_tuple[0] # axis doesn't matter; we are re...
return a slice of my values
def _slice(self, slicer): """ return a slice of my values """ # slice the category # return same dims as we currently have if isinstance(slicer, tuple) and len(slicer) == 2: if not com.is_null_slice(slicer[0]): raise AssertionError("invalid slicing for a 1-n...
Concatenate list of single blocks of the same type.
def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._holder._concat_same_type( [blk.values for blk in to_concat]) placement = placement or slice(0, len(values), 1) return self.make_bl...
Shift the block by `periods`. Dispatches to underlying ExtensionArray and re-boxes in an ExtensionBlock.
def shift(self, periods: int, axis: libinternals.BlockPlacement = 0, fill_value: Any = None) -> List['ExtensionBlock']: """ Shift the block by `periods`. Dispatches to underlying ExtensionArray and re-boxes in an ExtensionBlock. """ ...
convert to our native types format, slicing if desired
def to_native_types(self, slicer=None, na_rep='', float_format=None, decimal='.', quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: values = values[:, slicer] # see gh-...
return object dtype as boxed values, such as Timestamps/Timedelta
def get_values(self, dtype=None): """ return object dtype as boxed values, such as Timestamps/Timedelta """ if is_object_dtype(dtype): values = self.values.ravel() result = self._holder(values).astype(object) return result.reshape(self.values.shape) ...
Input validation for values passed to __init__. Ensure that we have datetime64ns, coercing if necessary. Parameters ---------- values : array-like Must be convertible to datetime64 Returns ------- values : ndarray[datetime64ns] Overridden by...
def _maybe_coerce_values(self, values): """Input validation for values passed to __init__. Ensure that we have datetime64ns, coercing if necessary. Parameters ---------- values : array-like Must be convertible to datetime64 Returns ------- va...
these automatically copy, so copy=True has no effect raise on an except if raise == True
def _astype(self, dtype, **kwargs): """ these automatically copy, so copy=True has no effect raise on an except if raise == True """ dtype = pandas_dtype(dtype) # if we are passed a datetime64[ns, tz] if is_datetime64tz_dtype(dtype): values = self.val...
Coerce values and other to dtype 'i8'. NaN and NaT convert to the smallest i8, and will correctly round-trip to NaT if converted back in _try_coerce_result. values is always ndarray-like, other may not be Parameters ---------- values : ndarray-like other : ndarra...
def _try_coerce_args(self, values, other): """ Coerce values and other to dtype 'i8'. NaN and NaT convert to the smallest i8, and will correctly round-trip to NaT if converted back in _try_coerce_result. values is always ndarray-like, other may not be Parameters ...
reverse of try_coerce_args
def _try_coerce_result(self, result): """ reverse of try_coerce_args """ if isinstance(result, np.ndarray): if result.dtype.kind in ['i', 'f']: result = result.astype('M8[ns]') elif isinstance(result, (np.integer, np.float, np.datetime64)): result = self....
convert to our native types format, slicing if desired
def to_native_types(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values i8values = self.values.view('i8') if slicer is not None: values = value...
Modify Block in-place with new item value Returns ------- None
def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ values = conversion.ensure_datetime64ns(values, copy=False) self.values[locs] = values
Input validation for values passed to __init__. Ensure that we have datetime64TZ, coercing if necessary. Parametetrs ----------- values : array-like Must be convertible to datetime64 Returns ------- values : DatetimeArray
def _maybe_coerce_values(self, values): """Input validation for values passed to __init__. Ensure that we have datetime64TZ, coercing if necessary. Parametetrs ----------- values : array-like Must be convertible to datetime64 Returns ------- ...
Returns an ndarray of values. Parameters ---------- dtype : np.dtype Only `object`-like dtypes are respected here (not sure why). Returns ------- values : ndarray When ``dtype=object``, then and object-dtype ndarray of box...
def get_values(self, dtype=None): """ Returns an ndarray of values. Parameters ---------- dtype : np.dtype Only `object`-like dtypes are respected here (not sure why). Returns ------- values : ndarray When ``dtype=obje...
return a slice of my values
def _slice(self, slicer): """ return a slice of my values """ if isinstance(slicer, tuple): col, loc = slicer if not com.is_null_slice(col) and col != 0: raise IndexError("{0} only contains one item".format(self)) return self.values[loc] return...
localize and return i8 for the values Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other
def _try_coerce_args(self, values, other): """ localize and return i8 for the values Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other """ # asi8 is a view...
reverse of try_coerce_args
def _try_coerce_result(self, result): """ reverse of try_coerce_args """ if isinstance(result, np.ndarray): if result.dtype.kind in ['i', 'f']: result = result.astype('M8[ns]') elif isinstance(result, (np.integer, np.float, np.datetime64)): result = self....
1st discrete difference Parameters ---------- n : int, number of periods to diff axis : int, axis to diff upon. default 0 Return ------ A list with a new TimeDeltaBlock. Note ---- The arguments here are mimicking shift so they are called...
def diff(self, n, axis=0): """1st discrete difference Parameters ---------- n : int, number of periods to diff axis : int, axis to diff upon. default 0 Return ------ A list with a new TimeDeltaBlock. Note ---- The arguments here ...
Coerce values and other to int64, with null values converted to iNaT. values is always ndarray-like, other may not be Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other
def _try_coerce_args(self, values, other): """ Coerce values and other to int64, with null values converted to iNaT. values is always ndarray-like, other may not be Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ...
reverse of try_coerce_args / try_operate
def _try_coerce_result(self, result): """ reverse of try_coerce_args / try_operate """ if isinstance(result, np.ndarray): mask = isna(result) if result.dtype.kind in ['i', 'f']: result = result.astype('m8[ns]') result[mask] = tslibs.iNaT elif ...
convert to our native types format, slicing if desired
def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: values = values[:, slicer] mask = isna(values) rvalues = n...
attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we ARE an ObjectBlock!!!!! can return multiple blocks!
def convert(self, *args, **kwargs): """ attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we ARE an ObjectBlock!!!!! can return multiple blocks! """ if args: raise NotImplementedError by_item = kwarg...
Modify Block in-place with new item value Returns ------- None
def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ try: self.values[locs] = values except (ValueError): # broadcasting error # see GH6171 new_shape = list(va...
provide coercion to our input arguments
def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if isinstance(other, ABCDatetimeIndex): # May get a DatetimeIndex here. Unbox it. other = other.array if isinstance(other, DatetimeArray): # hit in pandas/tests/indexi...
Replace elements by the given value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. ...
def _replace_single(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True, mask=None): """ Replace elements by the given value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expressi...
Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False ...
def _replace_coerce(self, to_replace, value, inplace=True, regex=False, convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scal...
reverse of try_coerce_args
def _try_coerce_result(self, result): """ reverse of try_coerce_args """ # GH12564: CategoricalBlock is 1-dim only # while returned results could be any dim if ((not is_categorical_dtype(result)) and isinstance(result, np.ndarray)): result = _block_shape(resu...
convert to our native types format, slicing if desired
def to_native_types(self, slicer=None, na_rep='', quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: # Categorical is always one dimension values = values[slicer] mask = isna(values)...
helper which recursively generate an xlwt easy style string for example: hstyle = {"font": {"bold": True}, "border": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"}, "align": {"horiz": "center"}} ...
def _style_to_xlwt(cls, item, firstlevel=True, field_sep=',', line_sep=';'): """helper which recursively generate an xlwt easy style string for example: hstyle = {"font": {"bold": True}, "border": {"top": "thin", "right": "thin", ...
converts a style_dict to an xlwt style object Parameters ---------- style_dict : style dictionary to convert num_format_str : optional number format string
def _convert_to_style(cls, style_dict, num_format_str=None): """ converts a style_dict to an xlwt style object Parameters ---------- style_dict : style dictionary to convert num_format_str : optional number format string """ import xlwt if style_d...
converts a style_dict to an xlsxwriter format dict Parameters ---------- style_dict : style dictionary to convert num_format_str : optional number format string
def convert(cls, style_dict, num_format_str=None): """ converts a style_dict to an xlsxwriter format dict Parameters ---------- style_dict : style dictionary to convert num_format_str : optional number format string """ # Create a XlsxWriter format objec...
Unstack an ExtensionArray-backed Series. The ExtensionDtype is preserved. Parameters ---------- series : Series A Series with an ExtensionArray for values level : Any The level name or number. fill_value : Any The user-level (not physical storage) fill value to use for ...
def _unstack_extension_series(series, level, fill_value): """ Unstack an ExtensionArray-backed Series. The ExtensionDtype is preserved. Parameters ---------- series : Series A Series with an ExtensionArray for values level : Any The level name or number. fill_value : An...
Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series
def stack(frame, level=-1, dropna=True): """ Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series """ def factorize(index): if index.is_unique: return index, np.arange...
Convert categorical variable into dummy/indicator variables. Parameters ---------- data : array-like, Series, or DataFrame Data of which to get dummy indicators. prefix : str, list of str, or dict of str, default None String to append DataFrame column names. Pass a list with len...
def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None): """ Convert categorical variable into dummy/indicator variables. Parameters ---------- data : array-like, Series, or DataFrame Data of which to get d...
Construct 1-0 dummy variables corresponding to designated axis labels Parameters ---------- frame : DataFrame axis : {'major', 'minor'}, default 'minor' transform : function, default None Function to apply to axis labels first. For example, to get "day of week" dummies in a time...
def make_axis_dummies(frame, axis='minor', transform=None): """ Construct 1-0 dummy variables corresponding to designated axis labels Parameters ---------- frame : DataFrame axis : {'major', 'minor'}, default 'minor' transform : function, default None Function to apply to axis l...
Re-orders the values when stacking multiple extension-arrays. The indirect stacking method used for EAs requires a followup take to get the order correct. Parameters ---------- arr : ExtensionArray n_rows, n_columns : int The number of rows and columns in the original DataFrame. R...
def _reorder_for_extension_array_stack(arr, n_rows, n_columns): """ Re-orders the values when stacking multiple extension-arrays. The indirect stacking method used for EAs requires a followup take to get the order correct. Parameters ---------- arr : ExtensionArray n_rows, n_columns : ...
Parameters ---------- s: string Fixed-length string to split parts: list of (name, length) pairs Used to break up string, name '_' will be filtered from output. Returns ------- Dict of name:contents of string at given location.
def _split_line(s, parts): """ Parameters ---------- s: string Fixed-length string to split parts: list of (name, length) pairs Used to break up string, name '_' will be filtered from output. Returns ------- Dict of name:contents of string at given location. """ ...
Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats.
def _parse_float_vec(vec): """ Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats. """ dtype = np.dtype('>u4,>u4') vec1 = vec.view(dtype=dtype) xport1 = vec1['f0'] xport2 = vec1['f1'] # Start by setting first half of ieee number to first half of...
Get number of records in file. This is maybe suboptimal because we have to seek to the end of the file. Side effect: returns file position to record_start.
def _record_count(self): """ Get number of records in file. This is maybe suboptimal because we have to seek to the end of the file. Side effect: returns file position to record_start. """ self.filepath_or_buffer.seek(0, 2) total_records_length = (self....
Reads lines from Xport file and returns as dataframe Parameters ---------- size : int, defaults to None Number of lines to read. If None, reads whole file. Returns ------- DataFrame
def get_chunk(self, size=None): """ Reads lines from Xport file and returns as dataframe Parameters ---------- size : int, defaults to None Number of lines to read. If None, reads whole file. Returns ------- DataFrame """ if ...
raise a helpful message about our construction
def construction_error(tot_items, block_shape, axes, e=None): """ raise a helpful message about our construction """ passed = tuple(map(int, [tot_items] + list(block_shape))) # Correcting the user facing error message during dataframe construction if len(passed) <= 2: passed = passed[::-1] ...
return a single array of a block that has a single dtype; if dtype is not None, coerce to this dtype
def _simple_blockify(tuples, dtype): """ return a single array of a block that has a single dtype; if dtype is not None, coerce to this dtype """ values, placement = _stack_arrays(tuples, dtype) # CHECK DTYPE? if dtype is not None and values.dtype != dtype: # pragma: no cover values = ...
return an array of blocks that potentially have different dtypes
def _multi_blockify(tuples, dtype=None): """ return an array of blocks that potentially have different dtypes """ # group by dtype grouper = itertools.groupby(tuples, lambda x: x[2].dtype) new_blocks = [] for dtype, tup_block in grouper: values, placement = _stack_arrays(list(tup_block), ...
return an array of blocks that potentially have different dtypes (and are sparse)
def _sparse_blockify(tuples, dtype=None): """ return an array of blocks that potentially have different dtypes (and are sparse) """ new_blocks = [] for i, names, array in tuples: array = _maybe_to_sparse(array) block = make_block(array, placement=[i]) new_blocks.append(block...
Find the common dtype for `blocks`. Parameters ---------- blocks : List[Block] Returns ------- dtype : Optional[Union[np.dtype, ExtensionDtype]] None is returned when `blocks` is empty.
def _interleaved_dtype( blocks: List[Block] ) -> Optional[Union[np.dtype, ExtensionDtype]]: """Find the common dtype for `blocks`. Parameters ---------- blocks : List[Block] Returns ------- dtype : Optional[Union[np.dtype, ExtensionDtype]] None is returned when `blocks` is ...
Merge blocks having same dtype, exclude non-consolidating blocks
def _consolidate(blocks): """ Merge blocks having same dtype, exclude non-consolidating blocks """ # sort by _can_consolidate, dtype gkey = lambda x: x._consolidate_key grouper = itertools.groupby(sorted(blocks, key=gkey), gkey) new_blocks = [] for (_can_consolidate, dtype), group_bloc...
Compare two array_like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array_like or scalar b : array_like or scalar regex : bool, default False ...
def _compare_or_regex_search(a, b, regex=False): """ Compare two array_like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array_like or scalar ...
If two indices overlap, add suffixes to overlapping entries. If corresponding suffix is empty, the entry is simply converted to string.
def items_overlap_with_suffix(left, lsuffix, right, rsuffix): """ If two indices overlap, add suffixes to overlapping entries. If corresponding suffix is empty, the entry is simply converted to string. """ to_rename = left.intersection(right) if len(to_rename) == 0: return left, right ...
Apply function to all values found in index. This includes transforming multiindex entries separately. Only apply function to one level of the MultiIndex if level is specified.
def _transform_index(index, func, level=None): """ Apply function to all values found in index. This includes transforming multiindex entries separately. Only apply function to one level of the MultiIndex if level is specified. """ if isinstance(index, MultiIndex): if level is not None...
Faster version of set(arr) for sequences of small numbers.
def _fast_count_smallints(arr): """Faster version of set(arr) for sequences of small numbers.""" counts = np.bincount(arr.astype(np.int_)) nz = counts.nonzero()[0] return np.c_[nz, counts[nz]]
Concatenate block managers into one. Parameters ---------- mgrs_indexers : list of (BlockManager, {axis: indexer,...}) tuples axes : list of Index concat_axis : int copy : bool
def concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy): """ Concatenate block managers into one. Parameters ---------- mgrs_indexers : list of (BlockManager, {axis: indexer,...}) tuples axes : list of Index concat_axis : int copy : bool """ concat_plans = [get_m...
return an empty BlockManager with the items axis of len 0
def make_empty(self, axes=None): """ return an empty BlockManager with the items axis of len 0 """ if axes is None: axes = [ensure_index([])] + [ensure_index(a) for a in self.axes[1:]] # preserve dtype if possible if self.ndim == 1: ...
Rename one of axes. Parameters ---------- mapper : unary callable axis : int copy : boolean, default True level : int, default None
def rename_axis(self, mapper, axis, copy=True, level=None): """ Rename one of axes. Parameters ---------- mapper : unary callable axis : int copy : boolean, default True level : int, default None """ obj = self.copy(deep=copy) obj....
Update mgr._blknos / mgr._blklocs.
def _rebuild_blknos_and_blklocs(self): """ Update mgr._blknos / mgr._blklocs. """ new_blknos = np.empty(self.shape[0], dtype=np.int64) new_blklocs = np.empty(self.shape[0], dtype=np.int64) new_blknos.fill(-1) new_blklocs.fill(-1) for blkno, blk in enumera...
return a dict of the counts of the function in BlockManager
def _get_counts(self, f): """ return a dict of the counts of the function in BlockManager """ self._consolidate_inplace() counts = dict() for b in self.blocks: v = f(b) counts[v] = counts.get(v, 0) + b.shape[0] return counts
iterate over the blocks, collect and create a new block manager Parameters ---------- f : the callable or function name to operate on at the block level axes : optional (if not supplied, use self.axes) filter : list, if supplied, only call the block if the filter is in ...
def apply(self, f, axes=None, filter=None, do_integrity_check=False, consolidate=True, **kwargs): """ iterate over the blocks, collect and create a new block manager Parameters ---------- f : the callable or function name to operate on at the block level ax...
Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and will do inference on the generated blocks. Parameters ---------- axis: reduction axis, default 0 consolidate: boolean, default True. Join together blocks having sa...
def quantile(self, axis=0, consolidate=True, transposed=False, interpolation='linear', qs=None, numeric_only=None): """ Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and will do inference on the generated blocks. ...
do a list replace
def replace_list(self, src_list, dest_list, inplace=False, regex=False): """ do a list replace """ inplace = validate_bool_kwarg(inplace, 'inplace') # figure out our mask a-priori to avoid repeated replacements values = self.as_array() def comp(s, regex=False): """...
Parameters ---------- copy : boolean, default False Whether to copy the blocks
def get_bool_data(self, copy=False): """ Parameters ---------- copy : boolean, default False Whether to copy the blocks """ self._consolidate_inplace() return self.combine([b for b in self.blocks if b.is_bool], copy)
Parameters ---------- copy : boolean, default False Whether to copy the blocks
def get_numeric_data(self, copy=False): """ Parameters ---------- copy : boolean, default False Whether to copy the blocks """ self._consolidate_inplace() return self.combine([b for b in self.blocks if b.is_numeric], copy)
return a new manager with the blocks
def combine(self, blocks, copy=True): """ return a new manager with the blocks """ if len(blocks) == 0: return self.make_empty() # FIXME: optimization potential indexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks]))...
Make deep or shallow copy of BlockManager Parameters ---------- deep : boolean o rstring, default True If False, return shallow copy (do not copy data) If 'all', copy data and a deep copy of the index Returns ------- copy : BlockManager
def copy(self, deep=True): """ Make deep or shallow copy of BlockManager Parameters ---------- deep : boolean o rstring, default True If False, return shallow copy (do not copy data) If 'all', copy data and a deep copy of the index Returns ...
Convert the blockmanager data into an numpy array. Parameters ---------- transpose : boolean, default False If True, transpose the return array items : list of strings or None Names of block items that will be included in the returned array. ``None`` ...
def as_array(self, transpose=False, items=None): """Convert the blockmanager data into an numpy array. Parameters ---------- transpose : boolean, default False If True, transpose the return array items : list of strings or None Names of block items that w...
Return ndarray from blocks with specified item order Items must be contained in the blocks
def _interleave(self): """ Return ndarray from blocks with specified item order Items must be contained in the blocks """ from pandas.core.dtypes.common import is_sparse dtype = _interleaved_dtype(self.blocks) # TODO: https://github.com/pandas-dev/pandas/issues/2...
Return a dict of str(dtype) -> BlockManager Parameters ---------- copy : boolean, default True Returns ------- values : a dict of dtype -> BlockManager Notes ----- This consolidates based on str(dtype)
def to_dict(self, copy=True): """ Return a dict of str(dtype) -> BlockManager Parameters ---------- copy : boolean, default True Returns ------- values : a dict of dtype -> BlockManager Notes ----- This consolidates based on str(...
get a cross sectional for a given location in the items ; handle dups return the result, is *could* be a view in the case of a single block
def fast_xs(self, loc): """ get a cross sectional for a given location in the items ; handle dups return the result, is *could* be a view in the case of a single block """ if len(self.blocks) == 1: return self.blocks[0].iget((slice(None), loc)) ...
Join together blocks having same dtype Returns ------- y : BlockManager
def consolidate(self): """ Join together blocks having same dtype Returns ------- y : BlockManager """ if self.is_consolidated(): return self bm = self.__class__(self.blocks, self.axes) bm._is_consolidated = False bm._consolid...
Return values for selected item (ndarray or BlockManager).
def get(self, item, fastpath=True): """ Return values for selected item (ndarray or BlockManager). """ if self.items.is_unique: if not isna(item): loc = self.items.get_loc(item) else: indexer = np.arange(len(self.items))[isna(self....
Return the data as a SingleBlockManager if fastpath=True and possible Otherwise return as a ndarray
def iget(self, i, fastpath=True): """ Return the data as a SingleBlockManager if fastpath=True and possible Otherwise return as a ndarray """ block = self.blocks[self._blknos[i]] values = block.iget(self._blklocs[i]) if not fastpath or not block._box_to_block_val...
Delete selected item (items if non-unique) in-place.
def delete(self, item): """ Delete selected item (items if non-unique) in-place. """ indexer = self.items.get_loc(item) is_deleted = np.zeros(self.shape[0], dtype=np.bool_) is_deleted[indexer] = True ref_loc_offset = -is_deleted.cumsum() is_blk_deleted =...
Set new item in-place. Does not consolidate. Adds new Block if not contained in the current set of items
def set(self, item, value): """ Set new item in-place. Does not consolidate. Adds new Block if not contained in the current set of items """ # FIXME: refactor, clearly separate broadcasting & zip-like assignment # can prob also fix the various if tests for sparse/c...