Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def apply(self, func, **kwargs):
with np.errstate(all='ignore'):
result = func(self.values, **kwargs)
if not isinstance(result, Block):
result = self.make_block(values=_block_shape(result,
... | [
" apply the function to my values; return a block if we are not\n one\n "
] |
Please provide a description of the function:def fillna(self, value, limit=None, inplace=False, downcast=None):
inplace = validate_bool_kwarg(inplace, 'inplace')
if not self._can_hold_na:
if inplace:
return self
else:
return self.copy()
... | [
" fillna on the block with the value. If we fail, then convert to\n ObjectBlock and try again\n "
] |
Please provide a description of the function:def split_and_operate(self, mask, f, inplace):
if mask is None:
mask = np.ones(self.shape, dtype=bool)
new_values = self.values
def make_a_block(nv, ref_loc):
if isinstance(nv, Block):
block = nv
... | [
"\n split the block per-column, and apply the callable f\n per-column, return a new block for each. Handle\n masking which will not change a block unless needed.\n\n Parameters\n ----------\n mask : 2-d boolean mask\n f : callable accepting (1d-mask, 1d values, index... |
Please provide a description of the function:def downcast(self, dtypes=None):
# turn it off completely
if dtypes is False:
return self
values = self.values
# single block handling
if self._is_single_block:
# try to cast all non-floats here
... | [
" try to downcast each item to the dict of dtypes if present "
] |
Please provide a description of the function:def _astype(self, dtype, copy=False, errors='raise', values=None,
**kwargs):
errors_legal_values = ('raise', 'ignore')
if errors not in errors_legal_values:
invalid_arg = ("Expected value of kwarg 'errors' to be one of {}... | [
"Coerce to the new type\n\n Parameters\n ----------\n dtype : str, dtype convertible\n copy : boolean, default False\n copy if indicated\n errors : str, {'raise', 'ignore'}, default 'ignore'\n - ``raise`` : allow exceptions to be raised\n - ``ignor... |
Please provide a description of the function:def _can_hold_element(self, element):
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) | [
" require the same dtype as ourselves "
] |
Please provide a description of the function:def _try_cast_result(self, result, dtype=None):
if dtype is None:
dtype = self.dtype
if self.is_integer or self.is_bool or self.is_datetime:
pass
elif self.is_float and result.dtype == self.dtype:
# prote... | [
" try to cast the result to our original type, we may have\n roundtripped thru object in the mean-time\n "
] |
Please provide a description of the function:def _try_coerce_args(self, values, other):
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(
t... | [
" provide coercion to our input arguments "
] |
Please provide a description of the function:def to_native_types(self, slicer=None, na_rep='nan', quoting=None,
**kwargs):
values = self.get_values()
if slicer is not None:
values = values[:, slicer]
mask = isna(values)
if not self.is_objec... | [
" convert to our native types format, slicing if desired "
] |
Please provide a description of the function:def copy(self, deep=True):
values = self.values
if deep:
values = values.copy()
return self.make_block_same_class(values, ndim=self.ndim) | [
" copy constructor "
] |
Please provide a description of the function:def replace(self, to_replace, value, inplace=False, filter=None,
regex=False, convert=True):
inplace = validate_bool_kwarg(inplace, 'inplace')
original_to_replace = to_replace
# try to replace, if we raise an error, convert ... | [
"replace the to_replace value with value, possible to create new\n blocks here this is just a call to putmask. regex is not used here.\n It is used in ObjectBlocks. It is here for API compatibility.\n "
] |
Please provide a description of the function:def setitem(self, indexer, value):
# coerce None values, if appropriate
if value is None:
if self.is_numeric:
value = np.nan
# coerce if block dtype can store value
values = self.values
try:
... | [
"Set the value inplace, returning a a maybe different typed block.\n\n Parameters\n ----------\n indexer : tuple, list-like, array-like, slice\n The subset of self.values to set\n value : object\n The value being set\n\n Returns\n -------\n Bloc... |
Please provide a description of the function:def putmask(self, mask, new, align=True, inplace=False, axis=0,
transpose=False):
new_values = self.values if inplace else self.values.copy()
new = getattr(new, 'values', new)
mask = getattr(mask, 'values', mask)
# ... | [
" putmask the data to the block; it is possible that we may create a\n new dtype of block\n\n return the resulting block(s)\n\n Parameters\n ----------\n mask : the condition to respect\n new : a ndarray/object\n align : boolean, perform alignment on other/cond, def... |
Please provide a description of the function:def coerce_to_target_dtype(self, other):
# if we cannot then coerce to object
dtype, _ = infer_dtype_from(other, pandas_dtype=True)
if is_dtype_equal(self.dtype, dtype):
return self
if self.is_bool or is_object_dtype(dt... | [
"\n coerce the current block to a dtype compat for other\n we will return a block, possibly object, and not raise\n\n we can also safely try to coerce to the same dtype\n and will receive the same block\n "
] |
Please provide a description of the function:def _interpolate_with_fill(self, method='pad', axis=0, inplace=False,
limit=None, fill_value=None, coerce=False,
downcast=None):
inplace = validate_bool_kwarg(inplace, 'inplace')
# if we... | [
" fillna but using the interpolate machinery "
] |
Please provide a description of the function: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):
inplace = v... | [
" interpolate using scipy wrappers "
] |
Please provide a description of the function:def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None):
# algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock
# so need to preserve types
# sparse is treated like an ndarray, but needs .get_values() shaping
... | [
"\n Take values according to indexer and return them as a block.bb\n\n "
] |
Please provide a description of the function:def diff(self, n, axis=1):
new_values = algos.diff(self.values, n, axis=axis)
return [self.make_block(values=new_values)] | [
" return block for the diff of the values "
] |
Please provide a description of the function:def shift(self, periods, axis=0, fill_value=None):
# 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 array ... | [
" shift the block by periods, possibly upcast "
] |
Please provide a description of the function:def where(self, other, cond, align=True, errors='raise',
try_cast=False, axis=0, transpose=False):
import pandas.core.computation.expressions as expressions
assert errors in ['raise', 'ignore']
values = self.values
orig... | [
"\n evaluate the block; return result block(s) from the result\n\n Parameters\n ----------\n other : a ndarray/object\n cond : the condition to respect\n align : boolean, perform alignment on other/cond\n errors : str, {'raise', 'ignore'}, default 'raise'\n ... |
Please provide a description of the function:def _unstack(self, unstacker_func, new_columns, n_rows, fill_value):
unstacker = unstacker_func(self.values.T)
new_items = unstacker.get_new_columns()
new_placement = new_columns.get_indexer(new_items)
new_values, mask = unstacker.get... | [
"Return a list of unstacked blocks of self\n\n Parameters\n ----------\n unstacker_func : callable\n Partially applied unstacker.\n new_columns : Index\n All columns of the unstacked BlockManager.\n n_rows : int\n Only used in ExtensionBlock.unstac... |
Please provide a description of the function:def quantile(self, qs, interpolation='linear', axis=0):
if self.is_datetimetz:
# TODO: cleanup this special case.
# We need to operate on i8 values for datetimetz
# but `Block.get_values()` returns an ndarray of objects
... | [
"\n compute the quantiles of the\n\n Parameters\n ----------\n qs: a scalar or list of the quantiles to be computed\n interpolation: type of interpolation, default 'linear'\n axis: axis to compute, default 0\n\n Returns\n -------\n Block\n "
] |
Please provide a description of the function:def _replace_coerce(self, to_replace, value, inplace=True, regex=False,
convert=False, mask=None):
if mask.any():
if not regex:
self = self.coerce_to_target_dtype(value)
return self.putmask... | [
"\n Replace value corresponding to the given boolean array with another\n value.\n\n Parameters\n ----------\n to_replace : object or pattern\n Scalar to replace or regular expression to match.\n value : object\n Replacement object.\n inplace : ... |
Please provide a description of the function:def putmask(self, mask, new, align=True, inplace=False, axis=0,
transpose=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
# use block's copy logic.
# .values may be an Index which does shallow copy by default
... | [
"\n putmask the data to the block; we must be a single block and not\n generate other blocks\n\n return the resulting block\n\n Parameters\n ----------\n mask : the condition to respect\n new : a ndarray/object\n align : boolean, perform alignment on other/co... |
Please provide a description of the function:def _get_unstack_items(self, unstacker, new_columns):
# shared with ExtensionBlock
new_items = unstacker.get_new_columns()
new_placement = new_columns.get_indexer(new_items)
new_values, mask = unstacker.get_new_values()
mask ... | [
"\n Get the placement, values, and mask for a Block unstack.\n\n This is shared between ObjectBlock and ExtensionBlock. They\n differ in that ObjectBlock passes the values, while ExtensionBlock\n passes the dummy ndarray of positions to be used by a take\n later.\n\n Parame... |
Please provide a description of the function:def _maybe_coerce_values(self, values):
if isinstance(values, (ABCIndexClass, ABCSeries)):
values = values._values
return values | [
"Unbox to an extension array.\n\n This will unbox an ExtensionArray stored in an Index or Series.\n ExtensionArrays pass through. No dtype coercion is done.\n\n Parameters\n ----------\n values : Index, Series, ExtensionArray\n\n Returns\n -------\n ExtensionA... |
Please provide a description of the function:def setitem(self, indexer, value):
if isinstance(indexer, tuple):
# we are always 1-D
indexer = indexer[0]
check_setitem_lengths(indexer, value, self.values)
self.values[indexer] = value
return self | [
"Set the value inplace, returning a same-typed block.\n\n This differs from Block.setitem by not allowing setitem to change\n the dtype of the Block.\n\n Parameters\n ----------\n indexer : tuple, list-like, array-like, slice\n The subset of self.values to set\n ... |
Please provide a description of the function:def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None):
if fill_tuple is None:
fill_value = None
else:
fill_value = fill_tuple[0]
# axis doesn't matter; we are really a single-dim object
# but ... | [
"\n Take values according to indexer and return them as a block.\n "
] |
Please provide a description of the function:def _slice(self, slicer):
# 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... | [
" return a slice of my values "
] |
Please provide a description of the function:def concat_same_type(self, to_concat, placement=None):
values = self._holder._concat_same_type(
[blk.values for blk in to_concat])
placement = placement or slice(0, len(values), 1)
return self.make_block_same_class(values, ndim=se... | [
"\n Concatenate list of single blocks of the same type.\n "
] |
Please provide a description of the function:def shift(self,
periods: int,
axis: libinternals.BlockPlacement = 0,
fill_value: Any = None) -> List['ExtensionBlock']:
return [
self.make_block_same_class(
self.values.shift(periods=perio... | [
"\n Shift the block by `periods`.\n\n Dispatches to underlying ExtensionArray and re-boxes in an\n ExtensionBlock.\n "
] |
Please provide a description of the function:def to_native_types(self, slicer=None, na_rep='', float_format=None,
decimal='.', quoting=None, **kwargs):
values = self.values
if slicer is not None:
values = values[:, slicer]
# see gh-13418: no special... | [
" convert to our native types format, slicing if desired "
] |
Please provide a description of the function:def get_values(self, dtype=None):
if is_object_dtype(dtype):
values = self.values.ravel()
result = self._holder(values).astype(object)
return result.reshape(self.values.shape)
return self.values | [
"\n return object dtype as boxed values, such as Timestamps/Timedelta\n "
] |
Please provide a description of the function:def _maybe_coerce_values(self, values):
if values.dtype != _NS_DTYPE:
values = conversion.ensure_datetime64ns(values)
if isinstance(values, DatetimeArray):
values = values._data
assert isinstance(values, np.ndarray),... | [
"Input validation for values passed to __init__. Ensure that\n we have datetime64ns, coercing if necessary.\n\n Parameters\n ----------\n values : array-like\n Must be convertible to datetime64\n\n Returns\n -------\n values : ndarray[datetime64ns]\n\n ... |
Please provide a description of the function:def _astype(self, dtype, **kwargs):
dtype = pandas_dtype(dtype)
# if we are passed a datetime64[ns, tz]
if is_datetime64tz_dtype(dtype):
values = self.values
if getattr(values, 'tz', None) is None:
val... | [
"\n these automatically copy, so copy=True has no effect\n raise on an except if raise == True\n "
] |
Please provide a description of the function:def _try_coerce_args(self, values, other):
values = values.view('i8')
if isinstance(other, bool):
raise TypeError
elif is_null_datetimelike(other):
other = tslibs.iNaT
elif isinstance(other, (datetime, np.dat... | [
"\n Coerce values and other to dtype 'i8'. NaN and NaT convert to\n the smallest i8, and will correctly round-trip to NaT if converted\n back in _try_coerce_result. values is always ndarray-like, other\n may not be\n\n Parameters\n ----------\n values : ndarray-like\... |
Please provide a description of the function:def _try_coerce_result(self, result):
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)):
res... | [
" reverse of try_coerce_args "
] |
Please provide a description of the function:def to_native_types(self, slicer=None, na_rep=None, date_format=None,
quoting=None, **kwargs):
values = self.values
i8values = self.values.view('i8')
if slicer is not None:
values = values[..., slicer]
... | [
" convert to our native types format, slicing if desired "
] |
Please provide a description of the function:def set(self, locs, values):
values = conversion.ensure_datetime64ns(values, copy=False)
self.values[locs] = values | [
"\n Modify Block in-place with new item value\n\n Returns\n -------\n None\n "
] |
Please provide a description of the function:def _maybe_coerce_values(self, values):
if not isinstance(values, self._holder):
values = self._holder(values)
if values.tz is None:
raise ValueError("cannot create a DatetimeTZBlock without a tz")
return values | [
"Input validation for values passed to __init__. Ensure that\n we have datetime64TZ, coercing if necessary.\n\n Parametetrs\n -----------\n values : array-like\n Must be convertible to datetime64\n\n Returns\n -------\n values : DatetimeArray\n "
] |
Please provide a description of the function:def get_values(self, dtype=None):
values = self.values
if is_object_dtype(dtype):
values = values._box_values(values._data)
values = np.asarray(values)
if self.ndim == 2:
# Ensure that our shape is correct fo... | [
"\n Returns an ndarray of values.\n\n Parameters\n ----------\n dtype : np.dtype\n Only `object`-like dtypes are respected here (not sure\n why).\n\n Returns\n -------\n values : ndarray\n When ``dtype=object``, then and object-dtype ... |
Please provide a description of the function:def _slice(self, slicer):
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 a slice of my values "
] |
Please provide a description of the function:def _try_coerce_args(self, values, other):
# asi8 is a view, needs copy
values = _block_shape(values.view("i8"), ndim=self.ndim)
if isinstance(other, ABCSeries):
other = self._holder(other)
if isinstance(other, bool):
... | [
"\n localize and return i8 for the values\n\n Parameters\n ----------\n values : ndarray-like\n other : ndarray-like or scalar\n\n Returns\n -------\n base-type values, base-type other\n "
] |
Please provide a description of the function:def _try_coerce_result(self, result):
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)):
res... | [
" reverse of try_coerce_args "
] |
Please provide a description of the function:def diff(self, n, axis=0):
if axis == 0:
# Cannot currently calculate diff across multiple blocks since this
# function is invoked via apply
raise NotImplementedError
new_values = (self.values - self.shift(n, axis=... | [
"1st discrete difference\n\n Parameters\n ----------\n n : int, number of periods to diff\n axis : int, axis to diff upon. default 0\n\n Return\n ------\n A list with a new TimeDeltaBlock.\n\n Note\n ----\n The arguments here are mimicking shift ... |
Please provide a description of the function:def _try_coerce_args(self, values, other):
values = values.view('i8')
if isinstance(other, bool):
raise TypeError
elif is_null_datetimelike(other):
other = tslibs.iNaT
elif isinstance(other, (timedelta, np.tim... | [
"\n Coerce values and other to int64, with null values converted to\n iNaT. values is always ndarray-like, other may not be\n\n Parameters\n ----------\n values : ndarray-like\n other : ndarray-like or scalar\n\n Returns\n -------\n base-type values, ba... |
Please provide a description of the function:def _try_coerce_result(self, result):
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 isi... | [
" reverse of try_coerce_args / try_operate "
] |
Please provide a description of the function:def to_native_types(self, slicer=None, na_rep=None, quoting=None,
**kwargs):
values = self.values
if slicer is not None:
values = values[:, slicer]
mask = isna(values)
rvalues = np.empty(values.sh... | [
" convert to our native types format, slicing if desired "
] |
Please provide a description of the function:def convert(self, *args, **kwargs):
if args:
raise NotImplementedError
by_item = kwargs.get('by_item', True)
new_inputs = ['coerce', 'datetime', 'numeric', 'timedelta']
new_style = False
for kw in new_inputs:
... | [
" attempt to coerce any object types to better types return a copy of\n the block (if copy = True) by definition we ARE an ObjectBlock!!!!!\n\n can return multiple blocks!\n "
] |
Please provide a description of the function:def set(self, locs, values):
try:
self.values[locs] = values
except (ValueError):
# broadcasting error
# see GH6171
new_shape = list(values.shape)
new_shape[0] = len(self.items)
... | [
"\n Modify Block in-place with new item value\n\n Returns\n -------\n None\n "
] |
Please provide a description of the function:def _try_coerce_args(self, values, other):
if isinstance(other, ABCDatetimeIndex):
# May get a DatetimeIndex here. Unbox it.
other = other.array
if isinstance(other, DatetimeArray):
# hit in pandas/tests/indexing... | [
" provide coercion to our input arguments "
] |
Please provide a description of the function:def _replace_single(self, to_replace, value, inplace=False, filter=None,
regex=False, convert=True, mask=None):
inplace = validate_bool_kwarg(inplace, 'inplace')
# to_replace is regex compilable
to_rep_re = regex and ... | [
"\n Replace elements by the given value.\n\n Parameters\n ----------\n to_replace : object or pattern\n Scalar to replace or regular expression to match.\n value : object\n Replacement object.\n inplace : bool, default False\n Perform inplac... |
Please provide a description of the function:def _replace_coerce(self, to_replace, value, inplace=True, regex=False,
convert=False, mask=None):
if mask.any():
block = super()._replace_coerce(
to_replace=to_replace, value=value, inplace=inplace,
... | [
"\n Replace value corresponding to the given boolean array with another\n value.\n\n Parameters\n ----------\n to_replace : object or pattern\n Scalar to replace or regular expression to match.\n value : object\n Replacement object.\n inplace : ... |
Please provide a description of the function:def _try_coerce_result(self, result):
# 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... | [
" reverse of try_coerce_args "
] |
Please provide a description of the function:def to_native_types(self, slicer=None, na_rep='', quoting=None, **kwargs):
values = self.values
if slicer is not None:
# Categorical is always one dimension
values = values[slicer]
mask = isna(values)
values =... | [
" convert to our native types format, slicing if desired "
] |
Please provide a description of the function:def _style_to_xlwt(cls, item, firstlevel=True, field_sep=',',
line_sep=';'):
if hasattr(item, 'items'):
if firstlevel:
it = ["{key}: {val}"
.format(key=key, val=cls._style_to_xlwt(value... | [
"helper which recursively generate an xlwt easy style string\n for example:\n\n hstyle = {\"font\": {\"bold\": True},\n \"border\": {\"top\": \"thin\",\n \"right\": \"thin\",\n \"bottom\": \"thin\",\n \"left\": \"thin\"},\n ... |
Please provide a description of the function:def _convert_to_style(cls, style_dict, num_format_str=None):
import xlwt
if style_dict:
xlwt_stylestr = cls._style_to_xlwt(style_dict)
style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
else:
... | [
"\n converts a style_dict to an xlwt style object\n Parameters\n ----------\n style_dict : style dictionary to convert\n num_format_str : optional number format string\n "
] |
Please provide a description of the function:def convert(cls, style_dict, num_format_str=None):
# Create a XlsxWriter format object.
props = {}
if num_format_str is not None:
props['num_format'] = num_format_str
if style_dict is None:
return props
... | [
"\n converts a style_dict to an xlsxwriter format dict\n\n Parameters\n ----------\n style_dict : style dictionary to convert\n num_format_str : optional number format string\n "
] |
Please provide a description of the function:def _unstack_extension_series(series, level, fill_value):
# Implementation note: the basic idea is to
# 1. Do a regular unstack on a dummy array of integers
# 2. Followup with a columnwise take.
# We use the dummy take to discover newly-created missing v... | [
"\n Unstack an ExtensionArray-backed Series.\n\n The ExtensionDtype is preserved.\n\n Parameters\n ----------\n series : Series\n A Series with an ExtensionArray for values\n level : Any\n The level name or number.\n fill_value : Any\n The user-level (not physical storage) ... |
Please provide a description of the function:def stack(frame, level=-1, dropna=True):
def factorize(index):
if index.is_unique:
return index, np.arange(len(index))
codes, categories = _factorize_from_iterable(index)
return categories, codes
N, K = frame.shape
# Wil... | [
"\n Convert DataFrame to Series with multi-level Index. Columns become the\n second level of the resulting hierarchical index\n\n Returns\n -------\n stacked : Series\n "
] |
Please provide a description of the function:def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
columns=None, sparse=False, drop_first=False, dtype=None):
from pandas.core.reshape.concat import concat
from itertools import cycle
dtypes_to_encode = ['object', 'category']... | [
"\n Convert categorical variable into dummy/indicator variables.\n\n Parameters\n ----------\n data : array-like, Series, or DataFrame\n Data of which to get dummy indicators.\n prefix : str, list of str, or dict of str, default None\n String to append DataFrame column names.\n P... |
Please provide a description of the function:def make_axis_dummies(frame, axis='minor', transform=None):
numbers = {'major': 0, 'minor': 1}
num = numbers.get(axis, axis)
items = frame.index.levels[num]
codes = frame.index.codes[num]
if transform is not None:
mapped_items = items.map(tr... | [
"\n Construct 1-0 dummy variables corresponding to designated axis\n labels\n\n Parameters\n ----------\n frame : DataFrame\n axis : {'major', 'minor'}, default 'minor'\n transform : function, default None\n Function to apply to axis labels first. For example, to\n get \"day of we... |
Please provide a description of the function:def _reorder_for_extension_array_stack(arr, n_rows, n_columns):
# final take to get the order correct.
# idx is an indexer like
# [c0r0, c1r0, c2r0, ...,
# c0r1, c1r1, c2r1, ...]
idx = np.arange(n_rows * n_columns).reshape(n_columns, n_rows).T.ravel... | [
"\n Re-orders the values when stacking multiple extension-arrays.\n\n The indirect stacking method used for EAs requires a followup\n take to get the order correct.\n\n Parameters\n ----------\n arr : ExtensionArray\n n_rows, n_columns : int\n The number of rows and columns in the origin... |
Please provide a description of the function:def _split_line(s, parts):
out = {}
start = 0
for name, length in parts:
out[name] = s[start:start + length].strip()
start += length
del out['_']
return out | [
"\n Parameters\n ----------\n s: string\n Fixed-length string to split\n parts: list of (name, length) pairs\n Used to break up string, name '_' will be filtered from output.\n\n Returns\n -------\n Dict of name:contents of string at given location.\n "
] |
Please provide a description of the function:def _parse_float_vec(vec):
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 IBM
# number sans exponent
ieee1 = xport1 & 0x00ffffff... | [
"\n Parse a vector of float values representing IBM 8 byte floats into\n native 8 byte floats.\n "
] |
Please provide a description of the function:def _record_count(self):
self.filepath_or_buffer.seek(0, 2)
total_records_length = (self.filepath_or_buffer.tell() -
self.record_start)
if total_records_length % 80 != 0:
warnings.warn("xport file... | [
"\n Get number of records in file.\n\n This is maybe suboptimal because we have to seek to the end of\n the file.\n\n Side effect: returns file position to record_start.\n "
] |
Please provide a description of the function:def get_chunk(self, size=None):
if size is None:
size = self._chunksize
return self.read(nrows=size) | [
"\n Reads lines from Xport file and returns as dataframe\n\n Parameters\n ----------\n size : int, defaults to None\n Number of lines to read. If None, reads whole file.\n\n Returns\n -------\n DataFrame\n "
] |
Please provide a description of the function:def construction_error(tot_items, block_shape, axes, e=None):
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]
implied =... | [
" raise a helpful message about our construction "
] |
Please provide a description of the function:def _simple_blockify(tuples, dtype):
values, placement = _stack_arrays(tuples, dtype)
# CHECK DTYPE?
if dtype is not None and values.dtype != dtype: # pragma: no cover
values = values.astype(dtype)
block = make_block(values, placement=placemen... | [
" return a single array of a block that has a single dtype; if dtype is\n not None, coerce to this dtype\n "
] |
Please provide a description of the function:def _multi_blockify(tuples, dtype=None):
# 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), dtype)
block = mak... | [
" return an array of blocks that potentially have different dtypes "
] |
Please provide a description of the function:def _sparse_blockify(tuples, dtype=None):
new_blocks = []
for i, names, array in tuples:
array = _maybe_to_sparse(array)
block = make_block(array, placement=[i])
new_blocks.append(block)
return new_blocks | [
" return an array of blocks that potentially have different dtypes (and\n are sparse)\n "
] |
Please provide a description of the function:def _interleaved_dtype(
blocks: List[Block]
) -> Optional[Union[np.dtype, ExtensionDtype]]:
if not len(blocks):
return None
return find_common_type([b.dtype for b in blocks]) | [
"Find the common dtype for `blocks`.\n\n Parameters\n ----------\n blocks : List[Block]\n\n Returns\n -------\n dtype : Optional[Union[np.dtype, ExtensionDtype]]\n None is returned when `blocks` is empty.\n "
] |
Please provide a description of the function:def _consolidate(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_blocks in grouper:
merged_block... | [
"\n Merge blocks having same dtype, exclude non-consolidating blocks\n "
] |
Please provide a description of the function:def _compare_or_regex_search(a, b, regex=False):
if not regex:
op = lambda x: operator.eq(x, b)
else:
op = np.vectorize(lambda x: bool(re.search(b, x)) if isinstance(x, str)
else False)
is_a_array = isinstance(a, np... | [
"\n Compare two array_like inputs of the same shape or two scalar values\n\n Calls operator.eq or re.search, depending on regex argument. If regex is\n True, perform an element-wise regex matching.\n\n Parameters\n ----------\n a : array_like or scalar\n b : array_like or scalar\n regex : bo... |
Please provide a description of the function:def items_overlap_with_suffix(left, lsuffix, right, rsuffix):
to_rename = left.intersection(right)
if len(to_rename) == 0:
return left, right
else:
if not lsuffix and not rsuffix:
raise ValueError('columns overlap but no suffix sp... | [
"\n If two indices overlap, add suffixes to overlapping entries.\n\n If corresponding suffix is empty, the entry is simply converted to string.\n\n ",
"Rename the left and right indices.\n\n If there is overlap, and suffix is not None, add\n suffix, otherwise, leave it as-is.\n\n ... |
Please provide a description of the function:def _transform_index(index, func, level=None):
if isinstance(index, MultiIndex):
if level is not None:
items = [tuple(func(y) if i == level else y
for i, y in enumerate(x)) for x in index]
else:
item... | [
"\n Apply function to all values found in index.\n\n This includes transforming multiindex entries separately.\n Only apply function to one level of the MultiIndex if level is specified.\n\n "
] |
Please provide a description of the function:def _fast_count_smallints(arr):
counts = np.bincount(arr.astype(np.int_))
nz = counts.nonzero()[0]
return np.c_[nz, counts[nz]] | [
"Faster version of set(arr) for sequences of small numbers."
] |
Please provide a description of the function:def concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy):
concat_plans = [get_mgr_concatenation_plan(mgr, indexers)
for mgr, indexers in mgrs_indexers]
concat_plan = combine_concat_plans(concat_plans, concat_axis)
blocks = [... | [
"\n Concatenate block managers into one.\n\n Parameters\n ----------\n mgrs_indexers : list of (BlockManager, {axis: indexer,...}) tuples\n axes : list of Index\n concat_axis : int\n copy : bool\n\n "
] |
Please provide a description of the function:def make_empty(self, axes=None):
if axes is None:
axes = [ensure_index([])] + [ensure_index(a)
for a in self.axes[1:]]
# preserve dtype if possible
if self.ndim == 1:
blocks = ... | [
" return an empty BlockManager with the items axis of len 0 "
] |
Please provide a description of the function:def rename_axis(self, mapper, axis, copy=True, level=None):
obj = self.copy(deep=copy)
obj.set_axis(axis, _transform_index(self.axes[axis], mapper, level))
return obj | [
"\n Rename one of axes.\n\n Parameters\n ----------\n mapper : unary callable\n axis : int\n copy : boolean, default True\n level : int, default None\n "
] |
Please provide a description of the function:def _rebuild_blknos_and_blklocs(self):
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 enumerate(self.block... | [
"\n Update mgr._blknos / mgr._blklocs.\n "
] |
Please provide a description of the function:def _get_counts(self, f):
self._consolidate_inplace()
counts = dict()
for b in self.blocks:
v = f(b)
counts[v] = counts.get(v, 0) + b.shape[0]
return counts | [
" return a dict of the counts of the function in BlockManager "
] |
Please provide a description of the function:def apply(self, f, axes=None, filter=None, do_integrity_check=False,
consolidate=True, **kwargs):
result_blocks = []
# filter kwarg is used in replace-* family of methods
if filter is not None:
filter_locs = set(se... | [
"\n iterate over the blocks, collect and create a new block manager\n\n Parameters\n ----------\n f : the callable or function name to operate on at the block level\n axes : optional (if not supplied, use self.axes)\n filter : list, if supplied, only call the block if the f... |
Please provide a description of the function:def quantile(self, axis=0, consolidate=True, transposed=False,
interpolation='linear', qs=None, numeric_only=None):
# Series dispatches to DataFrame for quantile, which allows us to
# simplify some of the code here and in the block... | [
"\n Iterate over blocks applying quantile reduction.\n This routine is intended for reduction type operations and\n will do inference on the generated blocks.\n\n Parameters\n ----------\n axis: reduction axis, default 0\n consolidate: boolean, default True. Join tog... |
Please provide a description of the function:def replace_list(self, src_list, dest_list, inplace=False, regex=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
# figure out our mask a-priori to avoid repeated replacements
values = self.as_array()
def comp(s, regex=Fal... | [
" do a list replace ",
"\n Generate a bool array by perform an equality check, or perform\n an element-wise regular expression matching\n "
] |
Please provide a description of the function:def get_bool_data(self, copy=False):
self._consolidate_inplace()
return self.combine([b for b in self.blocks if b.is_bool], copy) | [
"\n Parameters\n ----------\n copy : boolean, default False\n Whether to copy the blocks\n "
] |
Please provide a description of the function:def get_numeric_data(self, copy=False):
self._consolidate_inplace()
return self.combine([b for b in self.blocks if b.is_numeric], copy) | [
"\n Parameters\n ----------\n copy : boolean, default False\n Whether to copy the blocks\n "
] |
Please provide a description of the function:def combine(self, blocks, copy=True):
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])... | [
" return a new manager with the blocks "
] |
Please provide a description of the function:def copy(self, deep=True):
# this preserves the notion of view copying of axes
if deep:
if deep == 'all':
copy = lambda ax: ax.copy(deep=True)
else:
copy = lambda ax: ax.view()
new_a... | [
"\n Make deep or shallow copy of BlockManager\n\n Parameters\n ----------\n deep : boolean o rstring, default True\n If False, return shallow copy (do not copy data)\n If 'all', copy data and a deep copy of the index\n\n Returns\n -------\n copy... |
Please provide a description of the function:def as_array(self, transpose=False, items=None):
if len(self.blocks) == 0:
arr = np.empty(self.shape, dtype=float)
return arr.transpose() if transpose else arr
if items is not None:
mgr = self.reindex_axis(items, ... | [
"Convert the blockmanager data into an numpy array.\n\n Parameters\n ----------\n transpose : boolean, default False\n If True, transpose the return array\n items : list of strings or None\n Names of block items that will be included in the returned\n arr... |
Please provide a description of the function:def _interleave(self):
from pandas.core.dtypes.common import is_sparse
dtype = _interleaved_dtype(self.blocks)
# TODO: https://github.com/pandas-dev/pandas/issues/22791
# Give EAs some input on what happens here. Sparse needs this.
... | [
"\n Return ndarray from blocks with specified item order\n Items must be contained in the blocks\n "
] |
Please provide a description of the function:def to_dict(self, copy=True):
self._consolidate_inplace()
bd = {}
for b in self.blocks:
bd.setdefault(str(b.dtype), []).append(b)
return {dtype: self.combine(blocks, copy=copy)
for dtype, blocks in bd.ite... | [
"\n Return a dict of str(dtype) -> BlockManager\n\n Parameters\n ----------\n copy : boolean, default True\n\n Returns\n -------\n values : a dict of dtype -> BlockManager\n\n Notes\n -----\n This consolidates based on str(dtype)\n "
] |
Please provide a description of the function:def fast_xs(self, loc):
if len(self.blocks) == 1:
return self.blocks[0].iget((slice(None), loc))
items = self.items
# non-unique (GH4726)
if not items.is_unique:
result = self._interleave()
if sel... | [
"\n get a cross sectional for a given location in the\n items ; handle dups\n\n return the result, is *could* be a view in the case of a\n single block\n "
] |
Please provide a description of the function:def consolidate(self):
if self.is_consolidated():
return self
bm = self.__class__(self.blocks, self.axes)
bm._is_consolidated = False
bm._consolidate_inplace()
return bm | [
"\n Join together blocks having same dtype\n\n Returns\n -------\n y : BlockManager\n "
] |
Please provide a description of the function:def get(self, item, fastpath=True):
if self.items.is_unique:
if not isna(item):
loc = self.items.get_loc(item)
else:
indexer = np.arange(len(self.items))[isna(self.items)]
# allow a si... | [
"\n Return values for selected item (ndarray or BlockManager).\n "
] |
Please provide a description of the function:def iget(self, i, fastpath=True):
block = self.blocks[self._blknos[i]]
values = block.iget(self._blklocs[i])
if not fastpath or not block._box_to_block_values or values.ndim != 1:
return values
# fastpath shortcut for sel... | [
"\n Return the data as a SingleBlockManager if fastpath=True and possible\n\n Otherwise return as a ndarray\n "
] |
Please provide a description of the function:def delete(self, item):
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 = [False] * len(self.blocks)
... | [
"\n Delete selected item (items if non-unique) in-place.\n "
] |
Please provide a description of the function:def set(self, item, value):
# FIXME: refactor, clearly separate broadcasting & zip-like assignment
# can prob also fix the various if tests for sparse/categorical
# TODO(EA): Remove an is_extension_ when all extension types satisfy
... | [
"\n Set new item in-place. Does not consolidate. Adds new Block if not\n contained in the current set of items\n "
] |
Please provide a description of the function:def insert(self, loc, item, value, allow_duplicates=False):
if not allow_duplicates and item in self.items:
# Should this be a different kind of error??
raise ValueError('cannot insert {}, already exists'.format(item))
if not... | [
"\n Insert item at selected position.\n\n Parameters\n ----------\n loc : int\n item : hashable\n value : array_like\n allow_duplicates: bool\n If False, trying to insert non-unique item will raise\n\n "
] |
Please provide a description of the function:def reindex_axis(self, new_index, axis, method=None, limit=None,
fill_value=None, copy=True):
new_index = ensure_index(new_index)
new_index, indexer = self.axes[axis].reindex(new_index, method=method,
... | [
"\n Conform block manager to new index.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.