Code
stringlengths
103
85.9k
Summary
sequencelengths
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_categories: num = max_categories // 2 head = fmt.format_array(self.categories[:num], None) tail = fmt.format_array(self.categories[-num:], None) category_strs = head + ["..."] + tail else: category_strs = fmt.format_array(self.categories, None) # Strip all leading spaces, which format_array adds for columns... category_strs = [x.strip() for x in category_strs] return category_strs
[ "\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( length=len(self.categories), dtype=dtype) width, height = get_terminal_size() max_width = get_option("display.width") or width if console.in_ipython_frontend(): # 0 = no breaks max_width = 0 levstring = "" start = True cur_col_len = len(levheader) # header sep_len, sep = (3, " < ") if self.ordered else (2, ", ") linesep = sep.rstrip() + "\n" # remove whitespace for val in category_strs: if max_width != 0 and cur_col_len + sep_len + len(val) > max_width: levstring += linesep + (" " * (len(levheader) + 1)) cur_col_len = len(levheader) + 1 # header + a whitespace elif not start: levstring += sep cur_col_len += len(val) levstring += val start = False # replace to simple save space by return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"
[ "\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] for start, end in zip(counts, counts[1:])) result = dict(zip(categories, result)) return result
[ "\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 In [2]: c\n Out[2]:\n [a, a, b, c, a]\n Categories (3, object): [a, b, c]\n\n In [3]: c.categories\n Out[3]: Index(['a', 'b', 'c'], dtype='object')\n\n In [4]: c.codes\n Out[4]: array([0, 0, 1, 2, 0], dtype=int8)\n\n In [5]: c._reverse_indexer()\n Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}\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) if pointer == -1: return np.nan else: return self.categories[pointer]
[ "\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), dropna)) return self._constructor(values=codes, dtype=self.dtype, fastpath=True)
[ "\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 -------\n modes : `Categorical` (sorted)\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_codes = unique_codes[unique_codes != -1] if self.ordered: take_codes = np.sort(take_codes) return cat.set_categories(cat.categories.take(take_codes))
[ "\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 keeps existing order.\n\n Returns\n -------\n unique values : ``Categorical``\n\n Examples\n --------\n An unordered Categorical will return categories in the\n order of appearance.\n\n >>> pd.Categorical(list('baabc'))\n [b, a, c]\n Categories (3, object): [b, a, c]\n\n >>> pd.Categorical(list('baabc'), categories=list('abc'))\n [b, a, c]\n Categories (3, object): [b, a, c]\n\n An ordered Categorical preserves the category ordering.\n\n >>> pd.Categorical(list('baabc'),\n ... categories=list('abc'),\n ... ordered=True)\n [b, a, c]\n Categories (3, object): [a < b < c]\n\n See Also\n --------\n unique\n CategoricalIndex.unique\n Series.unique\n\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_for_categories(other.codes, other.categories, self.categories) return np.array_equal(self._codes, other_codes) return False
[ "\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'] result.index.name = 'categories' return result
[ "\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 [{values_type}]" .format(values_type=type(values).__name__)) values = sanitize_array(values, None, None) null_mask = np.asarray(isna(values)) code_values = self.categories.get_indexer(values) code_values = code_values[null_mask | (code_values >= 0)] return algorithms.isin(self.codes, code_values)
[ "\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 The sequence of values to test. Passing in a single string will\n raise a ``TypeError``. Instead, turn a single string into a\n list of one element.\n\n Returns\n -------\n isin : numpy.ndarray (bool dtype)\n\n Raises\n ------\n TypeError\n * If `values` is not a set or list-like\n\n See Also\n --------\n pandas.Series.isin : Equivalent method on Series.\n\n Examples\n --------\n\n >>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',\n ... 'hippo'])\n >>> s.isin(['cow', 'lama'])\n array([ True, True, True, False, True, False])\n\n Passing a single string as ``s.isin('lama')`` will raise an error. Use\n a list of one element instead:\n\n >>> s.isin(['lama'])\n array([ True, False, True, False, True, False])\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 unit in {'Y', 'y', 'M'}: warnings.warn("M and Y units are deprecated and " "will be removed in a future version.", FutureWarning, stacklevel=2) if arg is None: return arg elif isinstance(arg, ABCSeries): values = _convert_listlike(arg._values, unit=unit, box=False, errors=errors) return arg._constructor(values, index=arg.index, name=arg.name) elif isinstance(arg, ABCIndexClass): return _convert_listlike(arg, unit=unit, box=box, errors=errors, name=arg.name) elif isinstance(arg, np.ndarray) and arg.ndim == 0: # extract array scalar and process below arg = arg.item() elif is_list_like(arg) and getattr(arg, 'ndim', 1) == 1: return _convert_listlike(arg, unit=unit, box=box, errors=errors) elif getattr(arg, 'ndim', 1) > 1: raise TypeError('arg must be a string, timedelta, list, tuple, ' '1-d array, or Series') # ...so it must be a scalar value. Return scalar. return _coerce_scalar_to_timedelta_type(arg, unit=unit, box=box, errors=errors)
[ "\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 : str, timedelta, list-like or Series\n The data to be converted to timedelta.\n unit : str, default 'ns'\n Denotes the unit of the arg. Possible values:\n ('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr',\n 'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',\n 'sec', 'second', 'ms', 'milliseconds', 'millisecond',\n 'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',\n 'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',\n 'nanosecond', 'N').\n box : bool, default True\n - If True returns a Timedelta/TimedeltaIndex of the results.\n - If False returns a numpy.timedelta64 or numpy.darray of\n values of dtype timedelta64[ns].\n\n .. deprecated:: 0.25.0\n Use :meth:`.to_numpy` or :meth:`Timedelta.to_timedelta64`\n instead to get an ndarray of values or numpy.timedelta64,\n respectively.\n\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n - If 'raise', then invalid parsing will raise an exception.\n - If 'coerce', then invalid parsing will be set as NaT.\n - If 'ignore', then invalid parsing will return the input.\n\n Returns\n -------\n timedelta64 or numpy.array of timedelta64\n Output type returned if parsing succeeded.\n\n See Also\n --------\n DataFrame.astype : Cast argument to a specified dtype.\n to_datetime : Convert argument to datetime.\n\n Examples\n --------\n\n Parsing a single string to a Timedelta:\n\n >>> pd.to_timedelta('1 days 06:05:01.00003')\n Timedelta('1 days 06:05:01.000030')\n >>> pd.to_timedelta('15.5us')\n Timedelta('0 days 00:00:00.000015')\n\n Parsing a list or array of strings:\n\n >>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])\n TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT],\n dtype='timedelta64[ns]', freq=None)\n\n Converting numbers by specifying the `unit` keyword argument:\n\n >>> pd.to_timedelta(np.arange(5), unit='s')\n TimedeltaIndex(['00:00:00', '00:00:01', '00:00:02',\n '00:00:03', '00:00:04'],\n dtype='timedelta64[ns]', freq=None)\n >>> pd.to_timedelta(np.arange(5), unit='d')\n TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],\n dtype='timedelta64[ns]', freq=None)\n\n Returning an ndarray by using the 'box' keyword argument:\n\n >>> pd.to_timedelta(np.arange(5), box=False)\n array([0, 1, 2, 3, 4], dtype='timedelta64[ns]')\n " ]
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[ns]') except ValueError: if errors == 'raise': raise elif errors == 'ignore': return r # coerce result = NaT return result
[ "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 where the input is a # generator, we return a useful list-like instead of a # used-up generator arg = np.array(list(arg), dtype=object) try: value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0] except ValueError: if errors == 'ignore': return arg else: # This else-block accounts for the cases when errors='raise' # and errors='coerce'. If errors == 'raise', these errors # should be raised. If errors == 'coerce', we shouldn't # expect any errors to be raised, since all parsing errors # cause coercion to pd.NaT. However, if an error / bug is # introduced that causes an Exception to be raised, we would # like to surface it. raise if box: from pandas import TimedeltaIndex value = TimedeltaIndex(value, unit='ns', name=name) return value
[ "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): start = offset.rollforward(start) elif end and not offset.onOffset(end): end = offset.rollback(end) if periods is None and end < start and offset.n >= 0: end = None periods = 0 if end is None: end = start + (periods - 1) * offset if start is None: start = end - (periods - 1) * offset cur = start if offset.n >= 0: while cur <= end: yield cur # faster than cur + offset next_date = offset.apply(cur) if next_date <= cur: raise ValueError('Offset {offset} did not increment date' .format(offset=offset)) cur = next_date else: while cur >= end: yield cur # faster than cur + offset next_date = offset.apply(cur) if next_date >= cur: raise ValueError('Offset {offset} did not decrement date' .format(offset=offset)) cur = next_date
[ "\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, (default None)\n offset : DateOffset, (default BDay())\n\n Notes\n -----\n * This method is faster for generating weekdays than dateutil.rrule\n * At least two of (start, end, periods) must be specified.\n * If both start and end are specified, the returned dates will\n satisfy start <= date <= end.\n\n Returns\n -------\n dates : generator object\n " ]
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( name=self.__class__.__name__)) kwds = self.kwds relativedelta_fast = {'years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'microseconds'} # relativedelta/_offset path only valid for base DateOffset if (self._use_relativedelta and set(kwds).issubset(relativedelta_fast)): months = ((kwds.get('years', 0) * 12 + kwds.get('months', 0)) * self.n) if months: shifted = liboffsets.shift_months(i.asi8, months) i = type(i)(shifted, freq=i.freq, dtype=i.dtype) weeks = (kwds.get('weeks', 0)) * self.n if weeks: # integer addition on PeriodIndex is deprecated, # so we directly use _time_shift instead asper = i.to_period('W') if not isinstance(asper._data, np.ndarray): # unwrap PeriodIndex --> PeriodArray asper = asper._data shifted = asper._time_shift(weeks) i = shifted.to_timestamp() + i.to_perioddelta('W') timedelta_kwds = {k: v for k, v in kwds.items() if k in ['days', 'hours', 'minutes', 'seconds', 'microseconds']} if timedelta_kwds: delta = Timedelta(**timedelta_kwds) i = i + (self.n * delta) return i elif not self._use_relativedelta and hasattr(self, '_offset'): # timedelta return i + (self._offset * self.n) else: # relativedelta with other keywords kwd = set(kwds) - relativedelta_fast raise NotImplementedError("DateOffset with relativedelta " "keyword(s) {kwd} not able to be " "applied vectorized".format(kwd=kwd))
[ "\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, weekmask=self.weekmask, holidays=self.holidays, calendar=self.calendar) else: return BusinessDay(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 self.n < 0 and other.time() < self.start: other = other + self.next_bday return datetime(other.year, other.month, other.day, self.start.hour, self.start.minute)
[ "\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, self.end.hour, self.end.minute) return (until - dtstart).total_seconds() else: dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute) until = datetime(2014, 4, 2, self.end.hour, self.end.minute) return (until - dtstart).total_seconds()
[ "\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) else: dt = self._next_opening_time( dt) + timedelta(seconds=businesshours) 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): 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 if self.n >= 0: op = self._prev_opening_time(dt) else: op = self._next_opening_time(dt) span = (dt - op).total_seconds() if span <= businesshours: return True else: return False
[ "\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 = cbday.rollback return roll_func
[ "\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): # unwrap PeriodIndex --> PeriodArray base_period = base_period._data if self.n > 0: # when adding, dates on end roll to next normed = dtindex - off + Timedelta(1, 'D') - Timedelta(1, 'ns') roll = np.where(base_period.to_timestamp(how='end') == normed, self.n, self.n - 1) # integer-array addition on PeriodIndex is deprecated, # so we use _addsub_int_array directly shifted = base_period._addsub_int_array(roll, operator.add) base = shifted.to_timestamp(how='end') else: # integer addition on PeriodIndex is deprecated, # so we use _time_shift directly roll = self.n base = base_period._time_shift(roll).to_timestamp(how='end') return base + off + Timedelta(1, 'ns') - Timedelta(1, 'D')
[ "\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 adjustment qtr_lens = self.get_weeks(norm) # check thet qtr_lens is consistent with self._offset addition end = liboffsets.shift_day(start, days=7 * sum(qtr_lens)) assert self._offset.onOffset(end), (start, end, qtr_lens) tdelta = norm - start for qlen in qtr_lens: if qlen * 7 <= tdelta.days: num_qtrs += 1 tdelta -= Timedelta(days=qlen * 7) else: break else: tdelta = Timedelta(0) # Note: we always have tdelta.value >= 0 return start, num_qtrs, tdelta
[ "\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 ----------\n other : datetime or Timestamp\n\n Returns\n -------\n tuple of\n prev_year_end : Timestamp giving most recent fiscal year end\n num_qtrs : int\n tdelta : Timedelta\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_index=ignore_index, join=join, keys=keys, levels=levels, names=names, verify_integrity=verify_integrity, copy=copy, sort=sort) return op.get_result()
[ "\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 ----------\n objs : a sequence or mapping of Series, DataFrame, or Panel objects\n If a dict is passed, the sorted keys will be used as the `keys`\n argument, unless it is passed, in which case the values will be\n selected (see below). Any None objects will be dropped silently unless\n they are all None in which case a ValueError will be raised.\n axis : {0/'index', 1/'columns'}, default 0\n The axis to concatenate along.\n join : {'inner', 'outer'}, default 'outer'\n How to handle indexes on other axis (or axes).\n join_axes : list of Index objects\n Specific indexes to use for the other n - 1 axes instead of performing\n inner/outer set logic.\n ignore_index : bool, default False\n If True, do not use the index values along the concatenation axis. The\n resulting axis will be labeled 0, ..., n - 1. This is useful if you are\n concatenating objects where the concatenation axis does not have\n meaningful indexing information. Note the index values on the other\n axes are still respected in the join.\n keys : sequence, default None\n If multiple levels passed, should contain tuples. Construct\n hierarchical index using the passed keys as the outermost level.\n levels : list of sequences, default None\n Specific levels (unique values) to use for constructing a\n MultiIndex. Otherwise they will be inferred from the keys.\n names : list, default None\n Names for the levels in the resulting hierarchical index.\n verify_integrity : bool, default False\n Check whether the new concatenated axis contains duplicates. This can\n be very expensive relative to the actual data concatenation.\n sort : bool, default None\n Sort non-concatenation axis if it is not already aligned when `join`\n is 'outer'. The current default of sorting is deprecated and will\n change to not-sorting in a future version of pandas.\n\n Explicitly pass ``sort=True`` to silence the warning and sort.\n Explicitly pass ``sort=False`` to silence the warning and not sort.\n\n This has no effect when ``join='inner'``, which already preserves\n the order of the non-concatenation axis.\n\n .. versionadded:: 0.23.0\n\n copy : bool, default True\n If False, do not copy data unnecessarily.\n\n Returns\n -------\n object, type of objs\n When concatenating all ``Series`` along the index (axis=0), a\n ``Series`` is returned. When ``objs`` contains at least one\n ``DataFrame``, a ``DataFrame`` is returned. When concatenating along\n the columns (axis=1), a ``DataFrame`` is returned.\n\n See Also\n --------\n Series.append : Concatenate Series.\n DataFrame.append : Concatenate DataFrames.\n DataFrame.join : Join DataFrames using indexes.\n DataFrame.merge : Merge DataFrames by indexes or columns.\n\n Notes\n -----\n The keys, levels, and names arguments are all optional.\n\n A walkthrough of how this method fits in with other tools for combining\n pandas objects can be found `here\n <http://pandas.pydata.org/pandas-docs/stable/merging.html>`__.\n\n Examples\n --------\n Combine two ``Series``.\n\n >>> s1 = pd.Series(['a', 'b'])\n >>> s2 = pd.Series(['c', 'd'])\n >>> pd.concat([s1, s2])\n 0 a\n 1 b\n 0 c\n 1 d\n dtype: object\n\n Clear the existing index and reset it in the result\n by setting the ``ignore_index`` option to ``True``.\n\n >>> pd.concat([s1, s2], ignore_index=True)\n 0 a\n 1 b\n 2 c\n 3 d\n dtype: object\n\n Add a hierarchical index at the outermost level of\n the data with the ``keys`` option.\n\n >>> pd.concat([s1, s2], keys=['s1', 's2'])\n s1 0 a\n 1 b\n s2 0 c\n 1 d\n dtype: object\n\n Label the index keys you create with the ``names`` option.\n\n >>> pd.concat([s1, s2], keys=['s1', 's2'],\n ... names=['Series name', 'Row ID'])\n Series name Row ID\n s1 0 a\n 1 b\n s2 0 c\n 1 d\n dtype: object\n\n Combine two ``DataFrame`` objects with identical columns.\n\n >>> df1 = pd.DataFrame([['a', 1], ['b', 2]],\n ... columns=['letter', 'number'])\n >>> df1\n letter number\n 0 a 1\n 1 b 2\n >>> df2 = pd.DataFrame([['c', 3], ['d', 4]],\n ... columns=['letter', 'number'])\n >>> df2\n letter number\n 0 c 3\n 1 d 4\n >>> pd.concat([df1, df2])\n letter number\n 0 a 1\n 1 b 2\n 0 c 3\n 1 d 4\n\n Combine ``DataFrame`` objects with overlapping columns\n and return everything. Columns outside the intersection will\n be filled with ``NaN`` values.\n\n >>> df3 = pd.DataFrame([['c', 3, 'cat'], ['d', 4, 'dog']],\n ... columns=['letter', 'number', 'animal'])\n >>> df3\n letter number animal\n 0 c 3 cat\n 1 d 4 dog\n >>> pd.concat([df1, df3], sort=False)\n letter number animal\n 0 a 1 NaN\n 1 b 2 NaN\n 0 c 3 cat\n 1 d 4 dog\n\n Combine ``DataFrame`` objects with overlapping columns\n and return only those that are shared by passing ``inner`` to\n the ``join`` keyword argument.\n\n >>> pd.concat([df1, df3], join=\"inner\")\n letter number\n 0 a 1\n 1 b 2\n 0 c 3\n 1 d 4\n\n Combine ``DataFrame`` objects horizontally along the x axis by\n passing in ``axis=1``.\n\n >>> df4 = pd.DataFrame([['bird', 'polly'], ['monkey', 'george']],\n ... columns=['animal', 'name'])\n >>> pd.concat([df1, df4], axis=1)\n letter number animal name\n 0 a 1 bird polly\n 1 b 2 monkey george\n\n Prevent the result from including duplicate index values with the\n ``verify_integrity`` option.\n\n >>> df5 = pd.DataFrame([1], index=['a'])\n >>> df5\n 0\n a 1\n >>> df6 = pd.DataFrame([2], index=['a'])\n >>> df6\n 0\n a 2\n >>> pd.concat([df5, df6], verify_integrity=True)\n Traceback (most recent call last):\n ...\n ValueError: Indexes have overlapping values: ['a']\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 elif self.keys is None: names = [None] * len(self.objs) num = 0 has_names = False for i, x in enumerate(self.objs): if not isinstance(x, Series): raise TypeError("Cannot concatenate type 'Series' " "with object of type {type!r}" .format(type=type(x).__name__)) if x.name is not None: names[i] = x.name has_names = True else: names[i] = num num += 1 if has_names: return Index(names) else: return ibase.default_index(len(self.objs)) else: return ensure_index(self.keys).set_names(self.names) else: indexes = [x._data.axes[self.axis] for x in self.objs] if self.ignore_index: idx = ibase.default_index(sum(len(i) for i in indexes)) return idx if self.keys is None: concat_axis = _concat_indexes(indexes) else: concat_axis = _make_concat_multiindex(indexes, self.keys, self.levels, self.names) self._maybe_check_integrity(concat_axis) return concat_axis
[ "\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_value = dt.type(term.value) term.update(new_value)
[ "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 dtype to cast to.\n " ]
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, term_type=term_type, eval_in_python=eval_in_python) right = self.rhs.evaluate(env, engine=engine, parser=parser, term_type=term_type, eval_in_python=eval_in_python) # base cases if self.op in eval_in_python: res = self.func(left.value, right.value) else: from pandas.core.computation.eval import eval res = eval(self, local_dict=env, engine=engine, parser=parser) name = env.add_tmp(res) return term_type(name, env=env)
[ "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-evaluated\" expression as an instance of ``term_type``\n " ]
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_thing return encoder(value) lhs, rhs = self.lhs, self.rhs if is_term(lhs) and lhs.is_datetime and is_term(rhs) and rhs.is_scalar: v = rhs.value if isinstance(v, (int, float)): v = stringify(v) v = Timestamp(_ensure_decoded(v)) if v.tz is not None: v = v.tz_convert('UTC') self.rhs.update(v) if is_term(rhs) and rhs.is_datetime and is_term(lhs) and lhs.is_scalar: v = lhs.value if isinstance(v, (int, float)): v = stringify(v) v = Timestamp(_ensure_decoded(v)) if v.tz is not None: v = v.tz_convert('UTC') self.lhs.update(v)
[ "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) rownames = _get_names(index, rownames, prefix='row') colnames = _get_names(columns, colnames, prefix='col') common_idx = _get_objs_combined_axis(index + columns, intersect=True, sort=False) data = {} data.update(zip(rownames, index)) data.update(zip(colnames, columns)) if values is None and aggfunc is not None: raise ValueError("aggfunc cannot be used without values.") if values is not None and aggfunc is None: raise ValueError("values cannot be used without an aggfunc.") from pandas import DataFrame df = DataFrame(data, index=common_idx) if values is None: df['__dummy__'] = 0 kwargs = {'aggfunc': len, 'fill_value': 0} else: df['__dummy__'] = values kwargs = {'aggfunc': aggfunc} table = df.pivot_table('__dummy__', index=rownames, columns=colnames, margins=margins, margins_name=margins_name, dropna=dropna, **kwargs) # Post-process if normalize is not False: table = _normalize(table, normalize=normalize, margins=margins, margins_name=margins_name) return table
[ "\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 in the rows.\n columns : array-like, Series, or list of arrays/Series\n Values to group by in the columns.\n values : array-like, optional\n Array of values to aggregate according to the factors.\n Requires `aggfunc` be specified.\n rownames : sequence, default None\n If passed, must match number of row arrays passed.\n colnames : sequence, default None\n If passed, must match number of column arrays passed.\n aggfunc : function, optional\n If specified, requires `values` be specified as well.\n margins : bool, default False\n Add row/column margins (subtotals).\n margins_name : str, default 'All'\n Name of the row/column that will contain the totals\n when margins is True.\n\n .. versionadded:: 0.21.0\n\n dropna : bool, default True\n Do not include columns whose entries are all NaN.\n normalize : bool, {'all', 'index', 'columns'}, or {0,1}, default False\n Normalize by dividing all values by the sum of values.\n\n - If passed 'all' or `True`, will normalize over all values.\n - If passed 'index' will normalize over each row.\n - If passed 'columns' will normalize over each column.\n - If margins is `True`, will also normalize margin values.\n\n .. versionadded:: 0.18.1\n\n Returns\n -------\n DataFrame\n Cross tabulation of the data.\n\n See Also\n --------\n DataFrame.pivot : Reshape data based on column values.\n pivot_table : Create a pivot table as a DataFrame.\n\n Notes\n -----\n Any Series passed will have their name attributes used unless row or column\n names for the cross-tabulation are specified.\n\n Any input passed containing Categorical data will have **all** of its\n categories included in the cross-tabulation, even if the actual data does\n not contain any instances of a particular category.\n\n In the event that there aren't overlapping indexes an empty DataFrame will\n be returned.\n\n Examples\n --------\n >>> a = np.array([\"foo\", \"foo\", \"foo\", \"foo\", \"bar\", \"bar\",\n ... \"bar\", \"bar\", \"foo\", \"foo\", \"foo\"], dtype=object)\n >>> b = np.array([\"one\", \"one\", \"one\", \"two\", \"one\", \"one\",\n ... \"one\", \"two\", \"two\", \"two\", \"one\"], dtype=object)\n >>> c = np.array([\"dull\", \"dull\", \"shiny\", \"dull\", \"dull\", \"shiny\",\n ... \"shiny\", \"dull\", \"shiny\", \"shiny\", \"shiny\"],\n ... dtype=object)\n >>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])\n b one two\n c dull shiny dull shiny\n a\n bar 1 2 1 0\n foo 2 2 1 2\n\n Here 'c' and 'f' are not represented in the data and will not be\n shown in the output because dropna is True by default. Set\n dropna=False to preserve categories with no data.\n\n >>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])\n >>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])\n >>> pd.crosstab(foo, bar)\n col_0 d e\n row_0\n a 1 0\n b 0 1\n >>> pd.crosstab(foo, bar, dropna=False)\n col_0 d e f\n row_0\n a 1 0 0\n b 0 1 0\n c 0 0 0\n " ]
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)[1] for l in left) + self._shape(right)[1]) else: vcells = max([self._shape(l)[0] for l in left] + [self._shape(right)[0]]) hcells = sum([self._shape(l)[1] for l in left] + [self._shape(right)[1]]) return hcells, vcells
[ "\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] right = self._conv(right) hcells, vcells = self._get_cells(left, right, vertical) if vertical: figsize = self.cell_width * hcells, self.cell_height * vcells else: # include margin for titles figsize = self.cell_width * hcells, self.cell_height * vcells fig = plt.figure(figsize=figsize) if vertical: gs = gridspec.GridSpec(len(left), hcells) # left max_left_cols = max(self._shape(l)[1] for l in left) max_left_rows = max(self._shape(l)[0] for l in left) for i, (l, label) in enumerate(zip(left, labels)): ax = fig.add_subplot(gs[i, 0:max_left_cols]) self._make_table(ax, l, title=label, height=1.0 / max_left_rows) # right ax = plt.subplot(gs[:, max_left_cols:]) self._make_table(ax, right, title='Result', height=1.05 / vcells) fig.subplots_adjust(top=0.9, bottom=0.05, left=0.05, right=0.95) else: max_rows = max(self._shape(df)[0] for df in left + [right]) height = 1.0 / np.max(max_rows) gs = gridspec.GridSpec(1, hcells) # left i = 0 for l, label in zip(left, labels): sp = self._shape(l) ax = fig.add_subplot(gs[0, i:i + sp[1]]) self._make_table(ax, l, title=label, height=height) i += sp[1] # right ax = plt.subplot(gs[0, i:]) self._make_table(ax, right, title='Result', height=height) fig.subplots_adjust(top=0.85, bottom=0.05, left=0.05, right=0.95) return fig
[ "\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 If True, use vertical layout. If False, use horizontal layout.\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_series, series_index, name, x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) if not np.iterable(bins): if is_scalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.") try: # for array-like sz = x.size except AttributeError: x = np.asarray(x) sz = x.size if sz == 0: raise ValueError('Cannot cut empty array') rng = (nanops.nanmin(x), nanops.nanmax(x)) mn, mx = [mi + 0.0 for mi in rng] if np.isinf(mn) or np.isinf(mx): # GH 24314 raise ValueError('cannot specify integer `bins` when input data ' 'contains infinity') elif mn == mx: # adjust end points before binning mn -= .001 * abs(mn) if mn != 0 else .001 mx += .001 * abs(mx) if mx != 0 else .001 bins = np.linspace(mn, mx, bins + 1, endpoint=True) else: # adjust end points after binning bins = np.linspace(mn, mx, bins + 1, endpoint=True) adj = (mx - mn) * 0.001 # 0.1% of the range if right: bins[0] -= adj else: bins[-1] += adj elif isinstance(bins, IntervalIndex): if bins.is_overlapping: raise ValueError('Overlapping IntervalIndex is not accepted.') else: if is_datetime64tz_dtype(bins): bins = np.asarray(bins, dtype=_NS_DTYPE) else: bins = np.asarray(bins) bins = _convert_bin_to_numeric_type(bins, dtype) # GH 26045: cast to float64 to avoid an overflow if (np.diff(bins.astype('float64')) < 0).any(): raise ValueError('bins must increase monotonically.') fac, bins = _bins_to_cuts(x, bins, right=right, labels=labels, precision=precision, include_lowest=include_lowest, dtype=dtype, duplicates=duplicates) return _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype)
[ "\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 equal number of bins, or a\n pre-specified array of bins.\n\n Parameters\n ----------\n x : array-like\n The input array to be binned. Must be 1-dimensional.\n bins : int, sequence of scalars, or IntervalIndex\n The criteria to bin by.\n\n * int : Defines the number of equal-width bins in the range of `x`. The\n range of `x` is extended by .1% on each side to include the minimum\n and maximum values of `x`.\n * sequence of scalars : Defines the bin edges allowing for non-uniform\n width. No extension of the range of `x` is done.\n * IntervalIndex : Defines the exact bins to be used. Note that\n IntervalIndex for `bins` must be non-overlapping.\n\n right : bool, default True\n Indicates whether `bins` includes the rightmost edge or not. If\n ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]``\n indicate (1,2], (2,3], (3,4]. This argument is ignored when\n `bins` is an IntervalIndex.\n labels : array or bool, optional\n Specifies the labels for the returned bins. Must be the same length as\n the resulting bins. If False, returns only integer indicators of the\n bins. This affects the type of the output container (see below).\n This argument is ignored when `bins` is an IntervalIndex.\n retbins : bool, default False\n Whether to return the bins or not. Useful when bins is provided\n as a scalar.\n precision : int, default 3\n The precision at which to store and display the bins labels.\n include_lowest : bool, default False\n Whether the first interval should be left-inclusive or not.\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n out : Categorical, Series, or ndarray\n An array-like object representing the respective bin for each value\n of `x`. The type depends on the value of `labels`.\n\n * True (default) : returns a Series for Series `x` or a\n Categorical for all other inputs. The values stored within\n are Interval dtype.\n\n * sequence of scalars : returns a Series for Series `x` or a\n Categorical for all other inputs. The values stored within\n are whatever the type in the sequence is.\n\n * False : returns an ndarray of integers.\n\n bins : numpy.ndarray or IntervalIndex.\n The computed or specified bins. Only returned when `retbins=True`.\n For scalar or sequence `bins`, this is an ndarray with the computed\n bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For\n an IntervalIndex `bins`, this is equal to `bins`.\n\n See Also\n --------\n qcut : Discretize variable into equal-sized buckets based on rank\n or based on sample quantiles.\n Categorical : Array type for storing data that come from a\n fixed set of values.\n Series : One-dimensional array with axis labels (including time series).\n IntervalIndex : Immutable Index implementing an ordered, sliceable set.\n\n Notes\n -----\n Any NA values will be NA in the result. Out of bounds values will be NA in\n the resulting Series or Categorical object.\n\n Examples\n --------\n Discretize into three equal-sized bins.\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)\n ... # doctest: +ELLIPSIS\n [(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\n Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)\n ... # doctest: +ELLIPSIS\n ([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\n Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...\n array([0.994, 3. , 5. , 7. ]))\n\n Discovers the same bins, but assign them specific labels. Notice that\n the returned Categorical's categories are `labels` and is ordered.\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),\n ... 3, labels=[\"bad\", \"medium\", \"good\"])\n [bad, good, medium, medium, good, bad]\n Categories (3, object): [bad < medium < good]\n\n ``labels=False`` implies you just want the bins back.\n\n >>> pd.cut([0, 1, 1, 2], bins=4, labels=False)\n array([0, 1, 1, 3])\n\n Passing a Series as an input returns a Series with categorical dtype:\n\n >>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n ... index=['a', 'b', 'c', 'd', 'e'])\n >>> pd.cut(s, 3)\n ... # doctest: +ELLIPSIS\n a (1.992, 4.667]\n b (1.992, 4.667]\n c (4.667, 7.333]\n d (7.333, 10.0]\n e (7.333, 10.0]\n dtype: category\n Categories (3, interval[float64]): [(1.992, 4.667] < (4.667, ...\n\n Passing a Series as an input returns a Series with mapping value.\n It is used to map numerically to intervals based on bins.\n\n >>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n ... index=['a', 'b', 'c', 'd', 'e'])\n >>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)\n ... # doctest: +ELLIPSIS\n (a 0.0\n b 1.0\n c 2.0\n d 3.0\n e 4.0\n dtype: float64, array([0, 2, 4, 6, 8]))\n\n Use `drop` optional when bins is not unique\n\n >>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,\n ... right=False, duplicates='drop')\n ... # doctest: +ELLIPSIS\n (a 0.0\n b 1.0\n c 2.0\n d 3.0\n e 3.0\n dtype: float64, array([0, 2, 4, 6, 8]))\n\n Passing an IntervalIndex for `bins` results in those categories exactly.\n Notice that values not covered by the IntervalIndex are set to NaN. 0\n is to the left of the first bin (which is closed on the right), and 1.5\n falls between two bins.\n\n >>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])\n >>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)\n [NaN, (0, 1], NaN, (2, 3], (4, 5]]\n Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]\n " ]
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: quantiles = q bins = algos.quantile(x, quantiles) fac, bins = _bins_to_cuts(x, bins, labels=labels, precision=precision, include_lowest=True, dtype=dtype, duplicates=duplicates) return _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype)
[ "\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 x : 1d ndarray or Series\n q : integer or array of quantiles\n Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately\n array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles\n labels : array or boolean, default None\n Used as labels for the resulting bins. Must be of the same length as\n the resulting bins. If False, return only integer indicators of the\n bins.\n retbins : bool, optional\n Whether to return the (bins, labels) or not. Can be useful if bins\n is given as a scalar.\n precision : int, optional\n The precision at which to store and display the bins labels\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n out : Categorical or Series or array of integers if labels is False\n The return type (Categorical or Series) depends on the input: a Series\n of type category if input is a Series else Categorical. Bins are\n represented as categories when categorical data is returned.\n bins : ndarray of floats\n Returned only if `retbins` is True.\n\n Notes\n -----\n Out of bounds values will be NA in the resulting Categorical object\n\n Examples\n --------\n >>> pd.qcut(range(5), 4)\n ... # doctest: +ELLIPSIS\n [(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]\n Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ...\n\n >>> pd.qcut(range(5), 3, labels=[\"good\", \"medium\", \"bad\"])\n ... # doctest: +SKIP\n [good, good, medium, bad, bad]\n Categories (3, object): [good < medium < bad]\n\n >>> pd.qcut(range(5), 4, labels=False)\n array([0, 0, 1, 2, 3])\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) dtype = np.dtype('timedelta64[ns]') if dtype is not None: # GH 19768: force NaT to NaN during integer conversion x = np.where(x.notna(), x.view(np.int64), np.nan) return x, dtype
[ "\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: raise ValueError("bins must be of timedelta64 dtype") elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype): if bins_dtype in ['datetime', 'datetime64']: bins = to_datetime(bins).view(np.int64) else: raise ValueError("bins must be of datetime64 dtype") return bins
[ "\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.astype(np.int64), dtype=dtype) return bins
[ "\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 - Timedelta('1ns') elif is_datetime64_dtype(dtype): formatter = Timestamp adjust = lambda x: x - Timedelta('1ns') elif is_timedelta64_dtype(dtype): formatter = Timedelta adjust = lambda x: x - Timedelta('1ns') else: precision = _infer_precision(precision, bins) formatter = lambda x: _round_frac(x, precision) adjust = lambda x: x - 10 ** (-precision) breaks = [formatter(b) for b in bins] labels = IntervalIndex.from_breaks(breaks, closed=closed) if right and include_lowest: # we will adjust the left hand side by precision to # account that we are all right closed v = adjust(labels[0].left) i = IntervalIndex([Interval(v, labels[0].right, closed='right')]) labels = i.append(labels[1:]) return labels
[ " 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 strip away a Pandas data-type here (e.g. datetimetz) ndim = getattr(x, 'ndim', None) if ndim is None: x = np.asarray(x) if x.ndim != 1: raise ValueError("Input array must be 1 dimensional") return x_is_series, series_index, name, x
[ "\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(bins, dtype) return fac, bins
[ "\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 return np.around(x, digits)
[ "\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 'ascii' in encoding.lower(): try: encoding = locale.getpreferredencoding() except Exception: pass # when all else fails. this will usually be "ascii" if not encoding or 'ascii' in encoding.lower(): encoding = sys.getdefaultencoding() # GH#3360, save the reported defencoding at import time # MPL backends may change it. Make available for debugging. if not _initial_defencoding: _initial_defencoding = sys.getdefaultencoding() return encoding
[ "\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_count actual_arg_count = len(args) + max_fname_arg_count argument = 'argument' if max_arg_count == 1 else 'arguments' raise TypeError( "{fname}() takes at most {max_arg} {argument} " "({given_arg} given)".format( fname=fname, max_arg=max_arg_count, argument=argument, given_arg=actual_arg_count))
[ "\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 = arg_val_dict[key] v2 = compat_args[key] # check for None-ness otherwise we could end up # comparing a numpy array vs None if (v1 is not None and v2 is None) or \ (v1 is None and v2 is not None): match = False else: match = (v1 == v2) if not is_bool(match): raise ValueError("'match' is not a boolean") # could not compare them directly, so try comparison # using the 'is' operator except ValueError: match = (arg_val_dict[key] is compat_args[key]) if not match: raise ValueError(("the '{arg}' parameter is not " "supported in the pandas " "implementation of {fname}()". format(fname=fname, arg=key)))
[ "\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 in the pandas implementation of 'fname' kwargs = dict(zip(compat_args, args)) _check_for_default_values(fname, kwargs, compat_args)
[ "\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: tuple\n The `*args` parameter passed into a function\n\n max_fname_arg_count: int\n The maximum number of arguments that the function `fname`\n can accept, excluding those in `args`. Used for displaying\n appropriate error messages. Must be non-negative.\n\n compat_args: OrderedDict\n A ordered dictionary of keys and their associated default values.\n In order to accommodate buggy behaviour in some versions of `numpy`,\n where a signature displayed keyword arguments but then passed those\n arguments **positionally** internally when calling downstream\n implementations, an ordered dictionary ensures that the original\n order of the keyword arguments is enforced. Note that if there is\n only one key, a generic dict can be passed in as well.\n\n Raises\n ------\n TypeError if `args` contains more values than there are `compat_args`\n ValueError if `args` contains values that do not correspond to those\n of the default values specified in `compat_args`\n\n " ]
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 " "keyword argument '{arg}'". format(fname=fname, arg=bad_arg)))
[ "\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` parameter\n\n kwargs: dict\n The `**kwargs` parameter passed into `fname`\n\n compat_args: dict\n A dictionary of keys that `kwargs` is allowed to have and their\n associated default values\n\n Raises\n ------\n TypeError if `kwargs` contains keys not in `compat_args`\n ValueError if `kwargs` contains keys in `compat_args` that do not\n map to the default values specified in `compat_args`\n\n " ]
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 _check_arg_length(fname, args + tuple(kwargs.values()), max_fname_arg_count, compat_args) # Check there is no overlap with the positional and keyword # arguments, similar to what is done in actual Python functions args_dict = dict(zip(compat_args, args)) for key in args_dict: if key in kwargs: raise TypeError("{fname}() got multiple values for keyword " "argument '{arg}'".format(fname=fname, arg=key)) kwargs.update(args_dict) validate_kwargs(fname, kwargs, 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 `**kwargs` parameter\n\n args: tuple\n The `*args` parameter passed into a function\n\n kwargs: dict\n The `**kwargs` parameter passed into `fname`\n\n max_fname_arg_count: int\n The minimum number of arguments that the function `fname`\n requires, excluding those in `args`. Used for displaying\n appropriate error messages. Must be non-negative.\n\n compat_args: OrderedDict\n A ordered dictionary of keys that `kwargs` is allowed to\n have and their associated default values. Note that if there\n is only one key, a generic dict can be passed in as well.\n\n Raises\n ------\n TypeError if `args` contains more values than there are\n `compat_args` OR `kwargs` contains keys not in `compat_args`\n ValueError if `args` contains values not at the default value (`None`)\n `kwargs` contains keys in `compat_args` that do not map to the default\n value as specified in `compat_args`\n\n See Also\n --------\n validate_args : Purely args validation.\n validate_kwargs : Purely kwargs validation.\n\n " ]
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, typ=type(value).__name__)) return value
[ " 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 validating for consistency if 'axis' in kwargs and any(x in kwargs for x in data._AXIS_NUMBERS): msg = "Cannot specify both 'axis' and any of 'index' or 'columns'." raise TypeError(msg) # First fill with explicit values provided by the user... if arg_name in kwargs: if args: msg = ("{} got multiple values for argument " "'{}'".format(method_name, arg_name)) raise TypeError(msg) axis = data._get_axis_name(kwargs.get('axis', 0)) out[axis] = kwargs[arg_name] # More user-provided arguments, now from kwargs for k, v in kwargs.items(): try: ax = data._get_axis_name(k) except ValueError: pass else: out[ax] = v # All user-provided kwargs have been handled now. # Now we supplement with positional arguments, emitting warnings # when there's ambiguity and raising when there's conflicts if len(args) == 0: pass # It's up to the function to decide if this is valid elif len(args) == 1: axis = data._get_axis_name(kwargs.get('axis', 0)) out[axis] = args[0] elif len(args) == 2: if 'axis' in kwargs: # Unambiguously wrong msg = ("Cannot specify both 'axis' and any of 'index' " "or 'columns'") raise TypeError(msg) msg = ("Interpreting call\n\t'.{method_name}(a, b)' as " "\n\t'.{method_name}(index=a, columns=b)'.\nUse named " "arguments to remove any ambiguity. In the future, using " "positional arguments for 'index' or 'columns' will raise " " a 'TypeError'.") warnings.warn(msg.format(method_name=method_name,), FutureWarning, stacklevel=4) out[data._AXIS_NAMES[0]] = args[0] out[data._AXIS_NAMES[1]] = args[1] else: msg = "Cannot specify all of '{}', 'index', 'columns'." raise TypeError(msg.format(arg_name)) return out
[ "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 data : DataFrame or Panel\n args : tuple\n All positional arguments from the user\n kwargs : dict\n All keyword arguments from the user\n arg_name, method_name : str\n Used for better error messages\n\n Returns\n -------\n kwargs : dict\n A dictionary of keyword arguments. Doesn't modify ``kwargs``\n inplace, so update them with the return value here.\n\n Examples\n --------\n >>> df._validate_axis_style_args((str.upper,), {'columns': id},\n ... 'mapper', 'rename')\n {'columns': <function id>, 'index': <method 'upper' of 'str' objects>}\n\n This emits a warning\n >>> df._validate_axis_style_args((str.upper, id), {},\n ... 'mapper', 'rename')\n {'columns': <function id>, 'index': <method 'upper' of 'str' objects>}\n " ]
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 method is not None: method = clean_fill_method(method) elif value is not None and method is None: if validate_scalar_dict_value and isinstance(value, (list, tuple)): raise TypeError('"value" parameter must be a scalar or dict, but ' 'you passed a "{0}"'.format(type(value).__name__)) elif value is not None and method is not None: raise ValueError("Cannot specify both 'value' and 'method'.") return value, method
[ "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'.\n validate_scalar_dict_value : bool, default True\n Whether to validate that 'value' is a scalar or dict. Specifically,\n validate that it is not a list or tuple.\n\n Returns\n -------\n value, method : object\n " ]
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: ....) else: method = ".apply(<func>)" # if we have both a how and fill_method, then show # the following warning if fill_method is None: warnings.warn("how in .resample() is deprecated\n" "the new syntax is " ".resample(...).{method}".format( method=method), FutureWarning, stacklevel=3) r = r.aggregate(how) if fill_method is not None: # show the prior function call method = '.' + method if how is not None else '' args = "limit={0}".format(limit) if limit is not None else "" warnings.warn("fill_method is deprecated to .resample()\n" "the new syntax is .resample(...){method}" ".{fill_method}({args})".format( method=method, fill_method=fill_method, args=args), FutureWarning, stacklevel=3) if how is not None: r = getattr(r, fill_method)(limit=limit) else: r = r.aggregate(fill_method, limit=limit) return r
[ "\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=rule, **kwargs) resampler = tg._get_resampler(groupby.obj, kind=kind) r = resampler._get_resampler_for_grouping(groupby=groupby) return _maybe_process_deprecations(r, how=how, fill_method=fill_method, limit=limit)
[ "\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, 24H, or 25H). # So "pretend" the dates are naive when adjusting the endpoints tz = first.tz first = first.tz_localize(None) last = last.tz_localize(None) first, last = _adjust_dates_anchored(first, last, offset, closed=closed, base=base) if isinstance(offset, Day): first = first.tz_localize(tz) last = last.tz_localize(tz) return first, last else: first = first.normalize() last = last.normalize() if closed == 'left': first = Timestamp(offset.rollback(first)) else: first = Timestamp(first - offset) last = Timestamp(last + offset) return first, last
[ "\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 the `closed` parameter.\n\n Parameters\n ----------\n first : pd.Timestamp\n The beginning Timestamp of the range to be adjusted.\n last : pd.Timestamp\n The ending Timestamp of the range to be adjusted.\n offset : pd.DateOffset\n The dateoffset to which the Timestamps will be adjusted.\n closed : {'right', 'left'}, default None\n Which side of bin interval is closed.\n base : int, default 0\n The \"origin\" of the adjusted Timestamps.\n\n Returns\n -------\n A tuple of length 2, containing the adjusted pd.Timestamp objects.\n " ]
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() last = last.to_timestamp() adjust_first = not offset.onOffset(first) adjust_last = offset.onOffset(last) first, last = _get_timestamp_range_edges(first, last, offset, closed=closed, base=base) first = (first + adjust_first * offset).to_period(offset) last = (last - adjust_last * offset).to_period(offset) return first, last
[ "\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 adjusted.\n offset : pd.DateOffset\n The dateoffset to which the Periods will be adjusted.\n closed : {'right', 'left'}, default None\n Which side of bin interval is closed.\n base : int, default 0\n The \"origin\" of the adjusted Periods.\n\n Returns\n -------\n A tuple of length 2, containing the adjusted pd.Period objects.\n " ]
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 = 'E' new_obj = obj.copy() new_obj.index = obj.index.asfreq(freq, how=how) elif len(obj.index) == 0: new_obj = obj.copy() new_obj.index = obj.index._shallow_copy(freq=to_offset(freq)) else: dti = date_range(obj.index[0], obj.index[-1], freq=freq) dti.name = obj.index.name new_obj = obj.reindex(dti, method=method, fill_value=fill_value) if normalize: new_obj.index = new_obj.index.normalize() return new_obj
[ "\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 self.groupby.level is not None))
[ "\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 transformed : Series\n\n Examples\n --------\n >>> resampled.transform(lambda x: (x - x.mean()) / x.std())\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 selection try: return grouped[key] except KeyError: return grouped
[ "\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.axis) try: if isinstance(obj, ABCDataFrame) and callable(how): # Check if the function is reducing or not. result = grouped._aggregate_item_by_item(how, *args, **kwargs) else: result = grouped.aggregate(how, *args, **kwargs) except Exception: # we have a non-reducing function # try to evaluate result = grouped.apply(how, *args, **kwargs) result = self._apply_loffset(result) return self._wrap_result(result)
[ "\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) > 0 ) if needs_offset: result.index = result.index + self.loffset self.loffset = None return result
[ "\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.index, PeriodIndex): result.index = obj.index.asfreq(self.freq) else: result.index = obj.index._shallow_copy(freq=self.freq) result.name = getattr(obj, 'name', None) return result
[ "\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=method, axis=axis, limit=limit, inplace=inplace, limit_direction=limit_direction, limit_area=limit_area, downcast=downcast, **kwargs)
[ "\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) result = self._groupby.apply(func) return self._wrap_result(result)
[ "\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() obj.index.freq = self.freq return obj # do we have a regular frequency if ax.freq is not None or ax.inferred_freq is not None: if len(self.grouper.binlabels) > len(ax) and how is None: # let's do an asfreq return self.asfreq() # we are downsampling # we want to call the actual grouper method here result = obj.groupby( self.grouper, axis=self.axis).aggregate(how, **kwargs) result = self._apply_loffset(result) return self._wrap_result(result)
[ "\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" " is not supported, use .set_index(...)" " to explicitly set index to" " datetime-like") ax = self.ax obj = self._selected_obj binner = self.binner res_index = self._adjust_binner_for_upsample(binner) # if we have the same frequency as our axis, then we are equal sampling if limit is None and to_offset(ax.inferred_freq) == self.freq: result = obj.copy() result.index = res_index else: result = obj.reindex(res_index, method=method, limit=limit, fill_value=fill_value) result = self._apply_loffset(result) return self._wrap_result(result)
[ "\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 missing values\n\n See Also\n --------\n .fillna\n\n " ]
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 if is_subperiod(ax.freq, self.freq): # Downsampling return self._groupby_and_aggregate(how, grouper=self.grouper, **kwargs) elif is_superperiod(ax.freq, self.freq): if how == 'ohlc': # GH #13083 # upsampling to subperiods is handled as an asfreq, which works # for pure aggregating/reducing methods # OHLC reduces along the time dimension, but creates multiple # values for each period -> handle by _groupby_and_aggregate() return self._groupby_and_aggregate(how, grouper=self.grouper) return self.asfreq() elif ax.freq == self.freq: return self.asfreq() raise IncompatibleFrequency( 'Frequency {} cannot be resampled to {}, as they are not ' 'sub or super periods'.format(ax.freq, self.freq))
[ "\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_value=fill_value) self._set_binner() ax = self.ax obj = self.obj new_index = self.binner # Start vs. end of period memb = ax.asfreq(self.freq, how=self.convention) # Get the fill indexer indexer = memb.get_indexer(new_index, method=method, limit=limit) return self._wrap_result(_take_new_index( obj, indexer, new_index, axis=self.axis))
[ "\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\n\n See Also\n --------\n .fillna\n\n " ]
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, kind=kind, axis=self.axis) elif isinstance(ax, PeriodIndex) or kind == 'period': return PeriodIndexResampler(obj, groupby=self, kind=kind, axis=self.axis) elif isinstance(ax, TimedeltaIndex): return TimedeltaIndexResampler(obj, groupby=self, axis=self.axis) raise TypeError("Only valid with DatetimeIndex, " "TimedeltaIndex or PeriodIndex, " "but got an instance of %r" % type(ax).__name__)
[ "\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 ------\n TypeError if incompatible axis\n\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(hash_tuples(obj, encoding, hash_key), dtype='uint64', copy=False) if isinstance(obj, ABCIndexClass): h = hash_array(obj.values, encoding, hash_key, categorize).astype('uint64', copy=False) h = Series(h, index=obj, dtype='uint64', copy=False) elif isinstance(obj, ABCSeries): h = hash_array(obj.values, encoding, hash_key, categorize).astype('uint64', copy=False) if index: index_iter = (hash_pandas_object(obj.index, index=False, encoding=encoding, hash_key=hash_key, categorize=categorize).values for _ in [None]) arrays = itertools.chain([h], index_iter) h = _combine_hash_arrays(arrays, 2) h = Series(h, index=obj.index, dtype='uint64', copy=False) elif isinstance(obj, ABCDataFrame): hashes = (hash_array(series.values) for _, series in obj.iteritems()) num_items = len(obj.columns) if index: index_hash_generator = (hash_pandas_object(obj.index, index=False, encoding=encoding, hash_key=hash_key, categorize=categorize).values # noqa for _ in [None]) num_items += 1 hashes = itertools.chain(hashes, index_hash_generator) h = _combine_hash_arrays(hashes, num_items) h = Series(h, index=obj.index, dtype='uint64', copy=False) else: raise TypeError("Unexpected type for hashing %s" % type(obj)) return h
[ "\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 : string key to encode, default to _default_hash_key\n categorize : bool, default True\n Whether to first categorize object arrays before hashing. This is more\n efficient when the array contains duplicate values.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n Series of uint64, same length as the object\n " ]
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 import Categorical, MultiIndex if not isinstance(vals, ABCMultiIndex): vals = MultiIndex.from_tuples(vals) # create a list-of-Categoricals vals = [Categorical(vals.codes[level], vals.levels[level], ordered=False, fastpath=True) for level in range(vals.nlevels)] # hash the list-of-ndarrays hashes = (_hash_categorical(cat, encoding=encoding, hash_key=hash_key) for cat in vals) h = _combine_hash_arrays(hashes, len(vals)) if is_tuple: h = h[0] return h
[ "\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 ndarray of hashed values array\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 support missing values # we don't want to use take_nd which will coerce to float # instead, directly construct the result with a # max(np.uint64) as the missing value indicator # # TODO: GH 15362 mask = c.isna() if len(hashed): result = hashed.take(c.codes) else: result = np.zeros(len(mask), dtype='uint64') if mask.any(): result[mask] = np.iinfo(np.uint64).max return result
[ "\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 values array, same size as len(c)\n " ]
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, we hash the categories, then remap the codes to the # hash values. (This check is above the complex check so that we don't ask # numpy if categorical is a subdtype of complex, as it will choke). if is_categorical_dtype(dtype): return _hash_categorical(vals, encoding, hash_key) elif is_extension_array_dtype(dtype): vals, _ = vals._values_for_factorize() dtype = vals.dtype # we'll be working with everything as 64-bit values, so handle this # 128-bit value early if np.issubdtype(dtype, np.complex128): return hash_array(vals.real) + 23 * hash_array(vals.imag) # First, turn whatever array this is into unsigned 64-bit ints, if we can # manage it. elif isinstance(dtype, np.bool): vals = vals.astype('u8') elif issubclass(dtype.type, (np.datetime64, np.timedelta64)): vals = vals.view('i8').astype('u8', copy=False) elif issubclass(dtype.type, np.number) and dtype.itemsize <= 8: vals = vals.view('u{}'.format(vals.dtype.itemsize)).astype('u8') else: # With repeated values, its MUCH faster to categorize object dtypes, # then hash and rename categories. We allow skipping the categorization # when the values are known/likely to be unique. if categorize: from pandas import factorize, Categorical, Index codes, categories = factorize(vals, sort=False) cat = Categorical(codes, Index(categories), ordered=False, fastpath=True) return _hash_categorical(cat, encoding, hash_key) try: vals = hashing.hash_object_array(vals, hash_key, encoding) except TypeError: # we have mixed types vals = hashing.hash_object_array(vals.astype(str).astype(object), hash_key, encoding) # Then, redistribute these 64-bit ints within the space of 64-bit ints vals ^= vals >> 30 vals *= np.uint64(0xbf58476d1ce4e5b9) vals ^= vals >> 27 vals *= np.uint64(0x94d049bb133111eb) vals ^= vals >> 31 return vals
[ "\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_key\n categorize : bool, default True\n Whether to first categorize object arrays before hashing. This is more\n efficient when the array contains duplicate values.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n 1d uint64 numpy array of hash values, same length as the vals\n " ]
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: # for tz-aware datetimes, we need the underlying naive UTC value and # not the tz aware object or pd extension type (as # infer_dtype_from_scalar would do) if not isinstance(val, tslibs.Timestamp): val = tslibs.Timestamp(val) val = val.tz_convert(None) dtype, val = infer_dtype_from_scalar(val) vals = np.array([val], dtype=dtype) return hash_array(vals, hash_key=hash_key, encoding=encoding, categorize=False)
[ "\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 else: raise FileNotFoundError('File {} not found'.format(single_doc)) elif single_doc.startswith('pandas.'): try: obj = pandas # noqa: F821 for name in single_doc.split('.'): obj = getattr(obj, name) except AttributeError: raise ImportError('Could not import {}'.format(single_doc)) else: return single_doc[len('pandas.'):] else: raise ValueError(('--single={} not understood. Value should be a ' 'valid path to a .rst or .ipynb file, or a ' 'valid pandas object (e.g. categorical.rst or ' 'pandas.DataFrame.head)').format(single_doc))
[ "\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.head.rst).\n " ]
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: cmd += ['-j', str(self.num_jobs)] if self.warnings_are_errors: cmd += ['-W', '--keep-going'] if self.verbosity: cmd.append('-{}'.format('v' * self.verbosity)) cmd += ['-d', os.path.join(BUILD_PATH, 'doctrees'), SOURCE_PATH, os.path.join(BUILD_PATH, kind)] return subprocess.call(cmd)
[ "\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( '<doc>', option_parser.get_default_values()) with open(fname) as f: data = f.read() parser = docutils.parsers.rst.Parser() # do not generate any warning when parsing the rst with open(os.devnull, 'a') as f: doc.reporter.stream = f parser.parse(data, doc) section = next(node for node in doc.children if isinstance(node, docutils.nodes.section)) title = next(node for node in section.children if isinstance(node, docutils.nodes.title)) return title.astext()
[ "\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}">{title}</a> </p> </body> <html> ''' with open(REDIRECTS_FILE) as mapping_fd: reader = csv.reader(mapping_fd) for row in reader: if not row or row[0].strip().startswith('#'): continue path = os.path.join(BUILD_PATH, 'html', *row[0].split('/')) + '.html' try: title = self._get_page_title(row[1]) except Exception: # the file can be an ipynb and not an rst, or docutils # may not be able to read the rst because it has some # sphinx specific stuff title = 'this page' if os.path.exists(path): raise RuntimeError(( 'Redirection would overwrite an existing file: ' '{}').format(path)) with open(path, 'w') as moved_page_fd: moved_page_fd.write( html.format(url='{}.html'.format(row[1]), title=title))
[ "\n Create in the build directory an html file with a redirect,\n for every row in REDIRECTS_FILE.\n " ]