text
stringlengths
81
112k
Take elements from the Categorical. Parameters ---------- indexer : sequence of int The indices in `self` to take. The meaning of negative values in `indexer` depends on the value of `allow_fill`. allow_fill : bool, default None How to handle negative...
Return a slice of myself. For internal compatibility with numpy arrays. def _slice(self, slicer): """ Return a slice of myself. For internal compatibility with numpy arrays. """ # only allow 1 dimensional slicing, but can # in a 2-d case be passd (slice(None),...
a short repr displaying only max_vals and an optional (but default footer) def _tidy_repr(self, max_vals=10, footer=True): """ a short repr displaying only max_vals and an optional (but default footer) """ num = max_vals // 2 head = self[:num]._get_repr(length=False, foo...
return the base repr for the categories def _repr_categories(self): """ return the base repr for the categories """ max_categories = (10 if get_option("display.max_categories") == 0 else get_option("display.max_categories")) from pandas.io.formats impor...
Returns a string representation of the footer. def _repr_categories_info(self): """ Returns a string representation of the footer. """ category_strs = self._repr_categories() dtype = getattr(self.categories, 'dtype_str', str(self.categories.dtype)) ...
return an indexer coerced to the codes dtype def _maybe_coerce_indexer(self, indexer): """ return an indexer coerced to the codes dtype """ if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i': indexer = indexer.astype(self._codes.dtype) return indexer
Compute the inverse of a categorical, returning a dict of categories -> indexers. *This is an internal function* Returns ------- dict of categories -> indexers Example ------- In [1]: c = pd.Categorical(list('aabca')) In [2]: c Out[2]: ...
The minimum value of the object. Only ordered `Categoricals` have a minimum! Raises ------ TypeError If the `Categorical` is not `ordered`. Returns ------- min : the minimum of this `Categorical` def min(self, numeric_only=None, **kwargs): ...
Returns the mode(s) of the Categorical. Always returns `Categorical` even if only one value. Parameters ---------- dropna : bool, default True Don't consider counts of NaN/NaT. .. versionadded:: 0.24.0 Returns ------- modes : `Categoric...
Return the ``Categorical`` which ``categories`` and ``codes`` are unique. Unused categories are NOT returned. - unordered category: values and categories are sorted by appearance order. - ordered category: values are sorted by appearance order, categories keeps existing orde...
Returns True if categorical arrays are equal. Parameters ---------- other : `Categorical` Returns ------- bool def equals(self, other): """ Returns True if categorical arrays are equal. Parameters ---------- other : `Categorical...
Returns True if categoricals are the same dtype same categories, and same ordered Parameters ---------- other : Categorical Returns ------- bool def is_dtype_equal(self, other): """ Returns True if categoricals are the same dtype sam...
Describes this Categorical Returns ------- description: `DataFrame` A dataframe with frequency and counts by category. def describe(self): """ Describes this Categorical Returns ------- description: `DataFrame` A dataframe with f...
Check whether `values` are contained in Categorical. Return a boolean NumPy Array showing whether each element in the Categorical matches an element in the passed sequence of `values` exactly. Parameters ---------- values : set or list-like The sequence of v...
Convert argument to timedelta. Timedeltas are absolute differences in times, expressed in difference units (e.g. days, hours, minutes, seconds). This method converts an argument from a recognized timedelta format / value into a Timedelta type. Parameters ---------- arg : str, timedelta, li...
Convert string 'r' to a timedelta object. def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'): """Convert string 'r' to a timedelta object.""" try: result = Timedelta(r, unit) if not box: # explicitly view as timedelta64 for case when result is pd.NaT ...
Convert a list of objects to a timedelta index object. def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None): """Convert a list of objects to a timedelta index object.""" if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'): # This is needed only to ensure that in the ca...
Generates a sequence of dates corresponding to the specified time offset. Similar to dateutil.rrule except uses pandas DateOffset objects to represent time increments. Parameters ---------- start : datetime (default None) end : datetime (default None) periods : int, (default None) offse...
Vectorized apply of DateOffset to DatetimeIndex, raises NotImplentedError for offsets without a vectorized implementation. Parameters ---------- i : DatetimeIndex Returns ------- y : DatetimeIndex def apply_index(self, i): """ Vectorized...
Roll provided date backward to next offset only if not on offset. def rollback(self, dt): """ Roll provided date backward to next offset only if not on offset. """ dt = as_timestamp(dt) if not self.onOffset(dt): dt = dt - self.__class__(1, normalize=self.normalize, *...
Roll provided date forward to next offset only if not on offset. def rollforward(self, dt): """ Roll provided date forward to next offset only if not on offset. """ dt = as_timestamp(dt) if not self.onOffset(dt): dt = dt + self.__class__(1, normalize=self.normalize, ...
Used for moving to next business day. def next_bday(self): """ Used for moving to next business day. """ if self.n >= 0: nb_offset = 1 else: nb_offset = -1 if self._prefix.startswith('C'): # CustomBusinessHour return Custom...
If n is positive, return tomorrow's business day opening time. Otherwise yesterday's business day's opening time. Opening time always locates on BusinessDay. Otherwise, closing time may not if business hour extends over midnight. def _next_opening_time(self, other): """ If n is...
Return business hours in a day by seconds. def _get_business_hours_by_sec(self): """ Return business hours in a day by seconds. """ if self._get_daytime_flag: # create dummy datetime to calculate businesshours in a day dtstart = datetime(2014, 4, 1, self.start.ho...
Roll provided date backward to next offset only if not on offset. def rollback(self, dt): """ Roll provided date backward to next offset only if not on offset. """ if not self.onOffset(dt): businesshours = self._get_business_hours_by_sec if self.n >= 0: ...
Roll provided date forward to next offset only if not on offset. def rollforward(self, dt): """ Roll provided date forward to next offset only if not on offset. """ if not self.onOffset(dt): if self.n >= 0: return self._next_opening_time(dt) else:...
Slight speedups using calculated values. def _onOffset(self, dt, businesshours): """ Slight speedups using calculated values. """ # if self.normalize and not _is_normalized(dt): # return False # Valid BH can be on the different BusinessDay during midnight # D...
Define default roll function to be called in apply method. def cbday_roll(self): """ Define default roll function to be called in apply method. """ cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds) if self._prefix.endswith('S'): # MonthBegin ...
Define default roll function to be called in apply method. def month_roll(self): """ Define default roll function to be called in apply method. """ if self._prefix.endswith('S'): # MonthBegin roll_func = self.m_offset.rollback else: # MonthEnd...
Add days portion of offset to DatetimeIndex i. Parameters ---------- i : DatetimeIndex roll : ndarray[int64_t] Returns ------- result : DatetimeIndex def _apply_index_days(self, i, roll): """ Add days portion of offset to DatetimeIndex i. ...
Add self to the given DatetimeIndex, specialized for case where self.weekday is non-null. Parameters ---------- dtindex : DatetimeIndex Returns ------- result : DatetimeIndex def _end_apply_index(self, dtindex): """ Add self to the given Datetim...
Find the day in the same month as other that has the same weekday as self.weekday and is the self.week'th such day in the month. Parameters ---------- other : datetime Returns ------- day : int def _get_offset_day(self, other): """ Find the day ...
Find the day in the same month as other that has the same weekday as self.weekday and is the last such day in the month. Parameters ---------- other: datetime Returns ------- day: int def _get_offset_day(self, other): """ Find the day in the sam...
Roll `other` back to the most recent date that was on a fiscal year end. Return the date of that year-end, the number of full quarters elapsed between that year-end and other, and the remaining Timedelta since the most recent quarter-end. Parameters ---------- o...
Concatenate pandas objects along a particular axis with optional set logic along the other axes. Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on the passed axis number. Parameters ---------- objs : ...
Return index to be used along concatenation axis. def _get_concat_axis(self): """ Return index to be used along concatenation axis. """ if self._is_series: if self.axis == 0: indexes = [x.index for x in self.objs] elif self.ignore_index: ...
Compute the vectorized membership of ``x in y`` if possible, otherwise use Python. def _in(x, y): """Compute the vectorized membership of ``x in y`` if possible, otherwise use Python. """ try: return x.isin(y) except AttributeError: if is_list_like(x): try: ...
Compute the vectorized membership of ``x not in y`` if possible, otherwise use Python. def _not_in(x, y): """Compute the vectorized membership of ``x not in y`` if possible, otherwise use Python. """ try: return ~x.isin(y) except AttributeError: if is_list_like(x): t...
Cast an expression inplace. Parameters ---------- terms : Op The expression that should cast. acceptable_dtypes : list of acceptable numpy.dtype Will not cast if term's dtype in this list. .. versionadded:: 0.19.0 dtype : str or numpy.dtype The dtype to cast to. d...
search order for local (i.e., @variable) variables: scope, key_variable [('locals', 'local_name'), ('globals', 'local_name'), ('locals', 'key'), ('globals', 'key')] def update(self, value): """ search order for local (i.e., @variable) variables: scop...
Evaluate a binary operation *before* being passed to the engine. Parameters ---------- env : Scope engine : str parser : str term_type : type eval_in_python : list Returns ------- term_type The "pre-evaluated" expression as an...
Convert datetimes to a comparable value in an expression. def convert_values(self): """Convert datetimes to a comparable value in an expression. """ def stringify(value): if self.encoding is not None: encoder = partial(pprint_thing_encoded, ...
Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed. Parameters ---------- index : array-like, Series, or list of arrays/Series Values to group by in the rows. c...
Calculate table chape considering index levels. def _shape(self, df): """ Calculate table chape considering index levels. """ row, col = df.shape return row + df.columns.nlevels, col + df.index.nlevels
Calculate appropriate figure size based on left and right data. def _get_cells(self, left, right, vertical): """ Calculate appropriate figure size based on left and right data. """ if vertical: # calculate required number of cells vcells = max(sum(self._shape(l)...
Plot left / right DataFrames in specified layout. Parameters ---------- left : list of DataFrames before operation is applied right : DataFrame of operation result labels : list of str to be drawn as titles of left DataFrames vertical : bool If True, use vert...
Convert each input to appropriate for table outplot def _conv(self, data): """Convert each input to appropriate for table outplot""" if isinstance(data, pd.Series): if data.name is None: data = data.to_frame(name='') else: data = data.to_frame() ...
Bin values into discrete intervals. Use `cut` when you need to segment and sort data values into bins. This function is also useful for going from a continuous variable to a categorical variable. For example, `cut` could convert ages to groups of age ranges. Supports binning into an equal number of bin...
Quantile-based discretization function. Discretize variable into equal-sized buckets based on rank or based on sample quantiles. For example 1000 values for 10 quantiles would produce a Categorical object indicating quantile membership for each data point. Parameters ---------- x : 1d ndarray o...
if the passed data is of datetime/timedelta type, this method converts it to numeric so that cut method can handle it def _coerce_to_type(x): """ if the passed data is of datetime/timedelta type, this method converts it to numeric so that cut method can handle it """ dtype = None i...
if the passed bin is of datetime/timedelta type, this method converts it to integer Parameters ---------- bins : list-like of bins dtype : dtype of data Raises ------ ValueError if bins are not of a compat dtype to dtype def _convert_bin_to_numeric_type(bins, dtype): """ if th...
Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is datelike Parameters ---------- bins : list-like of bins dtype : dtype of data Returns ------- bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is datelike def _convert_bin_to_dateli...
based on the dtype, return our labels def _format_labels(bins, precision, right=True, include_lowest=False, dtype=None): """ based on the dtype, return our labels """ closed = 'right' if right else 'left' if is_datetime64tz_dtype(dtype): formatter = partial(Timestamp, tz=dtype....
handles preprocessing for cut where we convert passed input to array, strip the index information and store it separately def _preprocess_for_cut(x): """ handles preprocessing for cut where we convert passed input to array, strip the index information and store it separately """ x_is_se...
handles post processing for the cut method where we combine the index information if the originally passed datatype was a series def _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype): """ handles post processing for the cut method where we com...
Round the fractional part of the given number def _round_frac(x, precision): """ Round the fractional part of the given number """ if not np.isfinite(x) or x == 0: return x else: frac, whole = np.modf(x) if whole == 0: digits = -int(np.floor(np.log10(abs(frac))))...
Infer an appropriate precision for _round_frac def _infer_precision(base_precision, bins): """Infer an appropriate precision for _round_frac """ for precision in range(base_precision, 20): levels = [_round_frac(b, precision) for b in bins] if algos.unique(levels).size == bins.size: ...
Try to find the most capable encoding supported by the console. slightly modified from the way IPython handles the same issue. def detect_console_encoding(): """ Try to find the most capable encoding supported by the console. slightly modified from the way IPython handles the same issue. """ gl...
Checks whether 'args' has length of at most 'compat_args'. Raises a TypeError if that is not the case, similar to in Python when a function is called with too many arguments. def _check_arg_length(fname, args, max_fname_arg_count, compat_args): """ Checks whether 'args' has length of at most 'compat_ar...
Check that the keys in `arg_val_dict` are mapped to their default values as specified in `compat_args`. Note that this function is to be called only when it has been checked that arg_val_dict.keys() is a subset of compat_args def _check_for_default_values(fname, arg_val_dict, compat_args): """ Che...
Checks whether the length of the `*args` argument passed into a function has at most `len(compat_args)` arguments and whether or not all of these elements in `args` are set to their default values. fname: str The name of the function being passed the `*args` parameter args: tuple The `...
Checks whether 'kwargs' contains any keys that are not in 'compat_args' and raises a TypeError if there is one. def _check_for_invalid_keys(fname, kwargs, compat_args): """ Checks whether 'kwargs' contains any keys that are not in 'compat_args' and raises a TypeError if there is one. """ # set...
Checks whether parameters passed to the **kwargs argument in a function `fname` are valid parameters as specified in `*compat_args` and whether or not they are set to their default values. Parameters ---------- fname: str The name of the function being passed the `**kwargs` parameter k...
Checks whether parameters passed to the *args and **kwargs argument in a function `fname` are valid parameters as specified in `*compat_args` and whether or not they are set to their default values. Parameters ---------- fname: str The name of the function being passed the `**kwargs` parame...
Ensures that argument passed in arg_name is of type bool. def validate_bool_kwarg(value, arg_name): """ Ensures that argument passed in arg_name is of type bool. """ if not (is_bool(value) or value is None): raise ValueError('For argument "{arg}" expected type bool, received ' ...
Argument handler for mixed index, columns / axis functions In an attempt to handle both `.method(index, columns)`, and `.method(arg, axis=.)`, we have to do some bad things to argument parsing. This translates all arguments to `{index=., columns=.}` style. Parameters ---------- data : DataFram...
Validate the keyword arguments to 'fillna'. This checks that exactly one of 'value' and 'method' is specified. If 'method' is specified, this validates that it's a valid method. Parameters ---------- value, method : object The 'value' and 'method' keyword arguments for 'fillna'. valida...
Potentially we might have a deprecation warning, show it but call the appropriate methods anyhow. def _maybe_process_deprecations(r, how=None, fill_method=None, limit=None): """ Potentially we might have a deprecation warning, show it but call the appropriate methods anyhow. """ if how is not ...
Create a TimeGrouper and return our resampler. def resample(obj, kind=None, **kwds): """ Create a TimeGrouper and return our resampler. """ tg = TimeGrouper(**kwds) return tg._get_resampler(obj, kind=kind)
Return our appropriate resampler when grouping as well. def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None, limit=None, kind=None, **kwargs): """ Return our appropriate resampler when grouping as well. """ # .resample uses 'on' similar to how .group...
Adjust the `first` Timestamp to the preceeding Timestamp that resides on the provided offset. Adjust the `last` Timestamp to the following Timestamp that resides on the provided offset. Input Timestamps that already reside on the offset will be adjusted depending on the type of offset and the `closed` p...
Adjust the provided `first` and `last` Periods to the respective Period of the given offset that encompasses them. Parameters ---------- first : pd.Period The beginning Period of the range to be adjusted. last : pd.Period The ending Period of the range to be adjusted. offset : p...
Utility frequency conversion method for Series/DataFrame. def asfreq(obj, freq, method=None, how=None, normalize=False, fill_value=None): """ Utility frequency conversion method for Series/DataFrame. """ if isinstance(obj.index, PeriodIndex): if method is not None: raise NotImplemen...
Is the resampling from a DataFrame column or MultiIndex level. def _from_selection(self): """ Is the resampling from a DataFrame column or MultiIndex level. """ # upsampling and PeriodIndex resampling do not work # with selection, this state used to catch and raise an error ...
Setup our binners. Cache these as we are an immutable object def _set_binner(self): """ Setup our binners. Cache these as we are an immutable object """ if self.binner is None: self.binner, self.grouper = self._get_binner()
Create the BinGrouper, assume that self.set_grouper(obj) has already been called. def _get_binner(self): """ Create the BinGrouper, assume that self.set_grouper(obj) has already been called. """ binner, bins, binlabels = self._get_binner_for_time() bin_grouper =...
Call function producing a like-indexed Series on each group and return a Series with the transformed values. Parameters ---------- arg : function To apply to each group. Should return a Series with the same index. Returns ------- transformed : Series...
Sub-classes to define. Return a sliced object. Parameters ---------- key : string / 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-...
Re-evaluate the obj with a groupby aggregation. def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs): """ Re-evaluate the obj with a groupby aggregation. """ if grouper is None: self._set_binner() grouper = self.grouper obj = self._selec...
If loffset is set, offset the result index. This is NOT an idempotent routine, it will be applied exactly once to the result. Parameters ---------- result : Series or DataFrame the result of resample def _apply_loffset(self, result): """ If loffset ...
Return the correct class for resampling with groupby. def _get_resampler_for_grouping(self, groupby, **kwargs): """ Return the correct class for resampling with groupby. """ return self._resampler_for_grouping(self, groupby=groupby, **kwargs)
Potentially wrap any results. def _wrap_result(self, result): """ Potentially wrap any results. """ if isinstance(result, ABCSeries) and self._selection is not None: result.name = self._selection if isinstance(result, ABCSeries) and result.empty: obj = s...
Interpolate values according to different methods. .. versionadded:: 0.18.1 def interpolate(self, method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None, **kwargs): """ Interpolate values according t...
Compute standard deviation of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 Degrees of freedom. def std(self, ddof=1, *args, **kwargs): """ Compute standard deviation of groups, excluding missing values. Parameters ...
Compute variance of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 degrees of freedom def var(self, ddof=1, *args, **kwargs): """ Compute variance of groups, excluding missing values. Parameters ---------- ...
Dispatch to _upsample; we are stripping all of the _upsample kwargs and performing the original function call on the grouped object. def _apply(self, f, grouper=None, *args, **kwargs): """ Dispatch to _upsample; we are stripping all of the _upsample kwargs and performing the original fu...
Downsample the cython defined function. Parameters ---------- how : string / cython mapped function **kwargs : kw args passed to how function def _downsample(self, how, **kwargs): """ Downsample the cython defined function. Parameters ---------- ...
Adjust our binner when upsampling. The range of a new index should not be outside specified range def _adjust_binner_for_upsample(self, binner): """ Adjust our binner when upsampling. The range of a new index should not be outside specified range """ if self.closed == ...
Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill', 'asfreq'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value : scalar, default None Value to use for missing values Se...
Downsample the cython defined function. Parameters ---------- how : string / cython mapped function **kwargs : kw args passed to how function def _downsample(self, how, **kwargs): """ Downsample the cython defined function. Parameters ---------- ...
Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value : scalar, default None Value to use for missing values See Also ...
Return my resampler or raise if we have an invalid axis. Parameters ---------- obj : input object kind : string, optional 'period','timestamp','timedelta' are valid Returns ------- a Resampler Raises ------ TypeError if incom...
Parameters ---------- arrays : generator num_items : int Should be the same as CPython's tupleobject.c def _combine_hash_arrays(arrays, num_items): """ Parameters ---------- arrays : generator num_items : int Should be the same as CPython's tupleobject.c """ try: ...
Return a data hash of the Index/Series/DataFrame .. versionadded:: 0.19.2 Parameters ---------- index : boolean, default True include the index in the hash (if Series/DataFrame) encoding : string, default 'utf8' encoding for data & key when strings hash_key : string key to enco...
Hash an MultiIndex / list-of-tuples efficiently .. versionadded:: 0.20.0 Parameters ---------- vals : MultiIndex, list-of-tuples, or single tuple encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ------- ndarray of hashed value...
Hash a single tuple efficiently Parameters ---------- val : single tuple encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ------- hash def hash_tuple(val, encoding='utf8', hash_key=None): """ Hash a single tuple efficientl...
Hash a Categorical by hashing its categories, and then mapping the codes to the hashes Parameters ---------- c : Categorical encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ------- ndarray of hashed values array, same size as ...
Given a 1d array, return an array of deterministic integers. .. versionadded:: 0.19.2 Parameters ---------- vals : ndarray, Categorical encoding : string, default 'utf8' encoding for data & key when strings hash_key : string key to encode, default to _default_hash_key categorize : ...
Hash scalar value Returns ------- 1d uint64 numpy array of hash value, of length 1 def _hash_scalar(val, encoding='utf8', hash_key=None): """ Hash scalar value Returns ------- 1d uint64 numpy array of hash value, of length 1 """ if isna(val): # this is to be consisten...
Make sure the provided value for --single is a path to an existing .rst/.ipynb file, or a pandas object that can be imported. For example, categorial.rst or pandas.DataFrame.head. For the latter, return the corresponding file path (e.g. reference/api/pandas.DataFrame.head.rst). def _pr...