Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def reindex(self, target, method=None, level=None, limit=None, tolerance=None): # GH6552: preserve names when reindexing to non-named target # (i.e. neither Index nor Series). preserve_names = not hasattr(target, 'name') ...
[ "\n Create index with target's values (move/add/delete values\n as necessary).\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index.\n indexer : np.ndarray or None\n Indi...
Please provide a description of the function:def _reindex_non_unique(self, target): target = ensure_index(target) indexer, missing = self.get_indexer_non_unique(target) check = indexer != -1 new_labels = self.take(indexer[check]) new_indexer = None if len(missi...
[ "\n Create a new index with target's values (move/add/delete values as\n necessary) use with non-unique Index and a possibly non-unique target.\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulti...
Please provide a description of the function:def _join_level(self, other, level, how='left', return_indexers=False, keep_order=True): from .multi import MultiIndex def _get_leaf_sorter(labels): if labels[0].size == 0: return np.empty...
[ "\n The join method *only* affects the level of the resulting\n MultiIndex. Otherwise it just exactly aligns the Index data to the\n labels of the level in the MultiIndex.\n\n If ```keep_order == True```, the order of the data indexed by the\n MultiIndex will not be changed; other...
Please provide a description of the function:def _try_convert_to_int_index(cls, data, copy, name, dtype): from .numeric import Int64Index, UInt64Index if not is_unsigned_integer_dtype(dtype): # skip int64 conversion attempt if uint-like dtype is passed, as # this could ...
[ "\n Attempt to convert an array of data into an integer index.\n\n Parameters\n ----------\n data : The data to convert.\n copy : Whether to copy the data or not.\n name : The name of the index returned.\n\n Returns\n -------\n int_index : data converte...
Please provide a description of the function:def _coerce_to_ndarray(cls, data): if not isinstance(data, (np.ndarray, Index)): if data is None or is_scalar(data): cls._scalar_data_error(data) # other iterable of some kind if not isinstance(data, (ABC...
[ "\n Coerces data to ndarray.\n\n Converts other iterables to list first and then to array.\n Does not touch ndarrays.\n\n Raises\n ------\n TypeError\n When the data passed in is a scalar.\n " ]
Please provide a description of the function:def _coerce_scalar_to_index(self, item): dtype = self.dtype if self._is_numeric_dtype and isna(item): # We can't coerce to the numeric dtype of "self" (unless # it's float) if there are NaN values in our output. d...
[ "\n We need to coerce a scalar to a compat for our index type.\n\n Parameters\n ----------\n item : scalar item to coerce\n " ]
Please provide a description of the function:def _assert_can_do_op(self, value): if not is_scalar(value): msg = "'value' must be a scalar, passed: {0}" raise TypeError(msg.format(type(value).__name__))
[ "\n Check value is valid for scalar op.\n " ]
Please provide a description of the function:def _can_hold_identifiers_and_holds_name(self, name): if self.is_object() or self.is_categorical(): return name in self return False
[ "\n Faster check for ``name in self`` when we know `name` is a Python\n identifier (e.g. in NDFrame.__getattr__, which hits this to support\n . key lookup). For indexes that can't hold identifiers (everything\n but object & categorical) we just return False.\n\n https://github.com...
Please provide a description of the function:def append(self, other): to_concat = [self] if isinstance(other, (list, tuple)): to_concat = to_concat + list(other) else: to_concat.append(other) for obj in to_concat: if not isinstance(obj, Ind...
[ "\n Append a collection of Index options together.\n\n Parameters\n ----------\n other : Index or list/tuple of indices\n\n Returns\n -------\n appended : Index\n " ]
Please provide a description of the function:def putmask(self, mask, value): values = self.values.copy() try: np.putmask(values, mask, self._convert_for_op(value)) return self._shallow_copy(values) except (ValueError, TypeError) as err: if is_object_d...
[ "\n Return a new Index of the values set with the mask.\n\n See Also\n --------\n numpy.ndarray.putmask\n " ]
Please provide a description of the function:def equals(self, other): if self.is_(other): return True if not isinstance(other, Index): return False if is_object_dtype(self) and not is_object_dtype(other): # if other is not object, use other's logic ...
[ "\n Determine if two Index objects contain the same elements.\n " ]
Please provide a description of the function:def identical(self, other): return (self.equals(other) and all((getattr(self, c, None) == getattr(other, c, None) for c in self._comparables)) and type(self) == type(other))
[ "\n Similar to equals, but check that other comparable attributes are\n also equal.\n " ]
Please provide a description of the function:def asof(self, label): try: loc = self.get_loc(label, method='pad') except KeyError: return self._na_value else: if isinstance(loc, slice): loc = loc.indices(len(self))[-1] retur...
[ "\n Return the label from the index, or, if not present, the previous one.\n\n Assuming that the index is sorted, return the passed index label if it\n is in the index, or return the previous index label if the passed one\n is not in the index.\n\n Parameters\n ----------\n...
Please provide a description of the function:def asof_locs(self, where, mask): locs = self.values[mask].searchsorted(where.values, side='right') locs = np.where(locs > 0, locs - 1, 0) result = np.arange(len(self))[mask].take(locs) first = mask.argmax() result[(locs == ...
[ "\n Find the locations (indices) of the labels from the index for\n every entry in the `where` argument.\n\n As in the `asof` function, if the label (a particular entry in\n `where`) is not in the index, the latest index label upto the\n passed label is chosen and its index return...
Please provide a description of the function:def sort_values(self, return_indexer=False, ascending=True): _as = self.argsort() if not ascending: _as = _as[::-1] sorted_index = self.take(_as) if return_indexer: return sorted_index, _as else: ...
[ "\n Return a sorted copy of the index.\n\n Return a sorted copy of the index, and optionally return the indices\n that sorted the index itself.\n\n Parameters\n ----------\n return_indexer : bool, default False\n Should the indices that would sort the index be re...
Please provide a description of the function:def argsort(self, *args, **kwargs): result = self.asi8 if result is None: result = np.array(self) return result.argsort(*args, **kwargs)
[ "\n Return the integer indices that would sort the index.\n\n Parameters\n ----------\n *args\n Passed to `numpy.ndarray.argsort`.\n **kwargs\n Passed to `numpy.ndarray.argsort`.\n\n Returns\n -------\n numpy.ndarray\n Integer ...
Please provide a description of the function:def get_value(self, series, key): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = getattr(series, '_values', series) if...
[ "\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing.\n " ]
Please provide a description of the function:def set_value(self, arr, key, value): self._engine.set_value(com.values_from_object(arr), com.values_from_object(key), value)
[ "\n Fast lookup of value from 1-dimensional ndarray.\n\n Notes\n -----\n Only use this if you know what you're doing.\n " ]
Please provide a description of the function:def get_indexer_for(self, target, **kwargs): if self.is_unique: return self.get_indexer(target, **kwargs) indexer, _ = self.get_indexer_non_unique(target, **kwargs) return indexer
[ "\n Guaranteed return of an indexer even when non-unique.\n\n This dispatches to get_indexer or get_indexer_nonunique\n as appropriate.\n " ]
Please provide a description of the function:def groupby(self, values): # TODO: if we are a MultiIndex, we can do better # that converting to tuples if isinstance(values, ABCMultiIndex): values = values.values values = ensure_categorical(values) result = val...
[ "\n Group the index labels by a given array of values.\n\n Parameters\n ----------\n values : array\n Values used to determine the groups.\n\n Returns\n -------\n groups : dict\n {group name -> group labels}\n " ]
Please provide a description of the function:def map(self, mapper, na_action=None): from .multi import MultiIndex new_values = super()._map_values(mapper, na_action=na_action) attributes = self._get_attributes_dict() # we can return a MultiIndex if new_values.size and...
[ "\n Map values using input correspondence (a dict, Series, or function).\n\n Parameters\n ----------\n mapper : function, dict, or Series\n Mapping correspondence.\n na_action : {None, 'ignore'}\n If 'ignore', propagate NA values, without passing them to the\...
Please provide a description of the function:def isin(self, values, level=None): if level is not None: self._validate_index_level(level) return algos.isin(self, values)
[ "\n Return a boolean array where the index values are in `values`.\n\n Compute boolean array of whether each index value is found in the\n passed set of values. The length of the returned boolean array matches\n the length of the index.\n\n Parameters\n ----------\n ...
Please provide a description of the function:def slice_indexer(self, start=None, end=None, step=None, kind=None): start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind) # return a slice if not is_scalar(start_slice): ...
[ "\n For an ordered or unique index, compute the slice indexer for input\n labels and step.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n ...
Please provide a description of the function:def _maybe_cast_indexer(self, key): if is_float(key) and not self.is_floating(): try: ckey = int(key) if ckey == key: key = ckey except (OverflowError, ValueError, TypeError): ...
[ "\n If we have a float key and are not a floating index, then try to cast\n to an int if equivalent.\n " ]
Please provide a description of the function:def _validate_indexer(self, form, key, kind): assert kind in ['ix', 'loc', 'getitem', 'iloc'] if key is None: pass elif is_integer(key): pass elif kind in ['iloc', 'getitem']: self._invalid_indexer...
[ "\n If we are positional indexer, validate that we have appropriate\n typed bounds must be an integer.\n " ]
Please provide a description of the function:def get_slice_bound(self, label, side, kind): assert kind in ['ix', 'loc', 'getitem', None] if side not in ('left', 'right'): raise ValueError("Invalid value for side kwarg," " must be either 'left' or 'right...
[ "\n Calculate slice bound that corresponds to given label.\n\n Returns leftmost (one-past-the-rightmost if ``side=='right'``) position\n of given label.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n...
Please provide a description of the function:def slice_locs(self, start=None, end=None, step=None, kind=None): inc = (step is None or step >= 0) if not inc: # If it's a reverse slice, temporarily swap bounds. start, end = end, start # GH 16785: If start and end...
[ "\n Compute slice locations for input labels.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, defaults None\n If None, de...
Please provide a description of the function:def delete(self, loc): return self._shallow_copy(np.delete(self._data, loc))
[ "\n Make new Index with passed location(-s) deleted.\n\n Returns\n -------\n new_index : Index\n " ]
Please provide a description of the function:def insert(self, loc, item): _self = np.asarray(self) item = self._coerce_scalar_to_index(item)._ndarray_values idx = np.concatenate((_self[:loc], item, _self[loc:])) return self._shallow_copy_with_infer(idx)
[ "\n Make new Index inserting new item at location.\n\n Follows Python list.append semantics for negative values.\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n new_index : Index\n " ]
Please provide a description of the function:def drop(self, labels, errors='raise'): arr_dtype = 'object' if self.dtype == 'object' else None labels = com.index_labels_to_array(labels, dtype=arr_dtype) indexer = self.get_indexer(labels) mask = indexer == -1 if mask.any()...
[ "\n Make new Index with passed list of labels deleted.\n\n Parameters\n ----------\n labels : array-like\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and existing labels are dropped.\n\n Returns\n -------\n dropped :...
Please provide a description of the function:def _add_comparison_methods(cls): cls.__eq__ = _make_comparison_op(operator.eq, cls) cls.__ne__ = _make_comparison_op(operator.ne, cls) cls.__lt__ = _make_comparison_op(operator.lt, cls) cls.__gt__ = _make_comparison_op(operator.gt, c...
[ "\n Add in comparison methods.\n " ]
Please provide a description of the function:def _add_numeric_methods_add_sub_disabled(cls): cls.__add__ = make_invalid_op('__add__') cls.__radd__ = make_invalid_op('__radd__') cls.__iadd__ = make_invalid_op('__iadd__') cls.__sub__ = make_invalid_op('__sub__') cls.__rsub...
[ "\n Add in the numeric add/sub methods to disable.\n " ]
Please provide a description of the function:def _add_numeric_methods_disabled(cls): cls.__pow__ = make_invalid_op('__pow__') cls.__rpow__ = make_invalid_op('__rpow__') cls.__mul__ = make_invalid_op('__mul__') cls.__rmul__ = make_invalid_op('__rmul__') cls.__floordiv__ =...
[ "\n Add in numeric methods to disable other than add/sub.\n " ]
Please provide a description of the function:def _validate_for_numeric_unaryop(self, op, opstr): if not self._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op " "{opstr} for type: {typ}" .format(opstr=opstr, typ=type(sel...
[ "\n Validate if we can perform a numeric unary operation.\n " ]
Please provide a description of the function:def _validate_for_numeric_binop(self, other, op): opstr = '__{opname}__'.format(opname=op.__name__) # if we are an inheritor of numeric, # but not actually numeric (e.g. DatetimeIndex/PeriodIndex) if not self._is_numeric_dtype: ...
[ "\n Return valid other; evaluate or raise TypeError if we are not of\n the appropriate type.\n\n Notes\n -----\n This is an internal method called by ops.\n " ]
Please provide a description of the function:def _add_numeric_methods_binary(cls): cls.__add__ = _make_arithmetic_op(operator.add, cls) cls.__radd__ = _make_arithmetic_op(ops.radd, cls) cls.__sub__ = _make_arithmetic_op(operator.sub, cls) cls.__rsub__ = _make_arithmetic_op(ops.r...
[ "\n Add in numeric methods.\n " ]
Please provide a description of the function:def _add_numeric_methods_unary(cls): def _make_evaluate_unary(op, opstr): def _evaluate_numeric_unary(self): self._validate_for_numeric_unaryop(op, opstr) attrs = self._get_attributes_dict() attrs...
[ "\n Add in numeric unary methods.\n " ]
Please provide a description of the function:def _add_logical_methods(cls): _doc = _index_shared_docs['index_all'] = dedent() _index_shared_docs['index_any'] = dedent() def _make_logical_function(name, desc, f): @Substitution(outname=name, desc=desc) ...
[ "\n Add in logical methods.\n ", "\n %(desc)s\n\n Parameters\n ----------\n *args\n These parameters will be passed to numpy.%(outname)s.\n **kwargs\n These parameters will be passed to numpy.%(outname)s.\n\n Returns\n -------\n ...
Please provide a description of the function:def _get_grouper(obj, key=None, axis=0, level=None, sort=True, observed=False, mutated=False, validate=True): group_axis = obj._get_axis(axis) # validate that the passed single level is compatible with the passed # axis of the object if...
[ "\n create and return a BaseGrouper, which is an internal\n mapping of how to create the grouper indexers.\n This may be composed of multiple Grouping objects, indicating\n multiple groupers\n\n Groupers are ultimately index mappings. They can originate as:\n index mappings, keys to columns, funct...
Please provide a description of the function:def _get_grouper(self, obj, validate=True): self._set_grouper(obj) self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key], axis=self.axis, ...
[ "\n Parameters\n ----------\n obj : the subject object\n validate : boolean, default True\n if True, validate the grouper\n\n Returns\n -------\n a tuple of binner, grouper, obj (possibly sorted)\n " ]
Please provide a description of the function:def _set_grouper(self, obj, sort=False): if self.key is not None and self.level is not None: raise ValueError( "The Grouper cannot specify both a key and a level!") # Keep self.grouper value before overriding if ...
[ "\n given an object and the specifications, setup the internal grouper\n for this particular specification\n\n Parameters\n ----------\n obj : the subject object\n sort : bool, default False\n whether the resulting grouper should be sorted\n " ]
Please provide a description of the function:def to_pickle(obj, path, compression='infer', protocol=pickle.HIGHEST_PROTOCOL): path = _stringify_path(path) f, fh = _get_handle(path, 'wb', compression=compression, is_text=False) if protocol < ...
[ "\n Pickle (serialize) object to file.\n\n Parameters\n ----------\n obj : any object\n Any python object.\n path : str\n File path where the pickled object will be stored.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n A string representing the...
Please provide a description of the function:def read_pickle(path, compression='infer'): path = _stringify_path(path) f, fh = _get_handle(path, 'rb', compression=compression, is_text=False) # 1) try standard libary Pickle # 2) try pickle_compat (older pandas version) to handle subclass changes ...
[ "\n Load pickled pandas object (or any object) from file.\n\n .. warning::\n\n Loading pickled data received from untrusted sources can be\n unsafe. See `here <https://docs.python.org/3/library/pickle.html>`__.\n\n Parameters\n ----------\n path : str\n File path where the pickled ...
Please provide a description of the function:def mask_missing(arr, values_to_mask): dtype, values_to_mask = infer_dtype_from_array(values_to_mask) try: values_to_mask = np.array(values_to_mask, dtype=dtype) except Exception: values_to_mask = np.array(values_to_mask, dtype=object) ...
[ "\n Return a masking array of same size/shape as arr\n with entries equaling any member of values_to_mask set to True\n " ]
Please provide a description of the function:def interpolate_1d(xvalues, yvalues, method='linear', limit=None, limit_direction='forward', limit_area=None, fill_value=None, bounds_error=False, order=None, **kwargs): # Treat the original, non-scipy methods first. invali...
[ "\n Logic for the 1-d interpolation. The result should be 1-d, inputs\n xvalues and yvalues will each be 1-d arrays of the same length.\n\n Bounds_error is currently hardcoded to False since non-scipy ones don't\n take it as an argument.\n " ]
Please provide a description of the function:def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None, bounds_error=False, order=None, **kwargs): try: from scipy import interpolate # TODO: Why is DatetimeIndex being imported here? from pandas im...
[ "\n Passed off to scipy.interpolate.interp1d. method is scipy's kind.\n Returns an array interpolated at new_x. Add any new methods to\n the list in _clean_interp_method.\n " ]
Please provide a description of the function:def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False): from scipy import interpolate # return the method for compat with scipy version & backwards compat method = interpolate.BPoly.from_derivatives m = method(xi, yi.reshape(-1, 1), ...
[ "\n Convenience function for interpolate.BPoly.from_derivatives.\n\n Construct a piecewise polynomial in the Bernstein basis, compatible\n with the specified values and derivatives at breakpoints.\n\n Parameters\n ----------\n xi : array_like\n sorted 1D array of x-coordinates\n yi : arr...
Please provide a description of the function:def _akima_interpolate(xi, yi, x, der=0, axis=0): from scipy import interpolate try: P = interpolate.Akima1DInterpolator(xi, yi, axis=axis) except TypeError: # Scipy earlier than 0.17.0 missing axis P = interpolate.Akima1DInterpolator...
[ "\n Convenience function for akima interpolation.\n xi and yi are arrays of values used to approximate some function f,\n with ``yi = f(xi)``.\n\n See `Akima1DInterpolator` for details.\n\n Parameters\n ----------\n xi : array_like\n A sorted list of x-coordinates, of length N.\n yi :...
Please provide a description of the function:def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None, dtype=None): transf = (lambda x: x) if axis == 0 else (lambda x: x.T) # reshape a 1 dim if needed ndim = values.ndim if values.ndim == 1: if axis !...
[ "\n Perform an actual interpolation of values, values will be make 2-d if\n needed fills inplace, returns the result.\n " ]
Please provide a description of the function:def _cast_values_for_fillna(values, dtype): # TODO: for int-dtypes we make a copy, but for everything else this # alters the values in-place. Is this intentional? if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or is_timedelta64...
[ "\n Cast values to a dtype that algos.pad and algos.backfill can handle.\n " ]
Please provide a description of the function:def fill_zeros(result, x, y, name, fill): if fill is None or is_float_dtype(result): return result if name.startswith(('r', '__r')): x, y = y, x is_variable_type = (hasattr(y, 'dtype') or hasattr(y, 'type')) is_scalar_type = is_scalar(y...
[ "\n If this is a reversed op, then flip x,y\n\n If we have an integer value (or array in y)\n and we have 0's, fill them with the fill,\n return the result.\n\n Mask the nan's from x.\n " ]
Please provide a description of the function:def mask_zero_div_zero(x, y, result, copy=False): if is_scalar(y): y = np.array(y) zmask = y == 0 if zmask.any(): shape = result.shape nan_mask = (zmask & (x == 0)).ravel() neginf_mask = (zmask & (x < 0)).ravel() pos...
[ "\n Set results of 0 / 0 or 0 // 0 to np.nan, regardless of the dtypes\n of the numerator or the denominator.\n\n Parameters\n ----------\n x : ndarray\n y : ndarray\n result : ndarray\n copy : bool (default False)\n Whether to always create a new array or try to fill in the existing\...
Please provide a description of the function:def dispatch_missing(op, left, right, result): opstr = '__{opname}__'.format(opname=op.__name__).replace('____', '__') if op in [operator.truediv, operator.floordiv, getattr(operator, 'div', None)]: result = mask_zero_div_zero(left, right, ...
[ "\n Fill nulls caused by division by zero, casting to a diffferent dtype\n if necessary.\n\n Parameters\n ----------\n op : function (operator.add, operator.div, ...)\n left : object (Index for non-reversed ops)\n right : object (Index fof reversed ops)\n result : ndarray\n\n Returns\n ...
Please provide a description of the function:def _interp_limit(invalid, fw_limit, bw_limit): # handle forward first; the backward direction is the same except # 1. operate on the reversed array # 2. subtract the returned indices from N - 1 N = len(invalid) f_idx = set() b_idx = set() d...
[ "\n Get indexers of values that won't be filled\n because they exceed the limits.\n\n Parameters\n ----------\n invalid : boolean ndarray\n fw_limit : int or None\n forward limit to index\n bw_limit : int or None\n backward limit to index\n\n Returns\n -------\n set of in...
Please provide a description of the function:def _rolling_window(a, window): # https://stackoverflow.com/a/6811241 shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
[ "\n [True, True, False, True, False], 2 ->\n\n [\n [True, True],\n [True, False],\n [False, True],\n [True, False],\n ]\n " ]
Please provide a description of the function:def get_console_size(): from pandas import get_option display_width = get_option('display.width') # deprecated. display_height = get_option('display.max_rows') # Consider # interactive shell terminal, can detect term size # interactive non-...
[ "Return console size as tuple = (width, height).\n\n Returns (None,None) in non-interactive session.\n " ]
Please provide a description of the function:def in_interactive_session(): from pandas import get_option def check_main(): try: import __main__ as main except ModuleNotFoundError: return get_option('mode.sim_interactive') return (not hasattr(main, '__file__'...
[ " check if we're running in an interactive shell\n\n returns True if running under python/ipython interactive shell\n " ]
Please provide a description of the function:def recode_for_groupby(c, sort, observed): # we only care about observed values if observed: unique_codes = unique1d(c.codes) take_codes = unique_codes[unique_codes != -1] if c.ordered: take_codes = np.sort(take_codes) ...
[ "\n Code the categories to ensure we can groupby for categoricals.\n\n If observed=True, we return a new Categorical with the observed\n categories only.\n\n If sort=False, return a copy of self, coded with categories as\n returned by .unique(), followed by any categories not appearing in\n the da...
Please provide a description of the function:def recode_from_groupby(c, sort, ci): # we re-order to the original category orderings if sort: return ci.set_categories(c.categories) # we are not sorting, so add unobserved to the end return ci.add_categories( c.categories[~c.categori...
[ "\n Reverse the codes_to_groupby to account for sort / observed.\n\n Parameters\n ----------\n c : Categorical\n sort : boolean\n The value of the sort parameter groupby was called with.\n ci : CategoricalIndex\n The codes / categories to recode\n\n Returns\n -------\n Categ...
Please provide a description of the function:def get_engine(engine): if engine == 'auto': engine = get_option('io.parquet.engine') if engine == 'auto': # try engines in this order try: return PyArrowImpl() except ImportError: pass try: ...
[ " return our implementation " ]
Please provide a description of the function:def to_parquet(df, path, engine='auto', compression='snappy', index=None, partition_cols=None, **kwargs): impl = get_engine(engine) return impl.write(df, path, compression=compression, index=index, partition_cols=partition_co...
[ "\n Write a DataFrame to the parquet format.\n\n Parameters\n ----------\n path : str\n File path or Root Directory path. Will be used as Root Directory path\n while writing a partitioned dataset.\n\n .. versionchanged:: 0.24.0\n\n engine : {'auto', 'pyarrow', 'fastparquet'}, def...
Please provide a description of the function:def read_parquet(path, engine='auto', columns=None, **kwargs): impl = get_engine(engine) return impl.read(path, columns=columns, **kwargs)
[ "\n Load a parquet object from the file path, returning a DataFrame.\n\n .. versionadded 0.21.0\n\n Parameters\n ----------\n path : string\n File path\n engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.par...
Please provide a description of the function:def generate_bins_generic(values, binner, closed): lenidx = len(values) lenbin = len(binner) if lenidx <= 0 or lenbin <= 0: raise ValueError("Invalid length for values or for binner") # check binner fits data if values[0] < binner[0]: ...
[ "\n Generate bin edge offsets and bin labels for one array using another array\n which has bin edge values. Both arrays must be sorted.\n\n Parameters\n ----------\n values : array of values\n binner : a comparable array of values representing bins into which to bin\n the first array. Note,...
Please provide a description of the function:def get_iterator(self, data, axis=0): splitter = self._get_splitter(data, axis=axis) keys = self._get_group_keys() for key, (i, group) in zip(keys, splitter): yield key, group
[ "\n Groupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group\n " ]
Please provide a description of the function:def indices(self): if len(self.groupings) == 1: return self.groupings[0].indices else: label_list = [ping.labels for ping in self.groupings] keys = [com.values_from_object(ping.group_index) for ...
[ " dict {group name -> group indices} " ]
Please provide a description of the function:def size(self): ids, _, ngroup = self.group_info ids = ensure_platform_int(ids) if ngroup: out = np.bincount(ids[ids != -1], minlength=ngroup) else: out = [] return Series(out, ind...
[ "\n Compute group sizes\n\n " ]
Please provide a description of the function:def groups(self): if len(self.groupings) == 1: return self.groupings[0].groups else: to_groupby = lzip(*(ping.grouper for ping in self.groupings)) to_groupby = Index(to_groupby) return self.axis.groupby...
[ " dict {group name -> group labels} " ]
Please provide a description of the function:def groups(self): # this is mainly for compat # GH 3881 result = {key: value for key, value in zip(self.binlabels, self.bins) if key is not NaT} return result
[ " dict {group name -> group labels} " ]
Please provide a description of the function:def get_iterator(self, data, axis=0): if isinstance(data, NDFrame): slicer = lambda start, edge: data._slice( slice(start, edge), axis=axis) length = len(data.axes[axis]) else: slicer = lambda start...
[ "\n Groupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group\n " ]
Please provide a description of the function:def json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors='raise', sep='.'): def _pull_field(js, spec): result = js if isinstance(spe...
[ "\n Normalize semi-structured JSON data into a flat table.\n\n Parameters\n ----------\n data : dict or list of dicts\n Unserialized JSON objects\n record_path : string or list of strings, default None\n Path in each object to list of records. If not passed, data will be\n assume...
Please provide a description of the function:def lreshape(data, groups, dropna=True, label=None): if isinstance(groups, dict): keys = list(groups.keys()) values = list(groups.values()) else: keys, values = zip(*groups) all_cols = list(set.union(*[set(x) for x in values])) i...
[ "\n Reshape long-format data to wide. Generalized inverse of DataFrame.pivot\n\n Parameters\n ----------\n data : DataFrame\n groups : dict\n {new_name : list_of_columns}\n dropna : boolean, default True\n\n Examples\n --------\n >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [...
Please provide a description of the function:def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'): r def get_var_names(df, stub, sep, suffix): regex = r'^{stub}{sep}{suffix}$'.format( stub=re.escape(stub), sep=re.escape(sep), suffix=suffix) pattern = re.compile(regex) ...
[ "\n Wide panel to long format. Less flexible but more user-friendly than melt.\n\n With stubnames ['A', 'B'], this function expects to find one or more\n group of columns with format\n A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,...\n You specify what you want to call this suffix in the resulting ...
Please provide a description of the function:def _get_indices(self, names): def get_converter(s): # possibly convert to the actual key types # in the indices, could be a Timestamp or a np.datetime64 if isinstance(s, (Timestamp, datetime.datetime)): r...
[ "\n Safe get multiple indices, translate keys for\n datelike to underlying repr.\n " ]
Please provide a description of the function:def _set_group_selection(self): grp = self.grouper if not (self.as_index and getattr(grp, 'groupings', None) is not None and self.obj.ndim > 1 and self._group_selection is None): return ...
[ "\n Create group based selection.\n\n Used when selection is not passed directly but instead via a grouper.\n\n NOTE: this should be paired with a call to _reset_group_selection\n " ]
Please provide a description of the function:def get_group(self, name, obj=None): if obj is None: obj = self._selected_obj inds = self._get_index(name) if not len(inds): raise KeyError(name) return obj._take(inds, axis=self.axis)
[ "\n Construct NDFrame from group with provided name.\n\n Parameters\n ----------\n name : object\n the name of the group to get as a DataFrame\n obj : NDFrame, default None\n the NDFrame to take the DataFrame out of. If\n it is None, the object gr...
Please provide a description of the function:def _cumcount_array(self, ascending=True): ids, _, ngroups = self.grouper.group_info sorter = get_group_index_sorter(ids, ngroups) ids, count = ids[sorter], len(ids) if count == 0: return np.empty(0, dtype=np.int64) ...
[ "\n Parameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from length of group - 1 to 0.\n\n Notes\n -----\n this is currently implementing sort=False\n (though the default is sort=True) for groupby in general\n " ]
Please provide a description of the function:def _try_cast(self, result, obj, numeric_only=False): if obj.ndim > 1: dtype = obj._values.dtype else: dtype = obj.dtype if not is_scalar(result): if is_datetime64tz_dtype(dtype): # GH 2368...
[ "\n Try to cast the result to our obj original type,\n we may have roundtripped through object in the mean-time.\n\n If numeric_only is True, then only try to cast numerics\n and not datetimelikes.\n\n " ]
Please provide a description of the function:def _transform_should_cast(self, func_nm): return (self.size().fillna(0) > 0).any() and ( func_nm not in base.cython_cast_blacklist)
[ "\n Parameters:\n -----------\n func_nm: str\n The name of the aggregation function being performed\n\n Returns:\n --------\n bool\n Whether transform should attempt to cast the result of aggregation\n " ]
Please provide a description of the function:def _bool_agg(self, val_test, skipna): def objs_to_bool(vals: np.ndarray) -> Tuple[np.ndarray, Type]: if is_object_dtype(vals): vals = np.array([bool(x) for x in vals]) else: vals = vals.astype(np.bool...
[ "\n Shared func to call any / all Cython GroupBy implementations.\n " ]
Please provide a description of the function:def mean(self, *args, **kwargs): nv.validate_groupby_func('mean', args, kwargs, ['numeric_only']) try: return self._cython_agg_general('mean', **kwargs) except GroupByError: raise except Exception: # pragma: n...
[ "\n Compute mean of groups, excluding missing values.\n\n Returns\n -------\n pandas.Series or pandas.DataFrame\n %(see_also)s\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],\n ... 'B': [np.nan, 2, 3, 4, 5],\n ...
Please provide a description of the function:def median(self, **kwargs): try: return self._cython_agg_general('median', **kwargs) except GroupByError: raise except Exception: # pragma: no cover def f(x): if isinstance(x, np.ndarray):...
[ "\n Compute median of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex\n " ]
Please provide a description of the function:def std(self, ddof=1, *args, **kwargs): # TODO: implement at Cython level? nv.validate_groupby_func('std', args, kwargs) return np.sqrt(self.var(ddof=ddof, **kwargs))
[ "\n Compute standard deviation of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\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_groupby_func('var', args, kwargs) if ddof == 1: try: return self._cython_agg_general('var', **kwargs) except Exception: f = lambda x: x.var(dd...
[ "\n Compute variance of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom\n " ]
Please provide a description of the function:def sem(self, ddof=1): return self.std(ddof=ddof) / np.sqrt(self.count())
[ "\n Compute standard error of the mean of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom\n " ]
Please provide a description of the function:def size(self): result = self.grouper.size() if isinstance(self.obj, Series): result.name = getattr(self.obj, 'name', None) return result
[ "\n Compute group sizes.\n " ]
Please provide a description of the function:def _add_numeric_operations(cls): def groupby_function(name, alias, npfunc, numeric_only=True, _convert=False, min_count=-1): _local_template = "Compute %(f)s of group values" ...
[ "\n Add numeric operations to the GroupBy generically.\n " ]
Please provide a description of the function:def resample(self, rule, *args, **kwargs): from pandas.core.resample import get_resampler_for_grouping return get_resampler_for_grouping(self, rule, *args, **kwargs)
[ "\n Provide resampling when using a TimeGrouper.\n\n Given a grouper, the function resamples it according to a string\n \"string\" -> \"frequency\".\n\n See the :ref:`frequency aliases <timeseries.offset_aliases>`\n documentation for more details.\n\n Parameters\n --...
Please provide a description of the function:def rolling(self, *args, **kwargs): from pandas.core.window import RollingGroupby return RollingGroupby(self, *args, **kwargs)
[ "\n Return a rolling grouper, providing rolling functionality per group.\n " ]
Please provide a description of the function:def expanding(self, *args, **kwargs): from pandas.core.window import ExpandingGroupby return ExpandingGroupby(self, *args, **kwargs)
[ "\n Return an expanding grouper, providing expanding\n functionality per group.\n " ]
Please provide a description of the function:def _fill(self, direction, limit=None): # Need int value for Cython if limit is None: limit = -1 return self._get_cythonized_result('group_fillna_indexer', self.grouper, needs_mask=True,...
[ "\n Shared function for `pad` and `backfill` to call Cython method.\n\n Parameters\n ----------\n direction : {'ffill', 'bfill'}\n Direction passed to underlying Cython function. `bfill` will cause\n values to be filled backwards. `ffill` and any other values will\n...
Please provide a description of the function:def nth(self, n, dropna=None): if isinstance(n, int): nth_values = [n] elif isinstance(n, (set, list, tuple)): nth_values = list(set(n)) if dropna is not None: raise ValueError( ...
[ "\n Take the nth row from each group if n is an int, or a subset of rows\n if n is a list of ints.\n\n If dropna, will take the nth non-null row, dropna is either\n Truthy (if a Series) or 'all', 'any' (if a DataFrame);\n this is equivalent to calling dropna(how=dropna) before the...
Please provide a description of the function:def quantile(self, q=0.5, interpolation='linear'): def pre_processor( vals: np.ndarray ) -> Tuple[np.ndarray, Optional[Type]]: if is_object_dtype(vals): raise TypeError("'quantile' cannot be performed agai...
[ "\n Return group values at the given quantile, a la numpy.percentile.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n Value(s) between 0 and 1 providing the quantile(s) to compute.\n interpolation : {'linear', 'lower', 'higher', 'midp...
Please provide a description of the function:def ngroup(self, ascending=True): with _group_selection_context(self): index = self._selected_obj.index result = Series(self.grouper.group_info[0], index) if not ascending: result = self.ngroups - 1 - resu...
[ "\n Number each group from 0 to the number of groups - 1.\n\n This is the enumerative complement of cumcount. Note that the\n numbers given to the groups match the order in which the groups\n would be seen when iterating over the groupby object, not the\n order they are first obs...
Please provide a description of the function:def cumcount(self, ascending=True): with _group_selection_context(self): index = self._selected_obj.index cumcounts = self._cumcount_array(ascending=ascending) return Series(cumcounts, index)
[ "\n Number each item in each group from 0 to the length of that group - 1.\n\n Essentially this is equivalent to\n\n >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))\n\n Parameters\n ----------\n ascending : bool, default True\n If False, number in...
Please provide a description of the function:def rank(self, method='average', ascending=True, na_option='keep', pct=False, axis=0): if na_option not in {'keep', 'top', 'bottom'}: msg = "na_option must be one of 'keep', 'top', or 'bottom'" raise ValueError(msg) ...
[ "\n Provide the rank of values within each group.\n\n Parameters\n ----------\n method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'\n * average: average rank of group\n * min: lowest rank in group\n * max: highest rank in group\n ...
Please provide a description of the function:def cumprod(self, axis=0, *args, **kwargs): nv.validate_groupby_func('cumprod', args, kwargs, ['numeric_only', 'skipna']) if axis != 0: return self.apply(lambda x: x.cumprod(axis=axis, **kwargs)) ...
[ "\n Cumulative product for each group.\n " ]
Please provide a description of the function:def cummin(self, axis=0, **kwargs): if axis != 0: return self.apply(lambda x: np.minimum.accumulate(x, axis)) return self._cython_transform('cummin', numeric_only=False)
[ "\n Cumulative min for each group.\n " ]
Please provide a description of the function:def cummax(self, axis=0, **kwargs): if axis != 0: return self.apply(lambda x: np.maximum.accumulate(x, axis)) return self._cython_transform('cummax', numeric_only=False)
[ "\n Cumulative max for each group.\n " ]
Please provide a description of the function:def _get_cythonized_result(self, how, grouper, aggregate=False, cython_dtype=None, needs_values=False, needs_mask=False, needs_ngroups=False, result_is_index=False, ...
[ "\n Get result for Cythonized functions.\n\n Parameters\n ----------\n how : str, Cythonized function name to be called\n grouper : Grouper object containing pertinent group info\n aggregate : bool, default False\n Whether the result should be aggregated to match...
Please provide a description of the function:def shift(self, periods=1, freq=None, axis=0, fill_value=None): if freq is not None or axis != 0 or not isna(fill_value): return self.apply(lambda x: x.shift(periods, freq, axis, fill_value)) ...
[ "\n Shift each group by periods observations.\n\n Parameters\n ----------\n periods : integer, default 1\n number of periods to shift\n freq : frequency string\n axis : axis to shift, default 0\n fill_value : optional\n\n .. versionadded:: 0.24....