INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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): """ 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 `Ca...
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...
def mode(self, dropna=True): """ 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 R...
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...
def unique(self): """ 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, ca...
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 ------- bool """ if self.is_dtype_equal(other): if self.categories.equals(other.categories): ...
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 same categories, and same ordered Parameters ---------- other : Categorical Returns ------- bool """ try: return hash(self.dtype) ...
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 frequency and counts by category. """ counts = self.value_counts(dropna=False) freqs = counts / float(counts.sum()) from pand...
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...
def isin(self, values): """ 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 : se...
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...
def to_timedelta(arg, unit='ns', box=True, errors='raise'): """ 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 Tim...
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 result = result.asm8.view('timedelta...
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 case where we end up # returning arg (errors == "...
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...
def generate_range(start=None, end=None, periods=None, offset=BDay()): """ 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 ...
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 apply of DateOffset to DatetimeIndex, raises NotImplentedError for offsets without a vectorized implementation. Parameters ---------- i : DatetimeIndex Returns ------- y : DatetimeIndex """...
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, **self.kwds) return dt
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, **self.kwds) return dt
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 CustomBusinessDay(n=nb_offset, ...
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 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. ...
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.hour, self.start.minute) until = d...
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: dt = self._prev_opening_time( dt) + time...
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: return self._prev_opening_time(dt) return...
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 # Distinguish by the time spent from previous...
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 roll_func = cbday.rollforward else: ...
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 roll_func = self.m_offset.rollforward r...
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. Parameters ---------- i : DatetimeIndex roll : ndarray[int64_t] Returns ------- result : DatetimeIndex """ nanos = (roll % 2) * Timedelta(day...
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 DatetimeIndex, specialized for case where self.weekday is non-null. Parameters ---------- dtindex : DatetimeIndex Returns ------- result : DatetimeIndex """ off = dtin...
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 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 """ ...
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 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 """ dim ...
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...
def _rollback_to_year(self, other): """ 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 quart...
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 : ...
def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=None, copy=True): """ Concatenate pandas objects along a particular axis with optional set logic along the other axes. Can also add a layer o...
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: idx = ibase.default_index(len(self.objs)) ...
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): try: return ~y.isin(x) except AttributeError: pas...
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: return y.isin(x) except AttributeError: pass ...
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.
def _cast_inplace(terms, acceptable_dtypes, dtype): """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 ...
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: scope, key_variable [('locals', 'local_name'), ('globals', 'local_name'), ('locals', 'key'), ('globals', 'key')] """ key = self.name # if it's a variable ...
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...
def evaluate(self, env, engine, parser, term_type, eval_in_python): """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 ...
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, encoding=self.encoding) else: ...
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...
def crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False): """ Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an arr...
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)[0] for l in left), self._shape(right)[0...
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
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() data = data.fillna('NaN') return data
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...
def plot(self, left, right, labels=None, vertical=True): """ 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 ti...
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...
def cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise'): """ 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 ...
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...
def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'): """ 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 qua...
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 if is_datetime64tz_dtype(x): dtype = x.dtype elif is_datetime64_dtype(x): x = to_datetime(x) dtype =...
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 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 ""...
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_datelike_type(bins, dtype): """ 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...
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.tz) adjust = lambda x: x - Time...
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_series = isinstance(x, Series) series_index = None name = None if x_is_series: series_index = x.index na...
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 combine the index information if the originally passed datatype was a series """ if x_is_series: fac = Series(fac, index=...
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)))) - 1 + precision else: digi...
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: return precision return base_precision
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. """ global _initial_defencoding encoding = None try: encoding = sys.stdout.encoding or sys.stdin.encoding except (Att...
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_args'. Raises a TypeError if that is not the case, similar to in Python when a function is called with too many arguments. """ if max_fname_arg_count < 0: raise ...
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): """ 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 ...
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 `...
def validate_args(fname, args, max_fname_arg_count, compat_args): """ 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 ...
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(dict) --> set of the dictionary's keys diff = set(kwargs) - set(compat_args) if diff: bad_arg = lis...
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...
def validate_kwargs(fname, kwargs, compat_args): """ 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...
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...
def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_args): """ 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 ...
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...
def validate_axis_style_args(data, args, kwargs, arg_name, method_name): """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 ...
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...
def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True): """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 :...
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 ' 'type {typ}.'.format(arg=arg_name, ...
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 None: # .resample(..., how='sum') if isinstance(how, str): method = "{0}()...
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 .groupby uses 'key' kwargs['key'] = kwargs.pop('on', None) ...
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...
def _get_timestamp_range_edges(first, last, offset, closed='left', base=0): """ 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 resi...
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...
def _get_period_range_edges(first, last, offset, closed='left', base=0): """ 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. l...
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 NotImplementedError("'method' argument is not supported") if ...
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 return (self.groupby is not None and (self.g...
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 = BinGrouper(bins, binlabels, indexer=self.groupby.indexer) return binner, bin_group...
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...
def transform(self, arg, *args, **kwargs): """ 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...
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-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 ...
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._selected_obj grouped = groupby(obj, by=None, ...
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 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 """ ...
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 = self.obj if isinstan...
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 to different methods. .. versionadded:: 0.18.1 """ result = se...
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 ---------- ddof : integer, default 1 Degrees of freedom. """ nv.validate_resampler_func('std', args, kwargs) return self._do...
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 ---------- ddof : integer, default 1 degrees of freedom """ nv.validate_resampler_func('var', args, kwargs) return self._downsample('v...
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 function call on the grouped object. """ def func(x): x = self._shallow_copy(x, groupby=self.groupby) ...
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 ---------- how : string / cython mapped function **kwargs : kw args passed to how function """ self._set_binner() how = self._is_cython_func(how) or how ...
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 == 'right': binner = binner[1:] else: binner = binner[:-1] return binne...
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...
def _upsample(self, method, limit=None, fill_value=None): """ Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill', 'asfreq'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value ...
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 ---------- how : string / cython mapped function **kwargs : kw args passed to how function """ # we may need to actually resample as if we are timestamps ...
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 ...
def _upsample(self, method, limit=None, fill_value=None): """ Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value : scalar, ...
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...
def _get_resampler(self, obj, kind=None): """ 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 Resam...
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: first = next(arrays) except StopIteration: return np.array([], dtype=np.uint64) arrays = itertools.ch...
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...
def hash_pandas_object(obj, index=True, encoding='utf8', hash_key=None, categorize=True): """ 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/Da...
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...
def hash_tuples(vals, encoding='utf8', hash_key=None): """ 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 _de...
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 efficiently Parameters ---------- val : single tuple encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ------- hash """ hashes = (_hash_sc...
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 ...
def _hash_categorical(c, encoding, hash_key): """ 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 ...
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 : ...
def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): """ 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 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 consistent with the _hash_categorical implementation return np.array([np.iinfo(np.uint64).max], dt...
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 _process_single_doc(self, single_doc): """ 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 ...
Execute a command as a OS terminal. Parameters ---------- *args : list of str Command and parameters to be executed Examples -------- >>> DocBuilder()._run_os('python', '--version')
def _run_os(*args): """ Execute a command as a OS terminal. Parameters ---------- *args : list of str Command and parameters to be executed Examples -------- >>> DocBuilder()._run_os('python', '--version') """ subprocess.check...
Call sphinx to build documentation. Attribute `num_jobs` from the class is used. Parameters ---------- kind : {'html', 'latex'} Examples -------- >>> DocBuilder(num_jobs=4)._sphinx_build('html')
def _sphinx_build(self, kind): """ Call sphinx to build documentation. Attribute `num_jobs` from the class is used. Parameters ---------- kind : {'html', 'latex'} Examples -------- >>> DocBuilder(num_jobs=4)._sphinx_build('html') """ ...
Open a browser tab showing single
def _open_browser(self, single_doc_html): """ Open a browser tab showing single """ url = os.path.join('file://', DOC_PATH, 'build', 'html', single_doc_html) webbrowser.open(url, new=2)
Open the rst file `page` and extract its title.
def _get_page_title(self, page): """ Open the rst file `page` and extract its title. """ fname = os.path.join(SOURCE_PATH, '{}.rst'.format(page)) option_parser = docutils.frontend.OptionParser( components=(docutils.parsers.rst.Parser,)) doc = docutils.utils.ne...
Create in the build directory an html file with a redirect, for every row in REDIRECTS_FILE.
def _add_redirects(self): """ Create in the build directory an html file with a redirect, for every row in REDIRECTS_FILE. """ html = ''' <html> <head> <meta http-equiv="refresh" content="0;URL={url}"/> </head> <body> ...
Build HTML documentation.
def html(self): """ Build HTML documentation. """ ret_code = self._sphinx_build('html') zip_fname = os.path.join(BUILD_PATH, 'html', 'pandas.zip') if os.path.exists(zip_fname): os.remove(zip_fname) if self.single_doc_html is not None: self...
Build PDF documentation.
def latex(self, force=False): """ Build PDF documentation. """ if sys.platform == 'win32': sys.stderr.write('latex build has not been tested on windows\n') else: ret_code = self._sphinx_build('latex') os.chdir(os.path.join(BUILD_PATH, 'latex'))...