text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_ordered(self, inplace=False): """ Set the Categorical to be ordered. Parameters inplace : bool, default False Whether or not to set the ordered attribute ...
inplace = validate_bool_kwarg(inplace, 'inplace') return self.set_ordered(True, inplace=inplace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_unordered(self, inplace=False): """ Set the Categorical to be unordered. Parameters inplace : bool, default False Whether or not to set the ordered attrib...
inplace = validate_bool_kwarg(inplace, 'inplace') return self.set_ordered(False, inplace=inplace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_categories(self, new_categories, ordered=None, rename=False, inplace=False): """ Set the categories to the specified new_categories. `new_categories` can...
inplace = validate_bool_kwarg(inplace, 'inplace') if ordered is None: ordered = self.dtype.ordered new_dtype = CategoricalDtype(new_categories, ordered=ordered) cat = self if inplace else self.copy() if rename: if (cat.dtype.categories is not None and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_categories(self, new_categories, inplace=False): """ Rename categories. Parameters new_categories : list-like, dict-like or callable * list-like: all ...
inplace = validate_bool_kwarg(inplace, 'inplace') cat = self if inplace else self.copy() if isinstance(new_categories, ABCSeries): msg = ("Treating Series 'new_categories' as a list-like and using " "the values. In a future version, 'rename_categories' will " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reorder_categories(self, new_categories, ordered=None, inplace=False): """ Reorder categories as specified in new_categories. `new_categories` need to includ...
inplace = validate_bool_kwarg(inplace, 'inplace') if set(self.dtype.categories) != set(new_categories): raise ValueError("items in new_categories are not the same as in " "old categories") return self.set_categories(new_categories, ordered=ordered, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_categories(self, new_categories, inplace=False): """ Add new categories. `new_categories` will be included at the last/highest place in the categories an...
inplace = validate_bool_kwarg(inplace, 'inplace') if not is_list_like(new_categories): new_categories = [new_categories] already_included = set(new_categories) & set(self.dtype.categories) if len(already_included) != 0: msg = ("new categories must not include old...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_categories(self, removals, inplace=False): """ Remove the specified categories. `removals` must be included in the old categories. Values which were i...
inplace = validate_bool_kwarg(inplace, 'inplace') if not is_list_like(removals): removals = [removals] removal_set = set(list(removals)) not_included = removal_set - set(self.dtype.categories) new_categories = [c for c in self.dtype.categories ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_unused_categories(self, inplace=False): """ Remove categories which are not used. Parameters inplace : bool, default False Whether or not to drop unus...
inplace = validate_bool_kwarg(inplace, 'inplace') cat = self if inplace else self.copy() idx, inv = np.unique(cat._codes, return_inverse=True) if idx.size != 0 and idx[0] == -1: # na sentinel idx, inv = idx[1:], inv - 1 new_categories = cat.dtype.categories.take(i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift(self, periods, fill_value=None): """ Shift Categorical by desired number of periods. Parameters periods : int Number of periods to move, can be positiv...
# since categoricals always have ndim == 1, an axis parameter # doesn't make any sense here. codes = self.codes if codes.ndim > 1: raise NotImplementedError("Categorical with ndim > 1.") if np.prod(codes.shape) and (periods != 0): codes = np.roll(codes, e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memory_usage(self, deep=False): """ Memory usage of my values Parameters deep : bool Introspect the data deeply, interrogate `object` dtypes for system-level...
return self._codes.nbytes + self.dtype.categories.memory_usage( deep=deep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_counts(self, dropna=True): """ Return a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Par...
from numpy import bincount from pandas import Series, CategoricalIndex code, cat = self._codes, self.categories ncat, mask = len(cat), 0 <= code ix, clean = np.arange(ncat), mask.all() if dropna or clean: obs = code if clean else code[mask] coun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_values(self): """ Return the values. For internal compatibility with pandas formatting. Returns ------- numpy.array A numpy array of the same dtype as ca...
# if we are a datetime and period index, return Index to keep metadata if is_datetimelike(self.categories): return self.categories.take(self._codes, fill_value=np.nan) elif is_integer_dtype(self.categories) and -1 in self._codes: return self.categories.astype("object").t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_values(self, inplace=False, ascending=True, na_position='last'): """ Sort the Categorical by category value returning a new Categorical by default. Whil...
inplace = validate_bool_kwarg(inplace, 'inplace') if na_position not in ['last', 'first']: msg = 'invalid na_position: {na_position!r}' raise ValueError(msg.format(na_position=na_position)) sorted_idx = nargsort(self, ascending=ascending, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take_nd(self, indexer, allow_fill=None, fill_value=None): """ Take elements from the Categorical. Parameters indexer : sequence of int The indices in `self` ...
indexer = np.asarray(indexer, dtype=np.intp) if allow_fill is None: if (indexer < 0).any(): warn(_take_msg, FutureWarning, stacklevel=2) allow_fill = True dtype = self.dtype if isna(fill_value): fill_value = -1 elif allow...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _slice(self, slicer): """ Return a slice of myself. For internal compatibility with numpy arrays. """
# only allow 1 dimensional slicing, but can # in a 2-d case be passd (slice(None),....) if isinstance(slicer, tuple) and len(slicer) == 2: if not com.is_null_slice(slicer[0]): raise AssertionError("invalid slicing for a 1-ndim " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repr_categories(self): """ return the base repr for the categories """
max_categories = (10 if get_option("display.max_categories") == 0 else get_option("display.max_categories")) from pandas.io.formats import format as fmt if len(self.categories) > max_categories: num = max_categories // 2 head = fmt.format_array(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repr_categories_info(self): """ Returns a string representation of the footer. """
category_strs = self._repr_categories() dtype = getattr(self.categories, 'dtype_str', str(self.categories.dtype)) levheader = "Categories ({length}, {dtype}): ".format( length=len(self.categories), dtype=dtype) width, height = get_terminal_size() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_coerce_indexer(self, indexer): """ return an indexer coerced to the codes dtype """
if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i': indexer = indexer.astype(self._codes.dtype) return indexer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reverse_indexer(self): """ Compute the inverse of a categorical, returning a dict of categories -> indexers. *This is an internal function* Returns ------- ...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(self, numeric_only=None, **kwargs): """ The minimum value of the object. Only ordered `Categoricals` have a minimum! Raises ------ TypeError If the `Cate...
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[po...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique(self): """ Return the ``Categorical`` which ``categories`` and ``codes`` are unique. Unused categories are NOT returned. - unordered category: values ...
# 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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equals(self, other): """ Returns True if categorical arrays are equal. Parameters other : `Categorical` Returns ------- bool """
if self.is_dtype_equal(other): if self.categories.equals(other.categories): # fastpath to avoid re-coding other_codes = other._codes else: other_codes = _recode_for_categories(other.codes, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_dtype_equal(self, other): """ Returns True if categoricals are the same dtype same categories, and same ordered Parameters other : Categorical Returns ---...
try: return hash(self.dtype) == hash(other.dtype) except (AttributeError, TypeError): return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe(self): """ Describes this Categorical Returns ------- description: `DataFrame` A dataframe with frequency and counts by category. """
counts = self.value_counts(dropna=False) freqs = counts / float(counts.sum()) from pandas.core.reshape.concat import concat result = concat([counts, freqs], axis=1) result.columns = ['counts', 'freqs'] result.index.name = 'categories' return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isin(self, values): """ Check whether `values` are contained in Categorical. Return a boolean NumPy Array showing whether each element in the Categorical mat...
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).__...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_timedelta(arg, unit='ns', box=True, errors='raise'): """ Convert argument to timedelta. Timedeltas are absolute differences in times, expressed in differe...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'): """Convert string 'r' to a timedelta object."""
try: result = Timedelta(r, unit) if not box: # explicitly view as timedelta64 for case when result is pd.NaT result = result.asm8.view('timedelta64[ns]') except ValueError: if errors == 'raise': raise elif errors == 'ignore': retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None): """Convert a list of objects to a timedelta index object."""
if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'): # This is needed only to ensure that in the case where we end up # returning arg (errors == "ignore"), and where the input is a # generator, we return a useful list-like instead of a # used-up generator arg ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_range(start=None, end=None, periods=None, offset=BDay()): """ Generates a sequence of dates corresponding to the specified time offset. Similar to d...
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 p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_index(self, i): """ Vectorized apply of DateOffset to DatetimeIndex, raises NotImplentedError for offsets without a vectorized implementation. Paramete...
if type(self) is not DateOffset: raise NotImplementedError("DateOffset subclass {name} " "does not have a vectorized " "implementation".format( name=self.__class__.__name__)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_bday(self): """ Used for moving to next business day. """
if self.n >= 0: nb_offset = 1 else: nb_offset = -1 if self._prefix.startswith('C'): # CustomBusinessHour return CustomBusinessDay(n=nb_offset, weekmask=self.weekmask, holida...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_opening_time(self, other): """ If n is positive, return tomorrow's business day opening time. Otherwise yesterday's business day's opening time. Openin...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_business_hours_by_sec(self): """ Return business hours in a day by seconds. """
if self._get_daytime_flag: # create dummy datetime to calculate businesshours in a day dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute) until = datetime(2014, 4, 1, self.end.hour, self.end.minute) return (until - dtstart).total_seconds() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _onOffset(self, dt, businesshours): """ Slight speedups using calculated values. """
# if self.normalize and not _is_normalized(dt): # return False # Valid BH can be on the different BusinessDay during midnight # Distinguish by the time spent from previous opening time if self.n >= 0: op = self._prev_opening_time(dt) else: op ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_index_days(self, i, roll): """ Add days portion of offset to DatetimeIndex i. Parameters i : DatetimeIndex roll : ndarray[int64_t] Returns ------- res...
nanos = (roll % 2) * Timedelta(days=self.day_of_month - 1).value return i + nanos.astype('timedelta64[ns]')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _end_apply_index(self, dtindex): """ Add self to the given DatetimeIndex, specialized for case where self.weekday is non-null. Parameters dtindex : DatetimeI...
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 sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_offset_day(self, other): """ Find the day in the same month as other that has the same weekday as self.weekday and is the self.week'th such day in the m...
mstart = datetime(other.year, other.month, 1) wday = mstart.weekday() shift_days = (self.weekday - wday) % 7 return 1 + shift_days + self.week * 7
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_offset_day(self, other): """ Find the day in the same month as other that has the same weekday as self.weekday and is the last such day in the month. Pa...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rollback_to_year(self, other): """ Roll `other` back to the most recent date that was on a fiscal year end. Return the date of that year-end, the number of ...
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 co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_concat_axis(self): """ Return index to be used along concatenation axis. """
if self._is_series: if self.axis == 0: indexes = [x.index for x in self.objs] elif self.ignore_index: idx = ibase.default_index(len(self.objs)) return idx elif self.keys is None: names = [None] * len(self.objs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _in(x, y): """Compute the vectorized membership of ``x in y`` if possible, otherwise use Python. """
try: return x.isin(y) except AttributeError: if is_list_like(x): try: return y.isin(x) except AttributeError: pass return x in y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _not_in(x, y): """Compute the vectorized membership of ``x not in y`` if possible, otherwise use Python. """
try: return ~x.isin(y) except AttributeError: if is_list_like(x): try: return ~y.isin(x) except AttributeError: pass return x not in y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cast_inplace(terms, acceptable_dtypes, dtype): """Cast an expression inplace. Parameters terms : Op The expression that should cast. acceptable_dtypes : lis...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_values(self): """Convert datetimes to a comparable value in an expression. """
def stringify(value): if self.encoding is not None: encoder = partial(pprint_thing_encoded, encoding=self.encoding) else: encoder = pprint_thing return encoder(value) lhs, rhs = self.lhs, self.rhs ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shape(self, df): """ Calculate table chape considering index levels. """
row, col = df.shape return row + df.columns.nlevels, col + df.index.nlevels
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_cells(self, left, right, vertical): """ Calculate appropriate figure size based on left and right data. """
if vertical: # calculate required number of cells vcells = max(sum(self._shape(l)[0] for l in left), self._shape(right)[0]) hcells = (max(self._shape(l)[1] for l in left) + self._shape(right)[1]) else: vcell...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _conv(self, data): """Convert each input to appropriate for table outplot"""
if isinstance(data, pd.Series): if data.name is None: data = data.to_frame(name='') else: data = data.to_frame() data = data.fillna('NaN') return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise'): """ Bin values into discrete intervals. Use `cut...
# 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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'): """ Quantile-based discretization function. Discretize variable into equal-sized buc...
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, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_bin_to_datelike_type(bins, dtype): """ Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is datelike Parameters bins : list-lik...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_labels(bins, precision, right=True, include_lowest=False, dtype=None): """ based on the dtype, return our labels """
closed = 'right' if right else 'left' if is_datetime64tz_dtype(dtype): formatter = partial(Timestamp, tz=dtype.tz) adjust = lambda x: x - Timedelta('1ns') elif is_datetime64_dtype(dtype): formatter = Timestamp adjust = lambda x: x - Timedelta('1ns') elif is_timedelta64...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _preprocess_for_cut(x): """ handles preprocessing for cut where we convert passed input to array, strip the index information and store it separately """
x_is_series = isinstance(x, Series) series_index = None name = None if x_is_series: series_index = x.index 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, 'ndi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype): """ handles post processing for the cut method where we combine the index i...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _round_frac(x, precision): """ Round the fractional part of the given number """
if not np.isfinite(x) or x == 0: return x else: frac, whole = np.modf(x) if whole == 0: digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision else: digits = precision return np.around(x, digits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _infer_precision(base_precision, bins): """Infer an appropriate precision for _round_frac """
for precision in range(base_precision, 20): levels = [_round_frac(b, precision) for b in bins] if algos.unique(levels).size == bins.size: return precision return base_precision
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_console_encoding(): """ Try to find the most capable encoding supported by the console. slightly modified from the way IPython handles the same issue....
global _initial_defencoding encoding = None try: encoding = sys.stdout.encoding or sys.stdin.encoding except (AttributeError, IOError): pass # try again for something better if not encoding or 'ascii' in encoding.lower(): try: encoding = locale.getpreferred...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_arg_length(fname, args, max_fname_arg_count, compat_args): """ Checks whether 'args' has length of at most 'compat_args'. Raises a TypeError if that i...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_for_default_values(fname, arg_val_dict, compat_args): """ Check that the keys in `arg_val_dict` are mapped to their default values as specified in `co...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_for_invalid_keys(fname, kwargs, compat_args): """ Checks whether 'kwargs' contains any keys that are not in 'compat_args' and raises a TypeError if th...
# 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)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_bool_kwarg(value, arg_name): """ Ensures that argument passed in arg_name is of type bool. """
if not (is_bool(value) or value is None): raise ValueError('For argument "{arg}" expected type bool, received ' 'type {typ}.'.format(arg=arg_name, typ=type(value).__name__)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True): """Validate the keyword arguments to 'fillna'. This checks that exactly one of 'value...
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 valid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_process_deprecations(r, how=None, fill_method=None, limit=None): """ Potentially we might have a deprecation warning, show it but call the appropriate...
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 followi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(obj, kind=None, **kwds): """ Create a TimeGrouper and return our resampler. """
tg = TimeGrouper(**kwds) return tg._get_resampler(obj, kind=kind)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None, limit=None, kind=None, **kwargs): """ Return our appropriate resampler when grouping as...
# .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, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_timestamp_range_edges(first, last, offset, closed='left', base=0): """ Adjust the `first` Timestamp to the preceeding Timestamp that resides on the prov...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_period_range_edges(first, last, offset, closed='left', base=0): """ Adjust the provided `first` and `last` Periods to the respective Period of the given...
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _from_selection(self): """ Is the resampling from a DataFrame column or MultiIndex level. """
# upsampling and PeriodIndex resampling do not work # with selection, this state used to catch and raise an error return (self.groupby is not None and (self.groupby.key is not None or self.groupby.level is not None))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_binner(self): """ Setup our binners. Cache these as we are an immutable object """
if self.binner is None: self.binner, self.grouper = self._get_binner()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, arg, *args, **kwargs): """ Call function producing a like-indexed Series on each group and return a Series with the transformed values. Param...
return self._selected_obj.groupby(self.groupby).transform( arg, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs): """ Re-evaluate the obj with a groupby aggregation. """
if grouper is None: self._set_binner() grouper = self.grouper obj = self._selected_obj grouped = groupby(obj, by=None, grouper=grouper, axis=self.axis) try: if isinstance(obj, ABCDataFrame) and callable(how): # Check if the functio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_loffset(self, result): """ If loffset is set, offset the result index. This is NOT an idempotent routine, it will be applied exactly once to the resul...
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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_resampler_for_grouping(self, groupby, **kwargs): """ Return the correct class for resampling with groupby. """
return self._resampler_for_grouping(self, groupby=groupby, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_result(self, result): """ Potentially wrap any results. """
if isinstance(result, ABCSeries) and self._selection is not None: result.name = self._selection if isinstance(result, ABCSeries) and result.empty: obj = self.obj if isinstance(obj.index, PeriodIndex): result.index = obj.index.asfreq(self.freq) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply(self, f, grouper=None, *args, **kwargs): """ Dispatch to _upsample; we are stripping all of the _upsample kwargs and performing the original function ...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _adjust_binner_for_upsample(self, binner): """ Adjust our binner when upsampling. The range of a new index should not be outside specified range """
if self.closed == 'right': binner = binner[1:] else: binner = binner[:-1] return binner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_resampler(self, obj, kind=None): """ Return my resampler or raise if we have an invalid axis. Parameters obj : input object kind : string, optional 'per...
self._set_grouper(obj) ax = self.ax if isinstance(ax, DatetimeIndex): return DatetimeIndexResampler(obj, groupby=self, kind=kind, axis=self.axis) el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash_tuple(val, encoding='utf8', hash_key=None): """ Hash a single tuple efficiently Parameters val : single tuple encoding : string, default 'utf8' hash_key...
hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key) for v in val) h = _combine_hash_arrays(hashes, len(val))[0] return h
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hash_categorical(c, encoding, hash_key): """ Hash a Categorical by hashing its categories, and then mapping the codes to the hashes Parameters c : Categoric...
# 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 # ins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): """ Given a 1d array, return an array of deterministic integers. .. versionadded:: 0.19.2 ...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hash_scalar(val, encoding='utf8', hash_key=None): """ Hash scalar value Returns ------- 1d uint64 numpy array of hash value, of length 1 """
if isna(val): # this is to be consistent with the _hash_categorical implementation return np.array([np.iinfo(np.uint64).max], 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_os(*args): """ Execute a command as a OS terminal. Parameters *args : list of str Command and parameters to be executed Examples -------- """
subprocess.check_call(args, stdout=sys.stdout, stderr=sys.stderr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sphinx_build(self, kind): """ Call sphinx to build documentation. Attribute `num_jobs` from the class is used. Parameters kind : {'html', 'latex'} Examples ...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open_browser(self, single_doc_html): """ Open a browser tab showing single """
url = os.path.join('file://', DOC_PATH, 'build', 'html', single_doc_html) webbrowser.open(url, new=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_page_title(self, page): """ Open the rst file `page` and extract its title. """
fname = os.path.join(SOURCE_PATH, '{}.rst'.format(page)) option_parser = docutils.frontend.OptionParser( components=(docutils.parsers.rst.Parser,)) doc = docutils.utils.new_document( '<doc>', option_parser.get_default_values()) with open(fname) as f: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html(self): """ Build HTML documentation. """
ret_code = self._sphinx_build('html') zip_fname = os.path.join(BUILD_PATH, 'html', 'pandas.zip') if os.path.exists(zip_fname): os.remove(zip_fname) if self.single_doc_html is not None: self._open_browser(self.single_doc_html) else: self._add_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latex(self, force=False): """ Build PDF documentation. """
if sys.platform == 'win32': sys.stderr.write('latex build has not been tested on windows\n') else: ret_code = self._sphinx_build('latex') os.chdir(os.path.join(BUILD_PATH, 'latex')) if force: for i in range(3): self._ru...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(): """ Clean documentation generated files. """
shutil.rmtree(BUILD_PATH, ignore_errors=True) shutil.rmtree(os.path.join(SOURCE_PATH, 'reference', 'api'), ignore_errors=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zip_html(self): """ Compress HTML documentation into a zip file. """
zip_fname = os.path.join(BUILD_PATH, 'html', 'pandas.zip') if os.path.exists(zip_fname): os.remove(zip_fname) dirname = os.path.join(BUILD_PATH, 'html') fnames = os.listdir(dirname) os.chdir(dirname) self._run_os('zip', zip_fname, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_multicolumn(self, row, ilevels): r""" Combine columns belonging to a group to a single multicolumn entry according to self.multicolumn_format e.g.: a...
row2 = list(row[:ilevels]) ncol = 1 coltext = '' def append_col(): # write multicolumn if needed if ncol > 1: row2.append('\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}' .format(ncol=ncol, fmt=self.multicolumn_format...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_multirow(self, row, ilevels, i, rows): r""" Check following rows, whether row should be a multirow e.g.: becomes: a & 0 & \multirow{2}{*}{a} & 0 & & ...
for j in range(ilevels): if row[j].strip(): nrow = 1 for r in rows[i + 1:]: if not r[j].strip(): nrow += 1 else: break if nrow > 1: # overwrite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_cline(self, buf, i, icol): """ Print clines after multirow-blocks are finished """
for cl in self.clinebuf: if cl[0] == i: buf.write('\\cline{{{cl:d}-{icol:d}}}\n' .format(cl=cl[1], icol=icol)) # remove entries that have been written to buffer self.clinebuf = [x for x in self.clinebuf if x[0] != i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_integer(name, val, min_val=0): """ Checks whether the 'name' parameter for parsing is either an integer OR float that can SAFELY be cast to an inte...
msg = "'{name:s}' must be an integer >={min_val:d}".format(name=name, min_val=min_val) if val is not None: if is_float(val): if int(val) != val: raise ValueError(msg) val = int(val) elif not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_names(names): """ Check if the `names` parameter contains duplicates. If duplicates are found, we issue a warning before returning. Parameters name...
if names is not None: if len(names) != len(set(names)): msg = ("Duplicate names specified. This " "will raise an error in the future.") warnings.warn(msg, UserWarning, stacklevel=3) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read(filepath_or_buffer: FilePathOrBuffer, kwds): """Generic reader of line files."""
encoding = kwds.get('encoding', None) if encoding is not None: encoding = re.sub('_', '-', encoding).lower() kwds['encoding'] = encoding compression = kwds.get('compression', 'infer') compression = _infer_compression(filepath_or_buffer, compression) # TODO: get_filepath_or_buffer ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_fwf(filepath_or_buffer: FilePathOrBuffer, colspecs='infer', widths=None, infer_nrows=100, **kwds): r""" Read a table of fixed-width formatted lines into...
# Check input arguments. if colspecs is None and widths is None: raise ValueError("Must specify either colspecs or widths") elif colspecs not in (None, 'infer') and widths is not None: raise ValueError("You must specify only one of 'widths' and " "'colspecs'") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_potential_multi_index(columns): """ Check whether or not the `columns` parameter could be converted into a MultiIndex. Parameters columns : array-like Ob...
return (len(columns) and not isinstance(columns, MultiIndex) and all(isinstance(c, tuple) for c in columns))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _evaluate_usecols(usecols, names): """ Check whether or not the 'usecols' parameter is a callable. If so, enumerates the 'names' parameter and returns a set ...
if callable(usecols): return {i for i, name in enumerate(names) if usecols(name)} return usecols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_usecols_names(usecols, names): """ Validates that all usecols are present in a given list of names. If not, raise a ValueError that shows what usec...
missing = [c for c in usecols if c not in names] if len(missing) > 0: raise ValueError( "Usecols do not match columns, " "columns expected but not found: {missing}".format(missing=missing) ) return usecols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_usecols_arg(usecols): """ Validate the 'usecols' parameter. Checks whether or not the 'usecols' parameter contains all integers (column selection b...
msg = ("'usecols' must either be list-like of all strings, all unicode, " "all integers or a callable.") if usecols is not None: if callable(usecols): return usecols, None if not is_list_like(usecols): # see gh-20529 # # Ensure it is i...