text
stringlengths
81
112k
Get result for Cythonized functions. Parameters ---------- how : str, Cythonized function name to be called grouper : Grouper object containing pertinent group info aggregate : bool, default False Whether the result should be aggregated to match the number of ...
Shift each group by periods observations. Parameters ---------- periods : integer, default 1 number of periods to shift freq : frequency string axis : axis to shift, default 0 fill_value : optional .. versionadded:: 0.24.0 def shift(self, period...
Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) >>> df.gr...
Return last n rows of each group. Essentially equivalent to ``.apply(lambda x: x.tail(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], columns=['A', 'B']) ...
If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday, use Monday instead def next_monday(dt): """ If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday, use Monday instead """ if dt.weekday() == 5: return dt + timedelta(...
For second holiday of two adjacent ones! If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday or Monday, use following Tuesday instead (because Monday is already taken by adjacent holiday on the day before) def next_monday_or_tuesday(dt): """ For second holiday of ...
If holiday falls on Saturday or Sunday, use previous Friday instead. def previous_friday(dt): """ If holiday falls on Saturday or Sunday, use previous Friday instead. """ if dt.weekday() == 5: return dt - timedelta(1) elif dt.weekday() == 6: return dt - timedelta(2) return dt
If holiday falls on Sunday or Saturday, use day thereafter (Monday) instead. Needed for holidays such as Christmas observation in Europe def weekend_to_monday(dt): """ If holiday falls on Sunday or Saturday, use day thereafter (Monday) instead. Needed for holidays such as Christmas observation ...
If holiday falls on Saturday, use day before (Friday) instead; if holiday falls on Sunday, use day thereafter (Monday) instead. def nearest_workday(dt): """ If holiday falls on Saturday, use day before (Friday) instead; if holiday falls on Sunday, use day thereafter (Monday) instead. """ if dt....
returns next weekday used for observances def next_workday(dt): """ returns next weekday used for observances """ dt += timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt += timedelta(days=1) return dt
returns previous weekday used for observances def previous_workday(dt): """ returns previous weekday used for observances """ dt -= timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt -= timedelta(days=1) return dt
Calculate holidays observed between start date and end date Parameters ---------- start_date : starting date, datetime-like, optional end_date : ending date, datetime-like, optional return_name : bool, optional, default=False If True, return a series that has dates a...
Get reference dates for the holiday. Return reference dates for the holiday also returning the year prior to the start_date and year following the end_date. This ensures that any offsets to be applied will yield the holidays within the passed in dates. def _reference_dates(self, start...
Apply the given offset/observance to a DatetimeIndex of dates. Parameters ---------- dates : DatetimeIndex Dates to apply the given offset/observance rule Returns ------- Dates with rules applied def _apply_rule(self, dates): """ Apply the g...
Returns a curve with holidays between start_date and end_date Parameters ---------- start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional If True, return a series that has dates and holiday names. ...
Merge holiday calendars together. The base calendar will take precedence to other. The merge will be done based on each holiday's name. Parameters ---------- base : AbstractHolidayCalendar instance/subclass or array of Holiday objects other : AbstractHolidayCal...
Merge holiday calendars together. The caller's class rules take precedence. The merge will be done based on each holiday's name. Parameters ---------- other : holiday calendar inplace : bool (default=False) If True set rule_table to holidays, else return ar...
Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the option validator - a function of a single argument, should raise `Value...
Mark option `key` as deprecated, if code attempts to access this option, a warning will be produced, using `msg` if given, or a default message if not. if `rkey` is given, any access to the key will be re-routed to `rkey`. Neither the existence of `key` nor that if `rkey` is checked. If they do not...
returns a list of keys matching `pat` if pat=="all", returns all registered options def _select_options(pat): """returns a list of keys matching `pat` if pat=="all", returns all registered options """ # short-circuit for exact key if pat in _registered_options: return [pat] # el...
if key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is def _translate_key(key): """ if key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is """ d = _get_deprecated_option(...
Builds a formatted description of a registered option and prints it def _build_option_description(k): """ Builds a formatted description of a registered option and prints it """ o = _get_registered_option(k) d = _get_deprecated_option(k) s = '{k} '.format(k=k) if o.doc: s += '\n'.join(o....
contextmanager for multiple invocations of API with a common prefix supported API functions: (register / get / set )__option Warning: This is not thread - safe, and won't work properly if you import the API functions into your module using the "from x import y" construct. Example: import pandas....
Generates (prop, value) pairs from declarations In a future version may generate parsed tokens from tinycss/tinycss2 def parse(self, declarations_str): """Generates (prop, value) pairs from declarations In a future version may generate parsed tokens from tinycss/tinycss2 """ f...
Create an array. .. versionadded:: 0.24.0 Parameters ---------- data : Sequence of objects The scalars inside `data` should be instances of the scalar type for `dtype`. It's expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Serie...
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 Inte...
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. .. versionadded:: 0.20.0 Param...
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 ---------- obj : The object to check allow_sets : boolean, d...
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. Examples -------- >>> is_nested_...
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, 3]) False >>> is_dict_like(...
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 -------- >>> l = [1, 2, 3] >>> >>>...
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"], DatetimeI...
Return a fixed frequency DatetimeIndex. Parameters ---------- start : str or datetime-like, optional Left bound for generating dates. end : str or datetime-like, optional Right bound for generating dates. periods : integer, optional Number of periods to generate. freq : ...
Return a fixed frequency DatetimeIndex, with business day as the default frequency Parameters ---------- start : string or datetime-like, default None Left bound for generating dates. end : string or datetime-like, default None Right bound for generating dates. periods : integer...
Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the default frequency .. deprecated:: 0.21.0 Parameters ---------- start : string or datetime-like, default None Left bound for generating dates end : string or datetime-like, default None Right bound for generat...
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...
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 def _gotitem(self, key, ndim, subset=None): """ Sub-cla...
Return index as ndarrays. Returns ------- tuple of (index, index_as_ndarray) def _get_index(self, index=None): """ Return index as ndarrays. Returns ------- tuple of (index, index_as_ndarray) """ if self.is_freq_type: if ind...
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 i...
Wrap the results. Parameters ---------- results : list of ndarrays blocks : list of blocks obj : conformed data (may be resampled) def _wrap_results(self, results, blocks, obj): """ Wrap the results. Parameters ---------- results : list ...
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 = ...
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 isinstanc...
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 input argument def _apply_window(self, mean=True, **kwargs): ...
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 ...
Rolling statistical measure using supplied function. Designed to be used with passed-in Cython array-based functions. Parameters ---------- func : str/callable to apply name : str, optional name of this function window : int/array, default to _get_window() ...
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 ...
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 covariance. Returns ------- window :...
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 argument def _apply(self, func, **kwargs): ""...
Exponential weighted moving average. Parameters ---------- *args, **kwargs Arguments and keyword arguments to be passed into func. def mean(self, *args, **kwargs): """ Exponential weighted moving average. Parameters ---------- *args, **kwarg...
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), ...
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 No...
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 p...
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: ...
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 containing the names of the indices Returns --...
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...
Construct Panel from dict of DataFrame objects. Parameters ---------- data : dict {field : DataFrame} intersect : boolean Intersect indexes of input DataFrames orient : {'items', 'minor'}, default 'items' The "orientation" of the data. If the ...
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 re...
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 Data...
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 '' Missing data representation engine : string, default None write en...
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 item row) minor : minor axis label (panel item colu...
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 row) minor : minor axis label (panel item column) ...
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 = _unp...
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 columns would be items, and the index would be v...
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 negative, it specifies the number of positions to the l...
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 how : {'all', 'any'}, default 'any' 'any': one or more val...
Return slice of panel along selected axis. Parameters ---------- key : object Label axis : {'items', 'major', 'minor}, default 1/'major' Returns ------- y : ndim(self)-1 Notes ----- xs is only for getting, not setting values....
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] # ...
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_observations : boolean, default True Drop (major, minor) pairs w...
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_axis will each be passed as a Series; if axis = ('items',...
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 ...
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...
Return number of observations over requested axis. Parameters ---------- axis : {'items', 'major', 'minor'} or {0, 1, 2} Returns ------- count : DataFrame def count(self, axis='major'): """ Return number of observations over requested axis. Par...
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 DataFrame.shift() Parameters ---------- periods : in...
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', 'right', 'outer', 'inner'} How to handle indexes of the two objects. ...
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 object coercible to Panel The object from which the caller will be udpated. join : {'left', 'right', 'out...
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. Parameters ---------- frames : dict intersect : boolean, default True Returns ------- dict of aligned results & indices def _homogenize_dict(self,...
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 decon...
reconstruct labels from observed group ids Parameters ---------- xnull: boolean, if nulls are excluded; i.e. -1 labels are passed through def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull): """ reconstruct labels from observed group ids Parameters ---------- xnu...
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...
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) \ ...
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.argso...
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 produ...
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 ---------- values : list-like Sequence; must be unique if ``labels`` is no...
Attempt to prevent foot-shooting in a helpful way. Parameters ---------- terms : Term Terms can contain def _check_ne_builtin_clash(expr): """Attempt to prevent foot-shooting in a helpful way. Parameters ---------- terms : Term Terms can contain """ names = expr.na...
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. def evaluate(self): """Ru...
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 def get_block_type(values, dtype=None): """ Find the appropriate Block subclass to us...
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 isins...
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: ...
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 returned. Parameters ---------- arr : ar...
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 ------- values : ndarray with updated ...
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 ---------- values : array-like ndim : int or None ...
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 C...
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 """ i...
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: plac...
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 ...
Perform __getitem__-like, return result as block. As of now, only supports slices that preserve dimensionality. 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. ...