INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Create an array.
def array(data: Sequence[object], dtype: Optional[Union[str, np.dtype, ExtensionDtype]] = None, copy: bool = True, ) -> ABCExtensionArray: """ Create an array. .. versionadded:: 0.24.0 Parameters ---------- data : Sequence of objects The scalars inside `da...
Try to do platform conversion with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example empty lists return with integer dtype instead of object dtype which is prohibited for IntervalArray.
def maybe_convert_platform_interval(values): """ Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype ...
Check if the object is a file - like object.
def is_file_like(obj): """ Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. ...
Check if the object is list - like.
def is_list_like(obj, allow_sets=True): """ Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime objects, however, are not considered list-like. Parameters ---------- o...
Check if the object is list - like and that all of its elements are also list - like.
def is_nested_list_like(obj): """ Check if the object is list-like, and that all of its elements are also list-like. .. versionadded:: 0.20.0 Parameters ---------- obj : The object to check Returns ------- is_list_like : bool Whether `obj` has list-like properties. ...
Check if the object is dict - like.
def is_dict_like(obj): """ Check if the object is dict-like. Parameters ---------- obj : The object to check Returns ------- is_dict_like : bool Whether `obj` has dict-like properties. Examples -------- >>> is_dict_like({1: 2}) True >>> is_dict_like([1, 2, ...
Check if the object is a sequence of objects. String types are not included as sequences here.
def is_sequence(obj): """ Check if the object is a sequence of objects. String types are not included as sequences here. Parameters ---------- obj : The object to check Returns ------- is_sequence : bool Whether `obj` is a sequence of objects. Examples -------- ...
This is called upon unpickling rather than the default which doesn t have arguments and breaks __new__
def _new_DatetimeIndex(cls, d): """ This is called upon unpickling, rather than the default which doesn't have arguments and breaks __new__ """ if "data" in d and not isinstance(d["data"], DatetimeIndex): # Avoid need to verify integrity by calling simple_new directly data = d.pop("data") ...
Return a fixed frequency DatetimeIndex.
def date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs): """ Return a fixed frequency DatetimeIndex. Parameters ---------- start : str or datetime-like, optional Left bound for generating dates. end : str o...
Return a fixed frequency DatetimeIndex with business day as the default frequency
def bdate_range(start=None, end=None, periods=None, freq='B', tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs): """ Return a fixed frequency DatetimeIndex, with business day as the default frequency Parameters ---------- st...
Return a fixed frequency DatetimeIndex with CustomBusinessDay as the default frequency
def cdate_range(start=None, end=None, periods=None, freq='C', tz=None, normalize=True, name=None, closed=None, **kwargs): """ Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the default frequency .. deprecated:: 0.21.0 Parameters ---------- start : string ...
Split data into blocks & return conformed data.
def _create_blocks(self): """ Split data into blocks & return conformed data. """ obj, index = self._convert_freq() if index is not None: index = self._on # filter out the on from the object if self.on is not None: if obj.ndim == 2: ...
Sub - classes to define. Return a sliced object.
def _gotitem(self, key, ndim, subset=None): """ Sub-classes to define. Return a sliced object. Parameters ---------- key : str / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on ...
Return index as ndarrays.
def _get_index(self, index=None): """ Return index as ndarrays. Returns ------- tuple of (index, index_as_ndarray) """ if self.is_freq_type: if index is None: index = self._on return index, index.asi8 return index,...
Wrap a single result.
def _wrap_result(self, result, block=None, obj=None): """ Wrap a single result. """ if obj is None: obj = self._selected_obj index = obj.index if isinstance(result, np.ndarray): # coerce if necessary if block is not None: ...
Wrap the results.
def _wrap_results(self, results, blocks, obj): """ Wrap the results. Parameters ---------- results : list of ndarrays blocks : list of blocks obj : conformed data (may be resampled) """ from pandas import Series, concat from pandas.core.i...
Center the result in the window.
def _center_window(self, result, window): """ Center the result in the window. """ if self.axis > result.ndim - 1: raise ValueError("Requested axis is larger then no. of argument " "dimensions") offset = _offset(window, True) if o...
Provide validation for our window type return the window we have already been validated.
def _prep_window(self, **kwargs): """ Provide validation for our window type, return the window we have already been validated. """ window = self._get_window() if isinstance(window, (list, tuple, np.ndarray)): return com.asarray_tuplesafe(window).astype(float...
Applies a moving window of type window_type on the data.
def _apply_window(self, mean=True, **kwargs): """ Applies a moving window of type ``window_type`` on the data. Parameters ---------- mean : bool, default True If True computes weighted mean, else weighted sum Returns ------- y : same type as ...
Dispatch to apply ; we are stripping all of the _apply kwargs and performing the original function call on the grouped object.
def _apply(self, func, name, window=None, center=None, check_minp=None, **kwargs): """ Dispatch to apply; we are stripping all of the _apply kwargs and performing the original function call on the grouped object. """ def f(x, name=name, *args): x = sel...
Rolling statistical measure using supplied function.
def _apply(self, func, name=None, window=None, center=None, check_minp=None, **kwargs): """ Rolling statistical measure using supplied function. Designed to be used with passed-in Cython array-based functions. Parameters ---------- func : str/callable to ...
Validate on is_monotonic.
def _validate_monotonic(self): """ Validate on is_monotonic. """ if not self._on.is_monotonic: formatted = self.on or 'index' raise ValueError("{0} must be " "monotonic".format(formatted))
Validate & return window frequency.
def _validate_freq(self): """ Validate & return window frequency. """ from pandas.tseries.frequencies import to_offset try: return to_offset(self.window) except (TypeError, ValueError): raise ValueError("passed window {0} is not " ...
Get the window length over which to perform some operation.
def _get_window(self, other=None): """ Get the window length over which to perform some operation. Parameters ---------- other : object, default None The other object that is involved in the operation. Such an object is involved for operations like covari...
Rolling statistical measure using supplied function. Designed to be used with passed - in Cython array - based functions.
def _apply(self, func, **kwargs): """ Rolling statistical measure using supplied function. Designed to be used with passed-in Cython array-based functions. Parameters ---------- func : str/callable to apply Returns ------- y : same type as input ...
Exponential weighted moving average.
def mean(self, *args, **kwargs): """ Exponential weighted moving average. Parameters ---------- *args, **kwargs Arguments and keyword arguments to be passed into func. """ nv.validate_window_func('mean', args, kwargs) return self._apply('ewma'...
Exponential weighted moving stddev.
def std(self, bias=False, *args, **kwargs): """ Exponential weighted moving stddev. """ nv.validate_window_func('std', args, kwargs) return _zsqrt(self.var(bias=bias, **kwargs))
Exponential weighted moving variance.
def var(self, bias=False, *args, **kwargs): """ Exponential weighted moving variance. """ nv.validate_window_func('var', args, kwargs) def f(arg): return libwindow.ewmcov(arg, arg, self.com, int(self.adjust), int(self.ignore_na), i...
Exponential weighted sample covariance.
def cov(self, other=None, pairwise=None, bias=False, **kwargs): """ Exponential weighted sample covariance. """ if other is None: other = self._selected_obj # only default unset pairwise = True if pairwise is None else pairwise other = self._sh...
Exponential weighted sample correlation.
def corr(self, other=None, pairwise=None, **kwargs): """ Exponential weighted sample correlation. """ if other is None: other = self._selected_obj # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy...
Makes sure that time and panels are conformable.
def _ensure_like_indices(time, panels): """ Makes sure that time and panels are conformable. """ n_time = len(time) n_panel = len(panels) u_panels = np.unique(panels) # this sorts! u_time = np.unique(time) if len(u_time) == n_time: time = np.tile(u_time, len(u_panels)) if le...
Returns a multi - index suitable for a panel - like DataFrame.
def panel_index(time, panels, names=None): """ Returns a multi-index suitable for a panel-like DataFrame. Parameters ---------- time : array-like Time index, does not have to repeat panels : array-like Panel index, does not have to repeat names : list, optional List ...
Generate ND initialization ; axes are passed as required objects to __init__.
def _init_data(self, data, copy, dtype, **kwargs): """ Generate ND initialization; axes are passed as required objects to __init__. """ if data is None: data = {} if dtype is not None: dtype = self._validate_dtype(dtype) passed_axes = [kwa...
Construct Panel from dict of DataFrame objects.
def from_dict(cls, data, intersect=False, orient='items', dtype=None): """ Construct Panel from dict of DataFrame objects. Parameters ---------- data : dict {field : DataFrame} intersect : boolean Intersect indexes of input DataFrames orie...
Get my plane axes indexes: these are already ( as compared with higher level planes ) as we are returning a DataFrame axes indexes.
def _get_plane_axes_index(self, axis): """ Get my plane axes indexes: these are already (as compared with higher level planes), as we are returning a DataFrame axes indexes. """ axis_name = self._get_axis_name(axis) if axis_name == 'major_axis': index...
Get my plane axes indexes: these are already ( as compared with higher level planes ) as we are returning a DataFrame axes.
def _get_plane_axes(self, axis): """ Get my plane axes indexes: these are already (as compared with higher level planes), as we are returning a DataFrame axes. """ return [self._get_axis(axi) for axi in self._get_plane_axes_index(axis)]
Write each DataFrame in Panel to a separate excel sheet.
def to_excel(self, path, na_rep='', engine=None, **kwargs): """ Write each DataFrame in Panel to a separate excel sheet. Parameters ---------- path : string or ExcelWriter object File path or existing ExcelWriter na_rep : string, default '' Missin...
Quickly retrieve single value at ( item major minor ) location.
def get_value(self, *args, **kwargs): """ Quickly retrieve single value at (item, major, minor) location. .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- item : item label (panel item) major : major axis label (panel i...
Quickly set single value at ( item major minor ) location.
def set_value(self, *args, **kwargs): """ Quickly set single value at (item, major, minor) location. .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- item : item label (panel item) major : major axis label (panel item r...
Unpickle the panel.
def _unpickle_panel_compat(self, state): # pragma: no cover """ Unpickle the panel. """ from pandas.io.pickle import _unpickle_array _unpickle = _unpickle_array vals, items, major, minor = state items = _unpickle(items) major = _unpickle(major) ...
Conform input DataFrame to align with chosen axis pair.
def conform(self, frame, axis='items'): """ Conform input DataFrame to align with chosen axis pair. Parameters ---------- frame : DataFrame axis : {'items', 'major', 'minor'} Axis the input corresponds to. E.g., if axis='major', then the frame's ...
Round each value in Panel to a specified number of decimal places.
def round(self, decimals=0, *args, **kwargs): """ Round each value in Panel to a specified number of decimal places. .. versionadded:: 0.18.0 Parameters ---------- decimals : int Number of decimal places to round to (default: 0). If decimals is n...
Drop 2D from panel holding passed axis constant.
def dropna(self, axis=0, how='any', inplace=False): """ Drop 2D from panel, holding passed axis constant. Parameters ---------- axis : int, default 0 Axis to hold constant. E.g. axis=1 will drop major_axis entries having a certain amount of NA data ...
Return slice of panel along selected axis.
def xs(self, key, axis=1): """ Return slice of panel along selected axis. Parameters ---------- key : object Label axis : {'items', 'major', 'minor}, default 1/'major' Returns ------- y : ndim(self)-1 Notes ----- ...
Parameters ---------- i: int slice or sequence of integers axis: int
def _ixs(self, i, axis=0): """ Parameters ---------- i : int, slice, or sequence of integers axis : int """ ax = self._get_axis(axis) key = ax[i] # xs cannot handle a non-scalar key, so just reindex here # if we have a multi-index and a s...
Transform wide format into long ( stacked ) format as DataFrame whose columns are the Panel s items and whose index is a MultiIndex formed of the Panel s major and minor axes.
def to_frame(self, filter_observations=True): """ Transform wide format into long (stacked) format as DataFrame whose columns are the Panel's items and whose index is a MultiIndex formed of the Panel's major and minor axes. Parameters ---------- filter_observatio...
Apply function along axis ( or axes ) of the Panel.
def apply(self, func, axis='major', **kwargs): """ Apply function along axis (or axes) of the Panel. Parameters ---------- func : function Function to apply to each combination of 'other' axes e.g. if axis = 'items', the combination of major_axis/minor_ax...
Handle 2 - d slices equiv to iterating over the other axis.
def _apply_2d(self, func, axis): """ Handle 2-d slices, equiv to iterating over the other axis. """ ndim = self.ndim axis = [self._get_axis_number(a) for a in axis] # construct slabs, in 2-d this is a DataFrame result indexer_axis = list(range(ndim)) for ...
Return the type for the ndim of the result.
def _construct_return_type(self, result, axes=None): """ Return the type for the ndim of the result. """ ndim = getattr(result, 'ndim', None) # need to assume they are the same if ndim is None: if isinstance(result, dict): ndim = getattr(list(...
Return number of observations over requested axis.
def count(self, axis='major'): """ Return number of observations over requested axis. Parameters ---------- axis : {'items', 'major', 'minor'} or {0, 1, 2} Returns ------- count : DataFrame """ i = self._get_axis_number(axis) val...
Shift index by desired number of periods with an optional time freq.
def shift(self, periods=1, freq=None, axis='major'): """ Shift index by desired number of periods with an optional time freq. The shifted data will not include the dropped periods and the shifted axis will be smaller than the original. This is different from the behavior of Data...
Join items with other Panel either on major and minor axes column.
def join(self, other, how='left', lsuffix='', rsuffix=''): """ Join items with other Panel either on major and minor axes column. Parameters ---------- other : Panel or list of Panels Index should be similar to one of the columns in this one how : {'left', 'r...
Modify Panel in place using non - NA values from other Panel.
def update(self, other, join='left', overwrite=True, filter_func=None, errors='ignore'): """ Modify Panel in place using non-NA values from other Panel. May also use object coercible to Panel. Will align on items. Parameters ---------- other : Panel, or o...
Return a list of the axis indices.
def _extract_axes(self, data, axes, **kwargs): """ Return a list of the axis indices. """ return [self._extract_axis(self, data, axis=i, **kwargs) for i, a in enumerate(axes)]
Return the slice dictionary for these axes.
def _extract_axes_for_slice(self, axes): """ Return the slice dictionary for these axes. """ return {self._AXIS_SLICEMAP[i]: a for i, a in zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)}
Conform set of _constructor_sliced - like objects to either an intersection of indices/ columns or a union.
def _homogenize_dict(self, frames, intersect=True, dtype=None): """ Conform set of _constructor_sliced-like objects to either an intersection of indices / columns or a union. Parameters ---------- frames : dict intersect : boolean, default True Returns ...
For the particular label_list gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label combinations * as long as * this space fits within int64 bounds ; otherwise though group indices identify unique combinations of labels they cannot be deconstructed. - If so...
def get_group_index(labels, shape, sort, xnull): """ For the particular label_list, gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label combinations, *as long as* this space fits within int64 bounds; otherwise, though group indices ide...
reconstruct labels from observed group ids
def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull): """ reconstruct labels from observed group ids Parameters ---------- xnull: boolean, if nulls are excluded; i.e. -1 labels are passed through """ if not xnull: lift = np.fromiter(((a == -1).any() for a in la...
This is intended to be a drop - in replacement for np. argsort which handles NaNs. It adds ascending and na_position parameters. GH #6399 #5231
def nargsort(items, kind='quicksort', ascending=True, na_position='last'): """ This is intended to be a drop-in replacement for np.argsort which handles NaNs. It adds ascending and na_position parameters. GH #6399, #5231 """ # specially handle Categorical if is_categorical_dtype(items): ...
return a diction of { labels } - > { indexers }
def get_indexer_dict(label_list, keys): """ return a diction of {labels} -> {indexers} """ shape = list(map(len, keys)) group_index = get_group_index(label_list, shape, sort=True, xnull=True) ngroups = ((group_index.size and group_index.max()) + 1) \ if is_int64_overflow_possible(shape) \ ...
algos. groupsort_indexer implements counting sort and it is at least O ( ngroups ) where ngroups = prod ( shape ) shape = map ( len keys ) that is linear in the number of combinations ( cartesian product ) of unique values of groupby keys. This can be huge when doing multi - key groupby. np. argsort ( kind = mergesort ...
def get_group_index_sorter(group_index, ngroups): """ algos.groupsort_indexer implements `counting sort` and it is at least O(ngroups), where ngroups = prod(shape) shape = map(len, keys) that is, linear in the number of combinations (cartesian product) of unique values of groupby key...
Group_index is offsets into cartesian product of all possible labels. This space can be huge so this function compresses it by computing offsets ( comp_ids ) into the list of unique labels ( obs_group_ids ).
def compress_group_index(group_index, sort=True): """ Group_index is offsets into cartesian product of all possible labels. This space can be huge, so this function compresses it, by computing offsets (comp_ids) into the list of unique labels (obs_group_ids). """ size_hint = min(len(group_index...
Sort values and reorder corresponding labels. values should be unique if labels is not None. Safe for use with mixed types ( int str ) orders ints before strs.
def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False): """ Sort ``values`` and reorder corresponding ``labels``. ``values`` should be unique if ``labels`` is not None. Safe for use with mixed types (int, str), orders ints before strs. .. versionadded:: 0.19.0 Parameters -...
Attempt to prevent foot - shooting in a helpful way.
def _check_ne_builtin_clash(expr): """Attempt to prevent foot-shooting in a helpful way. Parameters ---------- terms : Term Terms can contain """ names = expr.names overlap = names & _ne_builtins if overlap: s = ', '.join(map(repr, overlap)) raise NumExprClobber...
Run the engine on the expression
def evaluate(self): """Run the engine on the expression This method performs alignment which is necessary no matter what engine is being used, thus its implementation is in the base class. Returns ------- obj : object The result of the passed expression. ...
Find the appropriate Block subclass to use for the given values and dtype.
def get_block_type(values, dtype=None): """ Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- values : ndarray-like dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block """ dtype = dtype or values.dtype ...
return a new extended blocks givin the result
def _extend_blocks(result, blocks=None): """ return a new extended blocks, givin the result """ from pandas.core.internals import BlockManager if blocks is None: blocks = [] if isinstance(result, list): for r in result: if isinstance(r, list): blocks.extend(r)...
guarantee the shape of the values to be at least 1 d
def _block_shape(values, ndim=1, shape=None): """ guarantee the shape of the values to be at least 1 d """ if values.ndim < ndim: if shape is None: shape = values.shape if not is_extension_array_dtype(values): # TODO: https://github.com/pandas-dev/pandas/issues/23023 ...
If possible reshape arr to have shape new_shape with a couple of exceptions ( see gh - 13012 ):
def _safe_reshape(arr, new_shape): """ If possible, reshape `arr` to have shape `new_shape`, with a couple of exceptions (see gh-13012): 1) If `arr` is a ExtensionArray or Index, `arr` will be returned as is. 2) If `arr` is a Series, the `_values` attribute will be reshaped and return...
Return a new ndarray try to preserve dtype if possible.
def _putmask_smart(v, m, n): """ Return a new ndarray, try to preserve dtype if possible. Parameters ---------- v : `values`, updated in-place (array like) m : `mask`, applies to both sides (array like) n : `new values` either scalar or an array like aligned with `values` Returns -...
ndim inference and validation.
def _check_ndim(self, values, ndim): """ ndim inference and validation. Infers ndim from 'values' if not provided to __init__. Validates that values.ndim and ndim are consistent if and only if the class variable '_validate_ndim' is True. Parameters ---------- ...
validate that we have a astypeable to categorical returns a boolean if we are a categorical
def is_categorical_astype(self, dtype): """ validate that we have a astypeable to categorical, returns a boolean if we are a categorical """ if dtype is Categorical or dtype is CategoricalDtype: # this is a pd.Categorical, but is not # a valid type for ast...
return an internal format currently just the ndarray this is often overridden to handle to_dense like operations
def get_values(self, dtype=None): """ return an internal format, currently just the ndarray this is often overridden to handle to_dense like operations """ if is_object_dtype(dtype): return self.values.astype(object) return self.values
Create a new block with type inference propagate any values that are not specified
def make_block(self, values, placement=None, ndim=None): """ Create a new block, with type inference propagate any values that are not specified """ if placement is None: placement = self.mgr_locs if ndim is None: ndim = self.ndim return m...
Wrap given values in a block of same type as self.
def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): """ Wrap given values in a block of same type as self. """ if dtype is not None: # issue 19431 fastparquet is passing this warnings.warn("dtype argument is deprecated, wi...
Perform __getitem__ - like return result as block.
def getitem_block(self, slicer, new_mgr_locs=None): """ Perform __getitem__-like, return result as block. As of now, only supports slices that preserve dimensionality. """ if new_mgr_locs is None: if isinstance(slicer, tuple): axis0_slicer = slicer[0]...
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.
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
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.
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
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
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
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
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
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...