Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _arith_method_SERIES(cls, op, special): str_rep = _get_opstr(op, cls) op_name = _get_op_name(op, special) eval_kwargs = _gen_eval_kwargs(op_name) fill_zeros = _gen_fill_zeros(op_name) construct_result = (_construct_divmod_result ...
[ "\n Wrapper function for Series arithmetic operations, to avoid\n code duplication.\n ", "\n return the result of evaluating na_op on the passed in values\n\n try coercion to object type if the native types are not compatible\n\n Parameters\n ----------\n lvalues : arra...
Please provide a description of the function:def _comp_method_SERIES(cls, op, special): op_name = _get_op_name(op, special) masker = _gen_eval_kwargs(op_name).get('masker', False) def na_op(x, y): # TODO: # should have guarantess on what x, y can be type-wise # Extension Dtypes...
[ "\n Wrapper function for Series arithmetic operations, to avoid\n code duplication.\n " ]
Please provide a description of the function:def _bool_method_SERIES(cls, op, special): op_name = _get_op_name(op, special) def na_op(x, y): try: result = op(x, y) except TypeError: assert not isinstance(y, (list, ABCSeries, ABCIndexClass)) if isinstance...
[ "\n Wrapper function for Series arithmetic operations, to avoid\n code duplication.\n " ]
Please provide a description of the function:def _combine_series_frame(self, other, func, fill_value=None, axis=None, level=None): if fill_value is not None: raise NotImplementedError("fill_value {fill} not supported." .format(fill=fill_value)...
[ "\n Apply binary operator `func` to self, other using alignment and fill\n conventions determined by the fill_value, axis, and level kwargs.\n\n Parameters\n ----------\n self : DataFrame\n other : Series\n func : binary operator\n fill_value : object, default None\n axis : {0, 1, 'column...
Please provide a description of the function:def _align_method_FRAME(left, right, axis): def to_series(right): msg = ('Unable to coerce to Series, length must be {req_len}: ' 'given {given_len}') if axis is not None and left._get_axis_name(axis) == 'index': if len(le...
[ " convert rhs to meet lhs dims if input is list, tuple or np.ndarray " ]
Please provide a description of the function:def _cast_sparse_series_op(left, right, opname): from pandas.core.sparse.api import SparseDtype opname = opname.strip('_') # TODO: This should be moved to the array? if is_integer_dtype(left) and is_integer_dtype(right): # series coerces to flo...
[ "\n For SparseSeries operation, coerce to float64 if the result is expected\n to have NaN or inf values\n\n Parameters\n ----------\n left : SparseArray\n right : SparseArray\n opname : str\n\n Returns\n -------\n left : SparseArray\n right : SparseArray\n " ]
Please provide a description of the function:def _arith_method_SPARSE_SERIES(cls, op, special): op_name = _get_op_name(op, special) def wrapper(self, other): if isinstance(other, ABCDataFrame): return NotImplemented elif isinstance(other, ABCSeries): if not isinstan...
[ "\n Wrapper function for Series arithmetic operations, to avoid\n code duplication.\n " ]
Please provide a description of the function:def _arith_method_SPARSE_ARRAY(cls, op, special): op_name = _get_op_name(op, special) def wrapper(self, other): from pandas.core.arrays.sparse.array import ( SparseArray, _sparse_array_op, _wrap_result, _get_fill) if isinstance(other...
[ "\n Wrapper function for Series arithmetic operations, to avoid\n code duplication.\n " ]
Please provide a description of the function:def validate_periods(periods): if periods is not None: if lib.is_float(periods): periods = int(periods) elif not lib.is_integer(periods): raise TypeError('periods must be a number, got {periods}' .f...
[ "\n If a `periods` argument is passed to the Datetime/Timedelta Array/Index\n constructor, cast it to an integer.\n\n Parameters\n ----------\n periods : None, float, int\n\n Returns\n -------\n periods : None or int\n\n Raises\n ------\n TypeError\n if periods is None, float...
Please provide a description of the function:def validate_endpoints(closed): left_closed = False right_closed = False if closed is None: left_closed = True right_closed = True elif closed == "left": left_closed = True elif closed == "right": right_closed = True ...
[ "\n Check that the `closed` argument is among [None, \"left\", \"right\"]\n\n Parameters\n ----------\n closed : {None, \"left\", \"right\"}\n\n Returns\n -------\n left_closed : bool\n right_closed : bool\n\n Raises\n ------\n ValueError : if argument is not among valid values\n ...
Please provide a description of the function:def validate_inferred_freq(freq, inferred_freq, freq_infer): if inferred_freq is not None: if freq is not None and freq != inferred_freq: raise ValueError('Inferred frequency {inferred} from passed ' 'values does not ...
[ "\n If the user passes a freq and another freq is inferred from passed data,\n require that they match.\n\n Parameters\n ----------\n freq : DateOffset or None\n inferred_freq : DateOffset or None\n freq_infer : bool\n\n Returns\n -------\n freq : DateOffset or None\n freq_infer : b...
Please provide a description of the function:def maybe_infer_freq(freq): freq_infer = False if not isinstance(freq, DateOffset): # if a passed freq is None, don't infer automatically if freq != 'infer': freq = frequencies.to_offset(freq) else: freq_infer = Tr...
[ "\n Comparing a DateOffset to the string \"infer\" raises, so we need to\n be careful about comparisons. Make a dummy variable `freq_infer` to\n signify the case where the given freq is \"infer\" and set freq to None\n to avoid comparison trouble later on.\n\n Parameters\n ----------\n freq : ...
Please provide a description of the function:def _ensure_datetimelike_to_i8(other, to_utc=False): from pandas import Index from pandas.core.arrays import PeriodArray if lib.is_scalar(other) and isna(other): return iNaT elif isinstance(other, (PeriodArray, ABCIndexClass, ...
[ "\n Helper for coercing an input scalar or array to i8.\n\n Parameters\n ----------\n other : 1d array\n to_utc : bool, default False\n If True, convert the values to UTC before extracting the i8 values\n If False, extract the i8 values directly.\n\n Returns\n -------\n i8 1d a...
Please provide a description of the function:def _scalar_from_string( self, value: str, ) -> Union[Period, Timestamp, Timedelta, NaTType]: raise AbstractMethodError(self)
[ "\n Construct a scalar type from a string.\n\n Parameters\n ----------\n value : str\n\n Returns\n -------\n Period, Timestamp, or Timedelta, or NaT\n Whatever the type of ``self._scalar_type`` is.\n\n Notes\n -----\n This should call ...
Please provide a description of the function:def _unbox_scalar( self, value: Union[Period, Timestamp, Timedelta, NaTType], ) -> int: raise AbstractMethodError(self)
[ "\n Unbox the integer value of a scalar `value`.\n\n Parameters\n ----------\n value : Union[Period, Timestamp, Timedelta]\n\n Returns\n -------\n int\n\n Examples\n --------\n >>> self._unbox_scalar(Timedelta('10s')) # DOCTEST: +SKIP\n 1...
Please provide a description of the function:def _check_compatible_with( self, other: Union[Period, Timestamp, Timedelta, NaTType], ) -> None: raise AbstractMethodError(self)
[ "\n Verify that `self` and `other` are compatible.\n\n * DatetimeArray verifies that the timezones (if any) match\n * PeriodArray verifies that the freq matches\n * Timedelta has no verification\n\n In each case, NaT is considered compatible.\n\n Parameters\n -------...
Please provide a description of the function:def strftime(self, date_format): from pandas import Index return Index(self._format_native_types(date_format=date_format))
[ "\n Convert to Index using specified date_format.\n\n Return an Index of formatted strings specified by date_format, which\n supports the same string format as the python standard library. Details\n of the string format can be found in `python string format\n doc <%(URL)s>`__.\n\n...
Please provide a description of the function:def searchsorted(self, value, side='left', sorter=None): if isinstance(value, str): value = self._scalar_from_string(value) if not (isinstance(value, (self._scalar_type, type(self))) or isna(value)): raise Val...
[ "\n Find indices where elements should be inserted to maintain order.\n\n Find the indices into a sorted array `self` such that, if the\n corresponding elements in `value` were inserted before the indices,\n the order of `self` would be preserved.\n\n Parameters\n ---------...
Please provide a description of the function:def repeat(self, repeats, *args, **kwargs): nv.validate_repeat(args, kwargs) values = self._data.repeat(repeats) return type(self)(values.view('i8'), dtype=self.dtype)
[ "\n Repeat elements of an array.\n\n See Also\n --------\n numpy.ndarray.repeat\n " ]
Please provide a description of the function:def value_counts(self, dropna=False): from pandas import Series, Index if dropna: values = self[~self.isna()]._data else: values = self._data cls = type(self) result = value_counts(values, sort=False...
[ "\n Return a Series containing counts of unique values.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't include counts of NaT values.\n\n Returns\n -------\n Series\n " ]
Please provide a description of the function:def _maybe_mask_results(self, result, fill_value=iNaT, convert=None): if self._hasnans: if convert: result = result.astype(convert) if fill_value is None: fill_value = np.nan result[self._i...
[ "\n Parameters\n ----------\n result : a ndarray\n fill_value : object, default iNaT\n convert : string/dtype or None\n\n Returns\n -------\n result : ndarray with values replace by the fill_value\n\n mask the result if needed, convert to the provided d...
Please provide a description of the function:def _validate_frequency(cls, index, freq, **kwargs): if is_period_dtype(cls): # Frequency validation is not meaningful for Period Array/Index return None inferred = index.inferred_freq if index.size == 0 or inferred =...
[ "\n Validate that a frequency is compatible with the values of a given\n Datetime Array/Index or Timedelta Array/Index\n\n Parameters\n ----------\n index : DatetimeIndex or TimedeltaIndex\n The index on which to determine if the given frequency is valid\n freq :...
Please provide a description of the function:def _add_delta(self, other): if isinstance(other, (Tick, timedelta, np.timedelta64)): new_values = self._add_timedeltalike_scalar(other) elif is_timedelta64_dtype(other): # ndarray[timedelta64] or TimedeltaArray/index ...
[ "\n Add a timedelta-like, Tick or TimedeltaIndex-like object\n to self, yielding an int64 numpy array\n\n Parameters\n ----------\n delta : {timedelta, np.timedelta64, Tick,\n TimedeltaIndex, ndarray[timedelta64]}\n\n Returns\n -------\n result...
Please provide a description of the function:def _add_timedeltalike_scalar(self, other): if isna(other): # i.e np.timedelta64("NaT"), not recognized by delta_to_nanoseconds new_values = np.empty(len(self), dtype='i8') new_values[:] = iNaT return new_value...
[ "\n Add a delta of a timedeltalike\n return the i8 result view\n " ]
Please provide a description of the function:def _add_delta_tdi(self, other): if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray): # ndarray[timedelta64]; wrap in TimedeltaIndex for op from pa...
[ "\n Add a delta of a TimedeltaIndex\n return the i8 result view\n " ]
Please provide a description of the function:def _add_nat(self): if is_period_dtype(self): raise TypeError('Cannot add {cls} and {typ}' .format(cls=type(self).__name__, typ=type(NaT).__name__)) # GH#19124 pd.NaT is tre...
[ "\n Add pd.NaT to self\n " ]
Please provide a description of the function:def _sub_nat(self): # GH#19124 Timedelta - datetime is not in general well-defined. # We make an exception for pd.NaT, which in this case quacks # like a timedelta. # For datetime64 dtypes by convention we treat NaT as a datetime, so ...
[ "\n Subtract pd.NaT from self\n " ]
Please provide a description of the function:def _sub_period_array(self, other): if not is_period_dtype(self): raise TypeError("cannot subtract {dtype}-dtype from {cls}" .format(dtype=other.dtype, cls=type(self).__name__)) ...
[ "\n Subtract a Period Array/Index from self. This is only valid if self\n is itself a Period Array/Index, raises otherwise. Both objects must\n have the same frequency.\n\n Parameters\n ----------\n other : PeriodIndex or PeriodArray\n\n Returns\n -------\n ...
Please provide a description of the function:def _addsub_int_array(self, other, op): # _addsub_int_array is overriden by PeriodArray assert not is_period_dtype(self) assert op in [operator.add, operator.sub] if self.freq is None: # GH#19123 raise NullFre...
[ "\n Add or subtract array-like of integers equivalent to applying\n `_time_shift` pointwise.\n\n Parameters\n ----------\n other : Index, ExtensionArray, np.ndarray\n integer-dtype\n op : {operator.add, operator.sub}\n\n Returns\n -------\n r...
Please provide a description of the function:def _addsub_offset_array(self, other, op): assert op in [operator.add, operator.sub] if len(other) == 1: return op(self, other[0]) warnings.warn("Adding/subtracting array of DateOffsets to " "{cls} not vecto...
[ "\n Add or subtract array-like of DateOffset objects\n\n Parameters\n ----------\n other : Index, np.ndarray\n object-dtype containing pd.DateOffset objects\n op : {operator.add, operator.sub}\n\n Returns\n -------\n result : same class as self\n ...
Please provide a description of the function:def _time_shift(self, periods, freq=None): if freq is not None and freq != self.freq: if isinstance(freq, str): freq = frequencies.to_offset(freq) offset = periods * freq result = self + offset ...
[ "\n Shift each value by `periods`.\n\n Note this is different from ExtensionArray.shift, which\n shifts the *position* of each element, padding the end with\n missing values.\n\n Parameters\n ----------\n periods : int\n Number of periods to shift by.\n ...
Please provide a description of the function:def _ensure_localized(self, arg, ambiguous='raise', nonexistent='raise', from_utc=False): # reconvert to local tz tz = getattr(self, 'tz', None) if tz is not None: if not isinstance(arg, type(self)): ...
[ "\n Ensure that we are re-localized.\n\n This is for compat as we can then call this on all datetimelike\n arrays generally (ignored for Period/Timedelta)\n\n Parameters\n ----------\n arg : Union[DatetimeLikeArray, DatetimeIndexOpsMixin, ndarray]\n ambiguous : str, ...
Please provide a description of the function:def min(self, axis=None, skipna=True, *args, **kwargs): nv.validate_min(args, kwargs) nv.validate_minmax_axis(axis) result = nanops.nanmin(self.asi8, skipna=skipna, mask=self.isna()) if isna(result): # Period._from_ordina...
[ "\n Return the minimum value of the Array or minimum along\n an axis.\n\n See Also\n --------\n numpy.ndarray.min\n Index.min : Return the minimum value in an Index.\n Series.min : Return the minimum value in a Series.\n " ]
Please provide a description of the function:def max(self, axis=None, skipna=True, *args, **kwargs): # TODO: skipna is broken with max. # See https://github.com/pandas-dev/pandas/issues/24265 nv.validate_max(args, kwargs) nv.validate_minmax_axis(axis) mask = self.isna()...
[ "\n Return the maximum value of the Array or maximum along\n an axis.\n\n See Also\n --------\n numpy.ndarray.max\n Index.max : Return the maximum value in an Index.\n Series.max : Return the maximum value in a Series.\n " ]
Please provide a description of the function:def _period_array_cmp(cls, op): opname = '__{name}__'.format(name=op.__name__) nat_result = opname == '__ne__' def wrapper(self, other): op = getattr(self.asi8, opname) if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): ...
[ "\n Wrap comparison operations to convert Period-like to PeriodDtype\n " ]
Please provide a description of the function:def _raise_on_incompatible(left, right): # GH#24283 error message format depends on whether right is scalar if isinstance(right, np.ndarray): other_freq = None elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)): other_f...
[ "\n Helper function to render a consistent error message when raising\n IncompatibleFrequency.\n\n Parameters\n ----------\n left : PeriodArray\n right : DateOffset, Period, ndarray, or timedelta-like\n\n Raises\n ------\n IncompatibleFrequency\n " ]
Please provide a description of the function:def period_array( data: Sequence[Optional[Period]], freq: Optional[Tick] = None, copy: bool = False, ) -> PeriodArray: if is_datetime64_dtype(data): return PeriodArray._from_datetime64(data, freq) if isinstance(data, (ABCPeriodInd...
[ "\n Construct a new PeriodArray from a sequence of Period scalars.\n\n Parameters\n ----------\n data : Sequence of Period objects\n A sequence of Period objects. These are required to all have\n the same ``freq.`` Missing values can be indicated by ``None``\n or ``pandas.NaT``.\n ...
Please provide a description of the function:def validate_dtype_freq(dtype, freq): if freq is not None: freq = frequencies.to_offset(freq) if dtype is not None: dtype = pandas_dtype(dtype) if not is_period_dtype(dtype): raise ValueError('dtype must be PeriodDtype') ...
[ "\n If both a dtype and a freq are available, ensure they match. If only\n dtype is available, extract the implied freq.\n\n Parameters\n ----------\n dtype : dtype\n freq : DateOffset or None\n\n Returns\n -------\n freq : DateOffset\n\n Raises\n ------\n ValueError : non-perio...
Please provide a description of the function:def dt64arr_to_periodarr(data, freq, tz=None): if data.dtype != np.dtype('M8[ns]'): raise ValueError('Wrong dtype: {dtype}'.format(dtype=data.dtype)) if freq is None: if isinstance(data, ABCIndexClass): data, freq = data._values, dat...
[ "\n Convert an datetime-like array to values Period ordinals.\n\n Parameters\n ----------\n data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]\n freq : Optional[Union[str, Tick]]\n Must match the `freq` on the `data` if `data` is a DatetimeIndex\n or Series.\n ...
Please provide a description of the function:def _from_datetime64(cls, data, freq, tz=None): data, freq = dt64arr_to_periodarr(data, freq, tz) return cls(data, freq=freq)
[ "\n Construct a PeriodArray from a datetime64 array\n\n Parameters\n ----------\n data : ndarray[datetime64[ns], datetime64[ns, tz]]\n freq : str or Tick\n tz : tzinfo, optional\n\n Returns\n -------\n PeriodArray[freq]\n " ]
Please provide a description of the function:def to_timestamp(self, freq=None, how='start'): from pandas.core.arrays import DatetimeArray how = libperiod._validate_end_alias(how) end = how == 'E' if end: if freq == 'B': # roll forward to ensure we l...
[ "\n Cast to DatetimeArray/Index.\n\n Parameters\n ----------\n freq : string or DateOffset, optional\n Target frequency. The default is 'D' for week or longer,\n 'S' otherwise\n how : {'s', 'e', 'start', 'end'}\n\n Returns\n -------\n Dat...
Please provide a description of the function:def _time_shift(self, periods, freq=None): if freq is not None: raise TypeError("`freq` argument is not supported for " "{cls}._time_shift" .format(cls=type(self).__name__)) values =...
[ "\n Shift each value by `periods`.\n\n Note this is different from ExtensionArray.shift, which\n shifts the *position* of each element, padding the end with\n missing values.\n\n Parameters\n ----------\n periods : int\n Number of periods to shift by.\n ...
Please provide a description of the function:def asfreq(self, freq=None, how='E'): how = libperiod._validate_end_alias(how) freq = Period._maybe_convert_freq(freq) base1, mult1 = libfrequencies.get_freq_code(self.freq) base2, mult2 = libfrequencies.get_freq_code(freq) ...
[ "\n Convert the Period Array/Index to the specified frequency `freq`.\n\n Parameters\n ----------\n freq : str\n a frequency\n how : str {'E', 'S'}\n 'E', 'END', or 'FINISH' for end,\n 'S', 'START', or 'BEGIN' for start.\n Whether the el...
Please provide a description of the function:def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs): values = self.astype(object) if date_format: formatter = lambda dt: dt.strftime(date_format) else: formatter = lambda dt: '%s' % dt if...
[ "\n actually format my specific types\n " ]
Please provide a description of the function:def _add_timedeltalike_scalar(self, other): assert isinstance(self.freq, Tick) # checked by calling function assert isinstance(other, (timedelta, np.timedelta64, Tick)) if notna(other): # special handling for np.timedelta64("NaT...
[ "\n Parameters\n ----------\n other : timedelta, Tick, np.timedelta64\n\n Returns\n -------\n result : ndarray[int64]\n " ]
Please provide a description of the function:def _add_delta_tdi(self, other): assert isinstance(self.freq, Tick) # checked by calling function delta = self._check_timedeltalike_freq_compat(other) return self._addsub_int_array(delta, operator.add).asi8
[ "\n Parameters\n ----------\n other : TimedeltaArray or ndarray[timedelta64]\n\n Returns\n -------\n result : ndarray[int64]\n " ]
Please provide a description of the function:def _add_delta(self, other): if not isinstance(self.freq, Tick): # We cannot add timedelta-like to non-tick PeriodArray _raise_on_incompatible(self, other) new_ordinals = super()._add_delta(other) return type(self)(ne...
[ "\n Add a timedelta-like, Tick, or TimedeltaIndex-like object\n to self, yielding a new PeriodArray\n\n Parameters\n ----------\n other : {timedelta, np.timedelta64, Tick,\n TimedeltaIndex, ndarray[timedelta64]}\n\n Returns\n -------\n result :...
Please provide a description of the function:def _check_timedeltalike_freq_compat(self, other): assert isinstance(self.freq, Tick) # checked by calling function own_offset = frequencies.to_offset(self.freq.rule_code) base_nanos = delta_to_nanoseconds(own_offset) if isinstance(...
[ "\n Arithmetic operations with timedelta-like scalars or array `other`\n are only valid if `other` is an integer multiple of `self.freq`.\n If the operation is valid, find that integer multiple. Otherwise,\n raise because the operation is invalid.\n\n Parameters\n --------...
Please provide a description of the function:def _isna_old(obj): if is_scalar(obj): return libmissing.checknull_old(obj) # hack (for now) because MI registers as ndarray elif isinstance(obj, ABCMultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") elif isinsta...
[ "Detect missing values. Treat None, NaN, INF, -INF as null.\n\n Parameters\n ----------\n arr: ndarray or object value\n\n Returns\n -------\n boolean ndarray or boolean\n " ]
Please provide a description of the function:def _use_inf_as_na(key): from pandas._config import get_option flag = get_option(key) if flag: globals()['_isna'] = _isna_old else: globals()['_isna'] = _isna_new
[ "Option change callback for na/inf behaviour\n Choose which replacement for numpy.isnan / -numpy.isfinite is used.\n\n Parameters\n ----------\n flag: bool\n True means treat None, NaN, INF, -INF as null (old way),\n False means None and NaN are null, but INF, -INF are not null\n (n...
Please provide a description of the function:def _isna_compat(arr, fill_value=np.nan): dtype = arr.dtype if isna(fill_value): return not (is_bool_dtype(dtype) or is_integer_dtype(dtype)) return True
[ "\n Parameters\n ----------\n arr: a numpy array\n fill_value: fill value, default to np.nan\n\n Returns\n -------\n True if we can fill using this fill_value\n " ]
Please provide a description of the function:def array_equivalent(left, right, strict_nan=False): left, right = np.asarray(left), np.asarray(right) # shape compat if left.shape != right.shape: return False # Object arrays can contain None, NaN and NaT. # string dtypes must be come to...
[ "\n True if two arrays, left and right, have equal non-NaN elements, and NaNs\n in corresponding locations. False otherwise. It is assumed that left and\n right are NumPy arrays of the same dtype. The behavior of this function\n (particularly with respect to NaNs) is not defined if the dtypes are\n ...
Please provide a description of the function:def _infer_fill_value(val): if not is_list_like(val): val = [val] val = np.array(val, copy=False) if is_datetimelike(val): return np.array('NaT', dtype=val.dtype) elif is_object_dtype(val.dtype): dtype = lib.infer_dtype(ensure_ob...
[ "\n infer the fill value for the nan/NaT from the provided\n scalar/ndarray/list-like if we are a NaT, return the correct dtyped\n element to provide proper block construction\n " ]
Please provide a description of the function:def _maybe_fill(arr, fill_value=np.nan): if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
[ "\n if we have a compatible fill_value and arr dtype, then fill\n " ]
Please provide a description of the function:def na_value_for_dtype(dtype, compat=True): dtype = pandas_dtype(dtype) if is_extension_array_dtype(dtype): return dtype.na_value if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or is_timedelta64_dtype(dtype) or is_period_...
[ "\n Return a dtype compat na value\n\n Parameters\n ----------\n dtype : string / dtype\n compat : boolean, default True\n\n Returns\n -------\n np.dtype or a pandas dtype\n\n Examples\n --------\n >>> na_value_for_dtype(np.dtype('int64'))\n 0\n >>> na_value_for_dtype(np.dtype...
Please provide a description of the function:def remove_na_arraylike(arr): if is_extension_array_dtype(arr): return arr[notna(arr)] else: return arr[notna(lib.values_from_object(arr))]
[ "\n Return array-like containing only true/non-NaN values, possibly empty.\n " ]
Please provide a description of the function:def table(ax, data, rowLabels=None, colLabels=None, **kwargs): if isinstance(data, ABCSeries): data = data.to_frame() elif isinstance(data, ABCDataFrame): pass else: raise ValueError('Input data must be DataFrame or Series') if r...
[ "\n Helper function to convert DataFrame and Series to matplotlib.table\n\n Parameters\n ----------\n ax : Matplotlib axes object\n data : DataFrame or Series\n data for table contents\n kwargs : keywords, optional\n keyword arguments which passed to matplotlib.table.table.\n ...
Please provide a description of the function:def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True, subplot_kw=None, ax=None, layout=None, layout_type='box', **fig_kw): import matplotlib.pyplot as plt if subplot_kw is None: subplot_kw = {} if ax is Non...
[ "Create a figure with a set of subplots already made.\n\n This utility wrapper makes it convenient to create common layouts of\n subplots, including the enclosing figure object, in a single call.\n\n Keyword arguments:\n\n naxes : int\n Number of required axes. Exceeded axes are set invisible. Defa...
Please provide a description of the function:def maybe_cythonize(extensions, *args, **kwargs): if len(sys.argv) > 1 and 'clean' in sys.argv: # Avoid running cythonize on `python setup.py clean` # See https://github.com/cython/cython/issues/1495 return extensions if not cython: ...
[ "\n Render tempita templates before calling cythonize\n " ]
Please provide a description of the function:def _transform_fast(self, result, obj, func_nm): # if there were groups with no observations (Categorical only?) # try casting data to original dtype cast = self._transform_should_cast(func_nm) # for each col, reshape to to size of o...
[ "\n Fast transform path for aggregations\n " ]
Please provide a description of the function:def filter(self, func, dropna=True, *args, **kwargs): # noqa indices = [] obj = self._selected_obj gen = self.grouper.get_iterator(obj, axis=self.axis) for name, group in gen: object.__setattr__(group, 'name', name) ...
[ "\n Return a copy of a DataFrame excluding elements from groups that\n do not satisfy the boolean criterion specified by func.\n\n Parameters\n ----------\n f : function\n Function to apply to each subframe. Should return True or False.\n dropna : Drop groups tha...
Please provide a description of the function:def _wrap_output(self, output, index, names=None): output = output[self._selection_name] if names is not None: return DataFrame(output, index=index, columns=names) else: name = self._selection_name if name...
[ " common agg/transform wrapping logic " ]
Please provide a description of the function:def _transform_fast(self, func, func_nm): if isinstance(func, str): func = getattr(self, func) ids, _, ngroup = self.grouper.group_info cast = self._transform_should_cast(func_nm) out = algorithms.take_1d(func()._values, ...
[ "\n fast version of transform, only applicable to\n builtin/cythonizable functions\n " ]
Please provide a description of the function:def filter(self, func, dropna=True, *args, **kwargs): # noqa if isinstance(func, str): wrapper = lambda x: getattr(x, func)(*args, **kwargs) else: wrapper = lambda x: func(x, *args, **kwargs) # Interpret np.nan as Fa...
[ "\n Return a copy of a Series excluding elements from groups that\n do not satisfy the boolean criterion specified by func.\n\n Parameters\n ----------\n func : function\n To apply to each group. Should return True or False.\n dropna : Drop groups that do not pas...
Please provide a description of the function:def nunique(self, dropna=True): ids, _, _ = self.grouper.group_info val = self.obj.get_values() try: sorter = np.lexsort((val, ids)) except TypeError: # catches object dtypes msg = 'val.dtype must be object,...
[ "\n Return number of unique elements in the group.\n " ]
Please provide a description of the function:def count(self): ids, _, ngroups = self.grouper.group_info val = self.obj.get_values() mask = (ids != -1) & ~isna(val) ids = ensure_platform_int(ids) minlength = ngroups or 0 out = np.bincount(ids[mask], minlength=min...
[ " Compute count of group, excluding missing values " ]
Please provide a description of the function:def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): # TODO: Remove this conditional when #23918 is fixed if freq: return self.apply(lambda x: x.pct_change(periods=periods, ...
[ "Calcuate pct_change of each value to previous entry in group" ]
Please provide a description of the function:def _gotitem(self, key, ndim, subset=None): if ndim == 2: if subset is None: subset = self.obj return DataFrameGroupBy(subset, self.grouper, selection=key, grouper=self.grouper, ...
[ "\n sub-classes to define\n return a sliced object\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n " ]
Please provide a description of the function:def _reindex_output(self, result): # we need to re-expand the output space to accomodate all values # whether observed or not in the cartesian product of our groupes groupings = self.grouper.groupings if groupings is None: ...
[ "\n If we have categorical groupers, then we want to make sure that\n we have a fully reindex-output to the levels. These may have not\n participated in the groupings (e.g. may have all been\n nan groups);\n\n This can re-expand the output space\n " ]
Please provide a description of the function:def _fill(self, direction, limit=None): res = super()._fill(direction, limit=limit) output = OrderedDict( (grp.name, grp.grouper) for grp in self.grouper.groupings) from pandas import concat return concat((self._wrap_tran...
[ "Overridden method to join grouped columns in output" ]
Please provide a description of the function:def count(self): from pandas.core.dtypes.missing import _isna_ndarraylike as _isna data, _ = self._get_data_to_aggregate() ids, _, ngroups = self.grouper.group_info mask = ids != -1 val = ((mask & ~_isna(np.atleast_2d(blk.ge...
[ " Compute count of group, excluding missing values " ]
Please provide a description of the function:def nunique(self, dropna=True): obj = self._selected_obj def groupby_series(obj, col=None): return SeriesGroupBy(obj, selection=col, grouper=self.grouper).nunique(dropna=...
[ "\n Return DataFrame with number of distinct observations per group for\n each column.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't include NaN in the counts.\n\n Returns\n -------\n nuniqu...
Please provide a description of the function:def extract_array(obj, extract_numpy=False): if isinstance(obj, (ABCIndexClass, ABCSeries)): obj = obj.array if extract_numpy and isinstance(obj, ABCPandasArray): obj = obj.to_numpy() return obj
[ "\n Extract the ndarray or ExtensionArray from a Series or Index.\n\n For all other types, `obj` is just returned as is.\n\n Parameters\n ----------\n obj : object\n For Series / Index, the underlying ExtensionArray is unboxed.\n For Numpy-backed ExtensionArrays, the ndarray is extracte...
Please provide a description of the function:def flatten(l): for el in l: if _iterable_not_string(el): for s in flatten(el): yield s else: yield el
[ "\n Flatten an arbitrarily nested sequence.\n\n Parameters\n ----------\n l : sequence\n The non string sequence to flatten\n\n Notes\n -----\n This doesn't consider strings sequences.\n\n Returns\n -------\n flattened : generator\n " ]
Please provide a description of the function:def is_bool_indexer(key: Any) -> bool: na_msg = 'cannot index with vector containing NA / NaN values' if (isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or (is_array_like(key) and is_extension_array_dtype(key.dtype))): if key.dtype == np....
[ "\n Check whether `key` is a valid boolean indexer.\n\n Parameters\n ----------\n key : Any\n Only list-likes may be considered boolean indexers.\n All other types are not considered a boolean indexer.\n For array-like input, boolean ndarrays or ExtensionArrays\n with ``_is_b...
Please provide a description of the function:def cast_scalar_indexer(val): # assumes lib.is_scalar(val) if lib.is_float(val) and val == int(val): return int(val) return val
[ "\n To avoid numpy DeprecationWarnings, cast float to integer where valid.\n\n Parameters\n ----------\n val : scalar\n\n Returns\n -------\n outval : scalar\n " ]
Please provide a description of the function:def index_labels_to_array(labels, dtype=None): if isinstance(labels, (str, tuple)): labels = [labels] if not isinstance(labels, (list, np.ndarray)): try: labels = list(labels) except TypeError: # non-iterable lab...
[ "\n Transform label or iterable of labels to array, for use in Index.\n\n Parameters\n ----------\n dtype : dtype\n If specified, use as dtype of the resulting array, otherwise infer.\n\n Returns\n -------\n array\n " ]
Please provide a description of the function:def is_null_slice(obj): return (isinstance(obj, slice) and obj.start is None and obj.stop is None and obj.step is None)
[ "\n We have a null slice.\n " ]
Please provide a description of the function:def is_full_slice(obj, l): return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and obj.step is None)
[ "\n We have a full length slice.\n " ]
Please provide a description of the function:def apply_if_callable(maybe_callable, obj, **kwargs): if callable(maybe_callable): return maybe_callable(obj, **kwargs) return maybe_callable
[ "\n Evaluate possibly callable input using obj and kwargs if it is callable,\n otherwise return as it is.\n\n Parameters\n ----------\n maybe_callable : possibly a callable\n obj : NDFrame\n **kwargs\n " ]
Please provide a description of the function:def standardize_mapping(into): if not inspect.isclass(into): if isinstance(into, collections.defaultdict): return partial( collections.defaultdict, into.default_factory) into = type(into) if not issubclass(into, abc.Ma...
[ "\n Helper function to standardize a supplied mapping.\n\n .. versionadded:: 0.21.0\n\n Parameters\n ----------\n into : instance or subclass of collections.abc.Mapping\n Must be a class, an initialized collections.defaultdict,\n or an instance of a collections.abc.Mapping subclass.\n\n...
Please provide a description of the function:def random_state(state=None): if is_integer(state): return np.random.RandomState(state) elif isinstance(state, np.random.RandomState): return state elif state is None: return np.random else: raise ValueError("random_state...
[ "\n Helper function for processing random_state arguments.\n\n Parameters\n ----------\n state : int, np.random.RandomState, None.\n If receives an int, passes to np.random.RandomState() as seed.\n If receives an np.random.RandomState object, just returns object.\n If receives `None...
Please provide a description of the function:def _pipe(obj, func, *args, **kwargs): if isinstance(func, tuple): func, target = func if target in kwargs: msg = '%s is both the pipe target and a keyword argument' % target raise ValueError(msg) kwargs[target] = obj ...
[ "\n Apply a function ``func`` to object ``obj`` either by passing obj as the\n first argument to the function or, in the case that the func is a tuple,\n interpret the first element of the tuple as a function and pass the obj to\n that function as a keyword argument whose key is the value of the second\...
Please provide a description of the function:def _get_rename_function(mapper): if isinstance(mapper, (abc.Mapping, ABCSeries)): def f(x): if x in mapper: return mapper[x] else: return x else: f = mapper return f
[ "\n Returns a function that will map names/labels, dependent if mapper\n is a dict, Series or just a function.\n " ]
Please provide a description of the function:def _get_fill_value(dtype, fill_value=None, fill_value_typ=None): if fill_value is not None: return fill_value if _na_ok_dtype(dtype): if fill_value_typ is None: return np.nan else: if fill_value_typ == '+inf': ...
[ " return the correct fill value for the dtype of the values " ]
Please provide a description of the function:def _wrap_results(result, dtype, fill_value=None): if is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype): if fill_value is None: # GH#24293 fill_value = iNaT if not isinstance(result, np.ndarray): tz = get...
[ " wrap our results if needed " ]
Please provide a description of the function:def _na_for_min_count(values, axis): # we either return np.nan or pd.NaT if is_numeric_dtype(values): values = values.astype('float64') fill_value = na_value_for_dtype(values.dtype) if values.ndim == 1: return fill_value else: ...
[ "Return the missing value for `values`\n\n Parameters\n ----------\n values : ndarray\n axis : int or None\n axis for the reduction\n\n Returns\n -------\n result : scalar or ndarray\n For 1-D values, returns a scalar of the correct missing type.\n For 2-D values, returns a...
Please provide a description of the function:def nanany(values, axis=None, skipna=True, mask=None): values, mask, dtype, _, _ = _get_values(values, skipna, False, copy=skipna, mask=mask) return values.any(axis)
[ "\n Check if any elements along an axis evaluate to True.\n\n Parameters\n ----------\n values : ndarray\n axis : int, optional\n skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : bool\n\n Examples\n --------\...
Please provide a description of the function:def nanall(values, axis=None, skipna=True, mask=None): values, mask, dtype, _, _ = _get_values(values, skipna, True, copy=skipna, mask=mask) return values.all(axis)
[ "\n Check if all elements along an axis evaluate to True.\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : bool\n\n Examples\n --------\n...
Please provide a description of the function:def nansum(values, axis=None, skipna=True, min_count=0, mask=None): values, mask, dtype, dtype_max, _ = _get_values(values, skipna, 0, mask=mask) dtype_sum = dtype_max if is_float_dtype(dtype): dtyp...
[ "\n Sum the elements along an axis ignoring NaNs\n\n Parameters\n ----------\n values : ndarray[dtype]\n axis: int, optional\n skipna : bool, default True\n min_count: int, default 0\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : dtype\n...
Please provide a description of the function:def nanmean(values, axis=None, skipna=True, mask=None): values, mask, dtype, dtype_max, _ = _get_values( values, skipna, 0, mask=mask) dtype_sum = dtype_max dtype_count = np.float64 if (is_integer_dtype(dtype) or is_timedelta64_dtype(dtype) or ...
[ "\n Compute the mean of the element along an axis ignoring NaNs\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : float\n Unless input is...
Please provide a description of the function:def nanmedian(values, axis=None, skipna=True, mask=None): def get_median(x): mask = notna(x) if not skipna and not mask.all(): return np.nan return np.nanmedian(x[mask]) values, mask, dtype, dtype_max, _ = _get_values(values,...
[ "\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : float\n Unless input is a float array, in which case use the same\n precision as th...
Please provide a description of the function:def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)) return _wrap_results(result, values.dtype)
[ "\n Compute the standard deviation along given axis while ignoring NaNs\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N re...
Please provide a description of the function:def nanvar(values, axis=None, skipna=True, ddof=1, mask=None): values = com.values_from_object(values) dtype = values.dtype if mask is None: mask = isna(values) if is_any_int_dtype(values): values = values.astype('f8') values[mask...
[ "\n Compute the variance along given axis while ignoring NaNs\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N represents t...
Please provide a description of the function:def nansem(values, axis=None, skipna=True, ddof=1, mask=None): # This checks if non-numeric-like data is passed with numeric_only=False # and raises a TypeError otherwise nanvar(values, axis, skipna, ddof=ddof, mask=mask) if mask is None: mask ...
[ "\n Compute the standard error in the mean along given axis while ignoring NaNs\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n wh...
Please provide a description of the function:def nanargmax(values, axis=None, skipna=True, mask=None): values, mask, dtype, _, _ = _get_values( values, skipna, fill_value_typ='-inf', mask=mask) result = values.argmax(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return resu...
[ "\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n --------\n result : int\n The index of max value in specified axis or -1 in the NA case\n\n Examples\n ...
Please provide a description of the function:def nanargmin(values, axis=None, skipna=True, mask=None): values, mask, dtype, _, _ = _get_values( values, skipna, fill_value_typ='+inf', mask=mask) result = values.argmin(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return resu...
[ "\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n --------\n result : int\n The index of min value in specified axis or -1 in the NA case\n\n Examples\n ...
Please provide a description of the function:def nanskew(values, axis=None, skipna=True, mask=None): values = com.values_from_object(values) if mask is None: mask = isna(values) if not is_float_dtype(values.dtype): values = values.astype('f8') count = _get_counts(mask, axis) ...
[ " Compute the sample skewness.\n\n The statistic computed here is the adjusted Fisher-Pearson standardized\n moment coefficient G1. The algorithm computes this coefficient directly\n from the second and third central moment.\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n...
Please provide a description of the function:def nankurt(values, axis=None, skipna=True, mask=None): values = com.values_from_object(values) if mask is None: mask = isna(values) if not is_float_dtype(values.dtype): values = values.astype('f8') count = _get_counts(mask, axis) ...
[ "\n Compute the sample excess kurtosis\n\n The statistic computed here is the adjusted Fisher-Pearson standardized\n moment coefficient G2, computed directly from the second and fourth\n central moment.\n\n Parameters\n ----------\n values : ndarray\n axis: int, optional\n skipna : bool, ...
Please provide a description of the function:def nanprod(values, axis=None, skipna=True, min_count=0, mask=None): if mask is None: mask = isna(values) if skipna and not is_any_int_dtype(values): values = values.copy() values[mask] = 1 result = values.prod(axis) return _maybe...
[ "\n Parameters\n ----------\n values : ndarray[dtype]\n axis: int, optional\n skipna : bool, default True\n min_count: int, default 0\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : dtype\n\n Examples\n --------\n >>> import pandas....