Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _repr_categories(self):
max_categories = (10 if get_option("display.max_categories") == 0 else
get_option("display.max_categories"))
from pandas.io.formats import format as fmt
if len(self.categories) > max_categ... | [
"\n return the base repr for the categories\n "
] |
Please provide a description of the function:def _repr_categories_info(self):
category_strs = self._repr_categories()
dtype = getattr(self.categories, 'dtype_str',
str(self.categories.dtype))
levheader = "Categories ({length}, {dtype}): ".format(
le... | [
"\n Returns a string representation of the footer.\n "
] |
Please provide a description of the function:def _maybe_coerce_indexer(self, indexer):
if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i':
indexer = indexer.astype(self._codes.dtype)
return indexer | [
"\n return an indexer coerced to the codes dtype\n "
] |
Please provide a description of the function:def _reverse_indexer(self):
categories = self.categories
r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),
categories.size)
counts = counts.cumsum()
result = (r[start:end... | [
"\n Compute the inverse of a categorical, returning\n a dict of categories -> indexers.\n\n *This is an internal function*\n\n Returns\n -------\n dict of categories -> indexers\n\n Example\n -------\n In [1]: c = pd.Categorical(list('aabca'))\n\n ... |
Please provide a description of the function:def min(self, numeric_only=None, **kwargs):
self.check_for_ordered('min')
if numeric_only:
good = self._codes != -1
pointer = self._codes[good].min(**kwargs)
else:
pointer = self._codes.min(**kwargs)
... | [
"\n The minimum value of the object.\n\n Only ordered `Categoricals` have a minimum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n min : the minimum of this `Categorical`\n "
] |
Please provide a description of the function:def mode(self, dropna=True):
import pandas._libs.hashtable as htable
codes = self._codes
if dropna:
good = self._codes != -1
codes = self._codes[good]
codes = sorted(htable.mode_int64(ensure_int64(codes), drop... | [
"\n Returns the mode(s) of the Categorical.\n\n Always returns `Categorical` even if only one value.\n\n Parameters\n ----------\n dropna : bool, default True\n Don't consider counts of NaN/NaT.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------... |
Please provide a description of the function:def unique(self):
# unlike np.unique, unique1d does not sort
unique_codes = unique1d(self.codes)
cat = self.copy()
# keep nan in codes
cat._codes = unique_codes
# exclude nan from indexer for categories
take... | [
"\n Return the ``Categorical`` which ``categories`` and ``codes`` are\n unique. Unused categories are NOT returned.\n\n - unordered category: values and categories are sorted by appearance\n order.\n - ordered category: values are sorted by appearance order, categories\n ... |
Please provide a description of the function:def equals(self, other):
if self.is_dtype_equal(other):
if self.categories.equals(other.categories):
# fastpath to avoid re-coding
other_codes = other._codes
else:
other_codes = _recode_... | [
"\n Returns True if categorical arrays are equal.\n\n Parameters\n ----------\n other : `Categorical`\n\n Returns\n -------\n bool\n "
] |
Please provide a description of the function:def is_dtype_equal(self, other):
try:
return hash(self.dtype) == hash(other.dtype)
except (AttributeError, TypeError):
return False | [
"\n Returns True if categoricals are the same dtype\n same categories, and same ordered\n\n Parameters\n ----------\n other : Categorical\n\n Returns\n -------\n bool\n "
] |
Please provide a description of the function:def describe(self):
counts = self.value_counts(dropna=False)
freqs = counts / float(counts.sum())
from pandas.core.reshape.concat import concat
result = concat([counts, freqs], axis=1)
result.columns = ['counts', 'freqs']
... | [
"\n Describes this Categorical\n\n Returns\n -------\n description: `DataFrame`\n A dataframe with frequency and counts by category.\n "
] |
Please provide a description of the function:def isin(self, values):
from pandas.core.internals.construction import sanitize_array
if not is_list_like(values):
raise TypeError("only list-like objects are allowed to be passed"
" to isin(), you passed a [{v... | [
"\n Check whether `values` are contained in Categorical.\n\n Return a boolean NumPy Array showing whether each element in\n the Categorical matches an element in the passed sequence of\n `values` exactly.\n\n Parameters\n ----------\n values : set or list-like\n ... |
Please provide a description of the function:def to_timedelta(arg, unit='ns', box=True, errors='raise'):
unit = parse_timedelta_unit(unit)
if errors not in ('ignore', 'raise', 'coerce'):
raise ValueError("errors must be one of 'ignore', "
"'raise', or 'coerce'}")
if u... | [
"\n Convert argument to timedelta.\n\n Timedeltas are absolute differences in times, expressed in difference\n units (e.g. days, hours, minutes, seconds). This method converts\n an argument from a recognized timedelta format / value into\n a Timedelta type.\n\n Parameters\n ----------\n arg ... |
Please provide a description of the function:def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'):
try:
result = Timedelta(r, unit)
if not box:
# explicitly view as timedelta64 for case when result is pd.NaT
result = result.asm8.view('timedelta64... | [
"Convert string 'r' to a timedelta object."
] |
Please provide a description of the function:def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None):
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 == "ignore"), and w... | [
"Convert a list of objects to a timedelta index object."
] |
Please provide a description of the function:def generate_range(start=None, end=None, periods=None, offset=BDay()):
from pandas.tseries.frequencies import to_offset
offset = to_offset(offset)
start = to_datetime(start)
end = to_datetime(end)
if start and not offset.onOffset(start):
st... | [
"\n Generates a sequence of dates corresponding to the specified time\n offset. Similar to dateutil.rrule except uses pandas DateOffset\n objects to represent time increments.\n\n Parameters\n ----------\n start : datetime (default None)\n end : datetime (default None)\n periods : int, (defa... |
Please provide a description of the function:def apply_index(self, i):
if type(self) is not DateOffset:
raise NotImplementedError("DateOffset subclass {name} "
"does not have a vectorized "
"implementation".format(... | [
"\n Vectorized apply of DateOffset to DatetimeIndex,\n raises NotImplentedError for offsets without a\n vectorized implementation.\n\n Parameters\n ----------\n i : DatetimeIndex\n\n Returns\n -------\n y : DatetimeIndex\n "
] |
Please provide a description of the function:def rollback(self, dt):
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt - self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | [
"\n Roll provided date backward to next offset only if not on offset.\n "
] |
Please provide a description of the function:def rollforward(self, dt):
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | [
"\n Roll provided date forward to next offset only if not on offset.\n "
] |
Please provide a description of the function:def next_bday(self):
if self.n >= 0:
nb_offset = 1
else:
nb_offset = -1
if self._prefix.startswith('C'):
# CustomBusinessHour
return CustomBusinessDay(n=nb_offset,
... | [
"\n Used for moving to next business day.\n "
] |
Please provide a description of the function:def _next_opening_time(self, other):
if not self.next_bday.onOffset(other):
other = other + self.next_bday
else:
if self.n >= 0 and self.start < other.time():
other = other + self.next_bday
elif sel... | [
"\n If n is positive, return tomorrow's business day opening time.\n Otherwise yesterday's business day's opening time.\n\n Opening time always locates on BusinessDay.\n Otherwise, closing time may not if business hour extends over midnight.\n "
] |
Please provide a description of the function:def _get_business_hours_by_sec(self):
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 = datetime(2014, 4, 1, s... | [
"\n Return business hours in a day by seconds.\n "
] |
Please provide a description of the function:def rollback(self, dt):
if not self.onOffset(dt):
businesshours = self._get_business_hours_by_sec
if self.n >= 0:
dt = self._prev_opening_time(
dt) + timedelta(seconds=businesshours)
els... | [
"\n Roll provided date backward to next offset only if not on offset.\n "
] |
Please provide a description of the function:def rollforward(self, dt):
if not self.onOffset(dt):
if self.n >= 0:
return self._next_opening_time(dt)
else:
return self._prev_opening_time(dt)
return dt | [
"\n Roll provided date forward to next offset only if not on offset.\n "
] |
Please provide a description of the function:def _onOffset(self, dt, businesshours):
# 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 opening time
... | [
"\n Slight speedups using calculated values.\n "
] |
Please provide a description of the function:def cbday_roll(self):
cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)
if self._prefix.endswith('S'):
# MonthBegin
roll_func = cbday.rollforward
else:
# MonthEnd
roll_func = cb... | [
"\n Define default roll function to be called in apply method.\n "
] |
Please provide a description of the function:def month_roll(self):
if self._prefix.endswith('S'):
# MonthBegin
roll_func = self.m_offset.rollback
else:
# MonthEnd
roll_func = self.m_offset.rollforward
return roll_func | [
"\n Define default roll function to be called in apply method.\n "
] |
Please provide a description of the function:def _apply_index_days(self, i, roll):
nanos = (roll % 2) * Timedelta(days=self.day_of_month - 1).value
return i + nanos.astype('timedelta64[ns]') | [
"\n Add days portion of offset to DatetimeIndex i.\n\n Parameters\n ----------\n i : DatetimeIndex\n roll : ndarray[int64_t]\n\n Returns\n -------\n result : DatetimeIndex\n "
] |
Please provide a description of the function:def _end_apply_index(self, dtindex):
off = dtindex.to_perioddelta('D')
base, mult = libfrequencies.get_freq_code(self.freqstr)
base_period = dtindex.to_period(base)
if not isinstance(base_period._data, np.ndarray):
# unwr... | [
"\n Add self to the given DatetimeIndex, specialized for case where\n self.weekday is non-null.\n\n Parameters\n ----------\n dtindex : DatetimeIndex\n\n Returns\n -------\n result : DatetimeIndex\n "
] |
Please provide a description of the function:def _get_offset_day(self, other):
mstart = datetime(other.year, other.month, 1)
wday = mstart.weekday()
shift_days = (self.weekday - wday) % 7
return 1 + shift_days + self.week * 7 | [
"\n Find the day in the same month as other that has the same\n weekday as self.weekday and is the self.week'th such day in the month.\n\n Parameters\n ----------\n other : datetime\n\n Returns\n -------\n day : int\n "
] |
Please provide a description of the function:def _get_offset_day(self, other):
dim = ccalendar.get_days_in_month(other.year, other.month)
mend = datetime(other.year, other.month, dim)
wday = mend.weekday()
shift_days = (wday - self.weekday) % 7
return dim - shift_days | [
"\n Find the day in the same month as other that has the same\n weekday as self.weekday and is the last such day in the month.\n\n Parameters\n ----------\n other: datetime\n\n Returns\n -------\n day: int\n "
] |
Please provide a description of the function:def _rollback_to_year(self, other):
num_qtrs = 0
norm = Timestamp(other).tz_localize(None)
start = self._offset.rollback(norm)
# Note: start <= norm and self._offset.onOffset(start)
if start < norm:
# roll adjust... | [
"\n Roll `other` back to the most recent date that was on a fiscal year\n end.\n\n Return the date of that year-end, the number of full quarters\n elapsed between that year-end and other, and the remaining Timedelta\n since the most recent quarter-end.\n\n Parameters\n ... |
Please provide a description of the function: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):
op = _Concatenator(objs, axis=axis, join_axes=join_axes,
ignore... | [
"\n Concatenate pandas objects along a particular axis with optional set logic\n along the other axes.\n\n Can also add a layer of hierarchical indexing on the concatenation axis,\n which may be useful if the labels are the same (or overlapping) on\n the passed axis number.\n\n Parameters\n ---... |
Please provide a description of the function:def _get_concat_axis(self):
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))
return idx
... | [
"\n Return index to be used along concatenation axis.\n "
] |
Please provide a description of the function:def _in(x, y):
try:
return x.isin(y)
except AttributeError:
if is_list_like(x):
try:
return y.isin(x)
except AttributeError:
pass
return x in y | [
"Compute the vectorized membership of ``x in y`` if possible, otherwise\n use Python.\n "
] |
Please provide a description of the function:def _not_in(x, y):
try:
return ~x.isin(y)
except AttributeError:
if is_list_like(x):
try:
return ~y.isin(x)
except AttributeError:
pass
return x not in y | [
"Compute the vectorized membership of ``x not in y`` if possible,\n otherwise use Python.\n "
] |
Please provide a description of the function:def _cast_inplace(terms, acceptable_dtypes, dtype):
dt = np.dtype(dtype)
for term in terms:
if term.type in acceptable_dtypes:
continue
try:
new_value = term.value.astype(dt)
except AttributeError:
new... | [
"Cast an expression inplace.\n\n Parameters\n ----------\n terms : Op\n The expression that should cast.\n acceptable_dtypes : list of acceptable numpy.dtype\n Will not cast if term's dtype in this list.\n\n .. versionadded:: 0.19.0\n\n dtype : str or numpy.dtype\n The dty... |
Please provide a description of the function:def update(self, value):
key = self.name
# if it's a variable name (otherwise a constant)
if isinstance(key, str):
self.env.swapkey(self.local_name, key, new_value=value)
self.value = value | [
"\n search order for local (i.e., @variable) variables:\n\n scope, key_variable\n [('locals', 'local_name'),\n ('globals', 'local_name'),\n ('locals', 'key'),\n ('globals', 'key')]\n "
] |
Please provide a description of the function:def evaluate(self, env, engine, parser, term_type, eval_in_python):
if engine == 'python':
res = self(env)
else:
# recurse over the left/right nodes
left = self.lhs.evaluate(env, engine=engine, parser=parser,
... | [
"Evaluate a binary operation *before* being passed to the engine.\n\n Parameters\n ----------\n env : Scope\n engine : str\n parser : str\n term_type : type\n eval_in_python : list\n\n Returns\n -------\n term_type\n The \"pre-evaluate... |
Please provide a description of the function:def convert_values(self):
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded,
encoding=self.encoding)
else:
encoder = pprint_thi... | [
"Convert datetimes to a comparable value in an expression.\n "
] |
Please provide a description of the function:def crosstab(index, columns, values=None, rownames=None, colnames=None,
aggfunc=None, margins=False, margins_name='All', dropna=True,
normalize=False):
index = com.maybe_make_list(index)
columns = com.maybe_make_list(columns)
rown... | [
"\n Compute a simple cross tabulation of two (or more) factors. By default\n computes a frequency table of the factors unless an array of values and an\n aggregation function are passed.\n\n Parameters\n ----------\n index : array-like, Series, or list of arrays/Series\n Values to group by ... |
Please provide a description of the function:def _shape(self, df):
row, col = df.shape
return row + df.columns.nlevels, col + df.index.nlevels | [
"\n Calculate table chape considering index levels.\n "
] |
Please provide a description of the function:def _get_cells(self, left, right, vertical):
if vertical:
# calculate required number of cells
vcells = max(sum(self._shape(l)[0] for l in left),
self._shape(right)[0])
hcells = (max(self._shape(l... | [
"\n Calculate appropriate figure size based on left and right data.\n "
] |
Please provide a description of the function:def plot(self, left, right, labels=None, vertical=True):
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
if not isinstance(left, list):
left = [left]
left = [self._conv(l) for l in left]
rig... | [
"\n Plot left / right DataFrames in specified layout.\n\n Parameters\n ----------\n left : list of DataFrames before operation is applied\n right : DataFrame of operation result\n labels : list of str to be drawn as titles of left DataFrames\n vertical : bool\n ... |
Please provide a description of the function:def _conv(self, data):
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 | [
"Convert each input to appropriate for table outplot"
] |
Please provide a description of the function:def cut(x, bins, right=True, labels=None, retbins=False, precision=3,
include_lowest=False, duplicates='raise'):
# NOTE: this binning code is changed a bit from histogram for var(x) == 0
# for handling the cut for datetime and timedelta objects
x_is... | [
"\n Bin values into discrete intervals.\n\n Use `cut` when you need to segment and sort data values into bins. This\n function is also useful for going from a continuous variable to a\n categorical variable. For example, `cut` could convert ages to groups of\n age ranges. Supports binning into an equ... |
Please provide a description of the function:def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'):
x_is_series, series_index, name, x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
if is_integer(q):
quantiles = np.linspace(0, 1, q + 1)
else:
quantile... | [
"\n Quantile-based discretization function. Discretize variable into\n equal-sized buckets based on rank or based on sample quantiles. For example\n 1000 values for 10 quantiles would produce a Categorical object indicating\n quantile membership for each data point.\n\n Parameters\n ----------\n ... |
Please provide a description of the function:def _coerce_to_type(x):
dtype = None
if is_datetime64tz_dtype(x):
dtype = x.dtype
elif is_datetime64_dtype(x):
x = to_datetime(x)
dtype = np.dtype('datetime64[ns]')
elif is_timedelta64_dtype(x):
x = to_timedelta(x)
... | [
"\n if the passed data is of datetime/timedelta type,\n this method converts it to numeric so that cut method can\n handle it\n "
] |
Please provide a description of the function:def _convert_bin_to_numeric_type(bins, dtype):
bins_dtype = infer_dtype(bins, skipna=False)
if is_timedelta64_dtype(dtype):
if bins_dtype in ['timedelta', 'timedelta64']:
bins = to_timedelta(bins).view(np.int64)
else:
rais... | [
"\n if the passed bin is of datetime/timedelta type,\n this method converts it to integer\n\n Parameters\n ----------\n bins : list-like of bins\n dtype : dtype of data\n\n Raises\n ------\n ValueError if bins are not of a compat dtype to dtype\n "
] |
Please provide a description of the function:def _convert_bin_to_datelike_type(bins, dtype):
if is_datetime64tz_dtype(dtype):
bins = to_datetime(bins.astype(np.int64),
utc=True).tz_convert(dtype.tz)
elif is_datetime_or_timedelta_dtype(dtype):
bins = Index(bins.ast... | [
"\n Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is\n datelike\n\n Parameters\n ----------\n bins : list-like of bins\n dtype : dtype of data\n\n Returns\n -------\n bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is\n datelike\n ... |
Please provide a description of the function:def _format_labels(bins, precision, right=True,
include_lowest=False, dtype=None):
closed = 'right' if right else 'left'
if is_datetime64tz_dtype(dtype):
formatter = partial(Timestamp, tz=dtype.tz)
adjust = lambda x: x - Time... | [
" based on the dtype, return our labels "
] |
Please provide a description of the function:def _preprocess_for_cut(x):
x_is_series = isinstance(x, Series)
series_index = None
name = None
if x_is_series:
series_index = x.index
name = x.name
# Check that the passed array is a Pandas or Numpy object
# We don't want to st... | [
"\n handles preprocessing for cut where we convert passed\n input to array, strip the index information and store it\n separately\n "
] |
Please provide a description of the function:def _postprocess_for_cut(fac, bins, retbins, x_is_series,
series_index, name, dtype):
if x_is_series:
fac = Series(fac, index=series_index, name=name)
if not retbins:
return fac
bins = _convert_bin_to_datelike_type(... | [
"\n handles post processing for the cut method where\n we combine the index information if the originally passed\n datatype was a series\n "
] |
Please provide a description of the function:def _round_frac(x, precision):
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:
digits = precision
... | [
"\n Round the fractional part of the given number\n "
] |
Please provide a description of the function:def _infer_precision(base_precision, bins):
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 | [
"Infer an appropriate precision for _round_frac\n "
] |
Please provide a description of the function:def detect_console_encoding():
global _initial_defencoding
encoding = None
try:
encoding = sys.stdout.encoding or sys.stdin.encoding
except (AttributeError, IOError):
pass
# try again for something better
if not encoding or 'asc... | [
"\n Try to find the most capable encoding supported by the console.\n slightly modified from the way IPython handles the same issue.\n "
] |
Please provide a description of the function:def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
if max_fname_arg_count < 0:
raise ValueError("'max_fname_arg_count' must be non-negative")
if len(args) > len(compat_args):
max_arg_count = len(compat_args) + max_fname_arg_co... | [
"\n Checks whether 'args' has length of at most 'compat_args'. Raises\n a TypeError if that is not the case, similar to in Python when a\n function is called with too many arguments.\n\n "
] |
Please provide a description of the function:def _check_for_default_values(fname, arg_val_dict, compat_args):
for key in arg_val_dict:
# try checking equality directly with '=' operator,
# as comparison may have been overridden for the left
# hand object
try:
v1 = ar... | [
"\n Check that the keys in `arg_val_dict` are mapped to their\n default values as specified in `compat_args`.\n\n Note that this function is to be called only when it has been\n checked that arg_val_dict.keys() is a subset of compat_args\n\n "
] |
Please provide a description of the function:def validate_args(fname, args, max_fname_arg_count, compat_args):
_check_arg_length(fname, args, max_fname_arg_count, compat_args)
# We do this so that we can provide a more informative
# error message about the parameters that we are not
# supporting i... | [
"\n Checks whether the length of the `*args` argument passed into a function\n has at most `len(compat_args)` arguments and whether or not all of these\n elements in `args` are set to their default values.\n\n fname: str\n The name of the function being passed the `*args` parameter\n\n args: t... |
Please provide a description of the function:def _check_for_invalid_keys(fname, kwargs, compat_args):
# set(dict) --> set of the dictionary's keys
diff = set(kwargs) - set(compat_args)
if diff:
bad_arg = list(diff)[0]
raise TypeError(("{fname}() got an unexpected "
... | [
"\n Checks whether 'kwargs' contains any keys that are not\n in 'compat_args' and raises a TypeError if there is one.\n\n "
] |
Please provide a description of the function:def validate_kwargs(fname, kwargs, compat_args):
kwds = kwargs.copy()
_check_for_invalid_keys(fname, kwargs, compat_args)
_check_for_default_values(fname, kwds, compat_args) | [
"\n Checks whether parameters passed to the **kwargs argument in a\n function `fname` are valid parameters as specified in `*compat_args`\n and whether or not they are set to their default values.\n\n Parameters\n ----------\n fname: str\n The name of the function being passed the `**kwargs... |
Please provide a description of the function:def validate_args_and_kwargs(fname, args, kwargs,
max_fname_arg_count,
compat_args):
# Check that the total number of arguments passed in (i.e.
# args and kwargs) does not exceed the length of compat_args... | [
"\n Checks whether parameters passed to the *args and **kwargs argument in a\n function `fname` are valid parameters as specified in `*compat_args`\n and whether or not they are set to their default values.\n\n Parameters\n ----------\n fname: str\n The name of the function being passed the... |
Please provide a description of the function:def validate_bool_kwarg(value, arg_name):
if not (is_bool(value) or value is None):
raise ValueError('For argument "{arg}" expected type bool, received '
'type {typ}.'.format(arg=arg_name,
... | [
" Ensures that argument passed in arg_name is of type bool. "
] |
Please provide a description of the function:def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
# TODO: Change to keyword-only args and remove all this
out = {}
# Goal: fill 'out' with index/columns-style arguments
# like out = {'index': foo, 'columns': bar}
# Start by v... | [
"Argument handler for mixed index, columns / axis functions\n\n In an attempt to handle both `.method(index, columns)`, and\n `.method(arg, axis=.)`, we have to do some bad things to argument\n parsing. This translates all arguments to `{index=., columns=.}` style.\n\n Parameters\n ----------\n da... |
Please provide a description of the function:def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True):
from pandas.core.missing import clean_fill_method
if value is None and method is None:
raise ValueError("Must specify a fill 'value' or 'method'.")
elif value is None and me... | [
"Validate the keyword arguments to 'fillna'.\n\n This checks that exactly one of 'value' and 'method' is specified.\n If 'method' is specified, this validates that it's a valid method.\n\n Parameters\n ----------\n value, method : object\n The 'value' and 'method' keyword arguments for 'fillna... |
Please provide a description of the function:def _maybe_process_deprecations(r, how=None, fill_method=None, limit=None):
if how is not None:
# .resample(..., how='sum')
if isinstance(how, str):
method = "{0}()".format(how)
# .resample(..., how=lambda x: ....)
... | [
"\n Potentially we might have a deprecation warning, show it\n but call the appropriate methods anyhow.\n "
] |
Please provide a description of the function:def resample(obj, kind=None, **kwds):
tg = TimeGrouper(**kwds)
return tg._get_resampler(obj, kind=kind) | [
"\n Create a TimeGrouper and return our resampler.\n "
] |
Please provide a description of the function:def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None,
limit=None, kind=None, **kwargs):
# .resample uses 'on' similar to how .groupby uses 'key'
kwargs['key'] = kwargs.pop('on', None)
tg = TimeGrouper(freq... | [
"\n Return our appropriate resampler when grouping as well.\n "
] |
Please provide a description of the function:def _get_timestamp_range_edges(first, last, offset, closed='left', base=0):
if isinstance(offset, Tick):
if isinstance(offset, Day):
# _adjust_dates_anchored assumes 'D' means 24H, but first/last
# might contain a DST transition (23H,... | [
"\n Adjust the `first` Timestamp to the preceeding Timestamp that resides on\n the provided offset. Adjust the `last` Timestamp to the following\n Timestamp that resides on the provided offset. Input Timestamps that\n already reside on the offset will be adjusted depending on the type of\n offset and... |
Please provide a description of the function:def _get_period_range_edges(first, last, offset, closed='left', base=0):
if not all(isinstance(obj, pd.Period) for obj in [first, last]):
raise TypeError("'first' and 'last' must be instances of type Period")
# GH 23882
first = first.to_timestamp()
... | [
"\n Adjust the provided `first` and `last` Periods to the respective Period of\n the given offset that encompasses them.\n\n Parameters\n ----------\n first : pd.Period\n The beginning Period of the range to be adjusted.\n last : pd.Period\n The ending Period of the range to be adjus... |
Please provide a description of the function:def asfreq(obj, freq, method=None, how=None, normalize=False, fill_value=None):
if isinstance(obj.index, PeriodIndex):
if method is not None:
raise NotImplementedError("'method' argument is not supported")
if how is None:
how... | [
"\n Utility frequency conversion method for Series/DataFrame.\n "
] |
Please provide a description of the function:def _from_selection(self):
# 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.groupby.key is not None or
... | [
"\n Is the resampling from a DataFrame column or MultiIndex level.\n "
] |
Please provide a description of the function:def _get_binner(self):
binner, bins, binlabels = self._get_binner_for_time()
bin_grouper = BinGrouper(bins, binlabels, indexer=self.groupby.indexer)
return binner, bin_grouper | [
"\n Create the BinGrouper, assume that self.set_grouper(obj)\n has already been called.\n "
] |
Please provide a description of the function:def transform(self, arg, *args, **kwargs):
return self._selected_obj.groupby(self.groupby).transform(
arg, *args, **kwargs) | [
"\n Call function producing a like-indexed Series on each group and return\n a Series with the transformed values.\n\n Parameters\n ----------\n arg : function\n To apply to each group. Should return a Series with the same index.\n\n Returns\n -------\n ... |
Please provide a description of the function:def _gotitem(self, key, ndim, subset=None):
self._set_binner()
grouper = self.grouper
if subset is None:
subset = self.obj
grouped = groupby(subset, by=None, grouper=grouper, axis=self.axis)
# try the key selectio... | [
"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n "
] |
Please provide a description of the function:def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
if grouper is None:
self._set_binner()
grouper = self.grouper
obj = self._selected_obj
grouped = groupby(obj, by=None, grouper=grouper, axis=self... | [
"\n Re-evaluate the obj with a groupby aggregation.\n "
] |
Please provide a description of the function:def _apply_loffset(self, result):
needs_offset = (
isinstance(self.loffset, (DateOffset, timedelta,
np.timedelta64)) and
isinstance(result.index, DatetimeIndex) and
len(result.index) ... | [
"\n If loffset is set, offset the result index.\n\n This is NOT an idempotent routine, it will be applied\n exactly once to the result.\n\n Parameters\n ----------\n result : Series or DataFrame\n the result of resample\n "
] |
Please provide a description of the function:def _get_resampler_for_grouping(self, groupby, **kwargs):
return self._resampler_for_grouping(self, groupby=groupby, **kwargs) | [
"\n Return the correct class for resampling with groupby.\n "
] |
Please provide a description of the function:def _wrap_result(self, result):
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 isinstance(obj.i... | [
"\n Potentially wrap any results.\n "
] |
Please provide a description of the function:def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
limit_direction='forward', limit_area=None,
downcast=None, **kwargs):
result = self._upsample(None)
return result.interpolate(method=met... | [
"\n Interpolate values according to different methods.\n\n .. versionadded:: 0.18.1\n "
] |
Please provide a description of the function:def std(self, ddof=1, *args, **kwargs):
nv.validate_resampler_func('std', args, kwargs)
return self._downsample('std', ddof=ddof) | [
"\n Compute standard deviation of groups, excluding missing values.\n\n Parameters\n ----------\n ddof : integer, default 1\n Degrees of freedom.\n "
] |
Please provide a description of the function:def var(self, ddof=1, *args, **kwargs):
nv.validate_resampler_func('var', args, kwargs)
return self._downsample('var', ddof=ddof) | [
"\n Compute variance of groups, excluding missing values.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom\n "
] |
Please provide a description of the function:def _apply(self, f, grouper=None, *args, **kwargs):
def func(x):
x = self._shallow_copy(x, groupby=self.groupby)
if isinstance(f, str):
return getattr(x, f)(**kwargs)
return x.apply(f, *args, **kwargs)
... | [
"\n Dispatch to _upsample; we are stripping all of the _upsample kwargs and\n performing the original function call on the grouped object.\n "
] |
Please provide a description of the function:def _downsample(self, how, **kwargs):
self._set_binner()
how = self._is_cython_func(how) or how
ax = self.ax
obj = self._selected_obj
if not len(ax):
# reset to the new freq
obj = obj.copy()
... | [
"\n Downsample the cython defined function.\n\n Parameters\n ----------\n how : string / cython mapped function\n **kwargs : kw args passed to how function\n "
] |
Please provide a description of the function:def _adjust_binner_for_upsample(self, binner):
if self.closed == 'right':
binner = binner[1:]
else:
binner = binner[:-1]
return binner | [
"\n Adjust our binner when upsampling.\n\n The range of a new index should not be outside specified range\n "
] |
Please provide a description of the function:def _upsample(self, method, limit=None, fill_value=None):
self._set_binner()
if self.axis:
raise AssertionError('axis must be 0')
if self._from_selection:
raise ValueError("Upsampling from level= or on= selection"
... | [
"\n Parameters\n ----------\n method : string {'backfill', 'bfill', 'pad',\n 'ffill', 'asfreq'} method for upsampling\n limit : int, default None\n Maximum size gap to fill when reindexing\n fill_value : scalar, default None\n Value to use for miss... |
Please provide a description of the function:def _downsample(self, how, **kwargs):
# we may need to actually resample as if we are timestamps
if self.kind == 'timestamp':
return super()._downsample(how, **kwargs)
how = self._is_cython_func(how) or how
ax = self.ax
... | [
"\n Downsample the cython defined function.\n\n Parameters\n ----------\n how : string / cython mapped function\n **kwargs : kw args passed to how function\n "
] |
Please provide a description of the function:def _upsample(self, method, limit=None, fill_value=None):
# we may need to actually resample as if we are timestamps
if self.kind == 'timestamp':
return super()._upsample(method, limit=limit,
fill_val... | [
"\n Parameters\n ----------\n method : string {'backfill', 'bfill', 'pad', 'ffill'}\n method for upsampling\n limit : int, default None\n Maximum size gap to fill when reindexing\n fill_value : scalar, default None\n Value to use for missing values... |
Please provide a description of the function:def _get_resampler(self, obj, kind=None):
self._set_grouper(obj)
ax = self.ax
if isinstance(ax, DatetimeIndex):
return DatetimeIndexResampler(obj,
groupby=self,
... | [
"\n Return my resampler or raise if we have an invalid axis.\n\n Parameters\n ----------\n obj : input object\n kind : string, optional\n 'period','timestamp','timedelta' are valid\n\n Returns\n -------\n a Resampler\n\n Raises\n -----... |
Please provide a description of the function:def hash_pandas_object(obj, index=True, encoding='utf8', hash_key=None,
categorize=True):
from pandas import Series
if hash_key is None:
hash_key = _default_hash_key
if isinstance(obj, ABCMultiIndex):
return Series(has... | [
"\n Return a data hash of the Index/Series/DataFrame\n\n .. versionadded:: 0.19.2\n\n Parameters\n ----------\n index : boolean, default True\n include the index in the hash (if Series/DataFrame)\n encoding : string, default 'utf8'\n encoding for data & key when strings\n hash_key... |
Please provide a description of the function:def hash_tuples(vals, encoding='utf8', hash_key=None):
is_tuple = False
if isinstance(vals, tuple):
vals = [vals]
is_tuple = True
elif not is_list_like(vals):
raise TypeError("must be convertible to a list-of-tuples")
from pandas... | [
"\n Hash an MultiIndex / list-of-tuples efficiently\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n vals : MultiIndex, list-of-tuples, or single tuple\n encoding : string, default 'utf8'\n hash_key : string key to encode, default to _default_hash_key\n\n Returns\n -------\n ... |
Please provide a description of the function:def hash_tuple(val, encoding='utf8', hash_key=None):
hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key)
for v in val)
h = _combine_hash_arrays(hashes, len(val))[0]
return h | [
"\n Hash a single tuple efficiently\n\n Parameters\n ----------\n val : single tuple\n encoding : string, default 'utf8'\n hash_key : string key to encode, default to _default_hash_key\n\n Returns\n -------\n hash\n\n "
] |
Please provide a description of the function:def _hash_categorical(c, encoding, hash_key):
# Convert ExtensionArrays to ndarrays
values = np.asarray(c.categories.values)
hashed = hash_array(values, encoding, hash_key,
categorize=False)
# we have uint64, as we don't directly... | [
"\n Hash a Categorical by hashing its categories, and then mapping the codes\n to the hashes\n\n Parameters\n ----------\n c : Categorical\n encoding : string, default 'utf8'\n hash_key : string key to encode, default to _default_hash_key\n\n Returns\n -------\n ndarray of hashed value... |
Please provide a description of the function:def hash_array(vals, encoding='utf8', hash_key=None, categorize=True):
if not hasattr(vals, 'dtype'):
raise TypeError("must pass a ndarray-like")
dtype = vals.dtype
if hash_key is None:
hash_key = _default_hash_key
# For categoricals, ... | [
"\n Given a 1d array, return an array of deterministic integers.\n\n .. versionadded:: 0.19.2\n\n Parameters\n ----------\n vals : ndarray, Categorical\n encoding : string, default 'utf8'\n encoding for data & key when strings\n hash_key : string key to encode, default to _default_hash_k... |
Please provide a description of the function:def _hash_scalar(val, encoding='utf8', hash_key=None):
if isna(val):
# this is to be consistent with the _hash_categorical implementation
return np.array([np.iinfo(np.uint64).max], dtype='u8')
if getattr(val, 'tzinfo', None) is not None:
... | [
"\n Hash scalar value\n\n Returns\n -------\n 1d uint64 numpy array of hash value, of length 1\n "
] |
Please provide a description of the function:def _process_single_doc(self, single_doc):
base_name, extension = os.path.splitext(single_doc)
if extension in ('.rst', '.ipynb'):
if os.path.exists(os.path.join(SOURCE_PATH, single_doc)):
return single_doc
els... | [
"\n Make sure the provided value for --single is a path to an existing\n .rst/.ipynb file, or a pandas object that can be imported.\n\n For example, categorial.rst or pandas.DataFrame.head. For the latter,\n return the corresponding file path\n (e.g. reference/api/pandas.DataFrame... |
Please provide a description of the function:def _run_os(*args):
subprocess.check_call(args, stdout=sys.stdout, stderr=sys.stderr) | [
"\n Execute a command as a OS terminal.\n\n Parameters\n ----------\n *args : list of str\n Command and parameters to be executed\n\n Examples\n --------\n >>> DocBuilder()._run_os('python', '--version')\n "
] |
Please provide a description of the function:def _sphinx_build(self, kind):
if kind not in ('html', 'latex'):
raise ValueError('kind must be html or latex, '
'not {}'.format(kind))
cmd = ['sphinx-build', '-b', kind]
if self.num_jobs:
... | [
"\n Call sphinx to build documentation.\n\n Attribute `num_jobs` from the class is used.\n\n Parameters\n ----------\n kind : {'html', 'latex'}\n\n Examples\n --------\n >>> DocBuilder(num_jobs=4)._sphinx_build('html')\n "
] |
Please provide a description of the function:def _open_browser(self, single_doc_html):
url = os.path.join('file://', DOC_PATH, 'build', 'html',
single_doc_html)
webbrowser.open(url, new=2) | [
"\n Open a browser tab showing single\n "
] |
Please provide a description of the function:def _get_page_title(self, page):
fname = os.path.join(SOURCE_PATH, '{}.rst'.format(page))
option_parser = docutils.frontend.OptionParser(
components=(docutils.parsers.rst.Parser,))
doc = docutils.utils.new_document(
'<... | [
"\n Open the rst file `page` and extract its title.\n "
] |
Please provide a description of the function:def _add_redirects(self):
html = '''
<html>
<head>
<meta http-equiv="refresh" content="0;URL={url}"/>
</head>
<body>
<p>
The page has been moved to <a href="{url}... | [
"\n Create in the build directory an html file with a redirect,\n for every row in REDIRECTS_FILE.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.