Code
stringlengths
103
85.9k
Summary
sequencelengths
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 if op in [divmod, rdivmod] else _construct_result) def na_op(x, y): import pandas.core.computation.expressions as expressions try: result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) except TypeError: result = masked_arith_op(x, y, op) result = missing.fill_zeros(result, x, y, op_name, fill_zeros) return result def safe_na_op(lvalues, rvalues): try: with np.errstate(all='ignore'): return na_op(lvalues, rvalues) except Exception: if is_object_dtype(lvalues): return libalgos.arrmap_object(lvalues, lambda x: op(x, rvalues)) raise def wrapper(left, right): if isinstance(right, ABCDataFrame): return NotImplemented left, right = _align_method_SERIES(left, right) res_name = get_op_result_name(left, right) right = maybe_upcast_for_op(right) if is_categorical_dtype(left): raise TypeError("{typ} cannot perform the operation " "{op}".format(typ=type(left).__name__, op=str_rep)) elif is_datetime64_dtype(left) or is_datetime64tz_dtype(left): # Give dispatch_to_index_op a chance for tests like # test_dt64_series_add_intlike, which the index dispatching handles # specifically. result = dispatch_to_index_op(op, left, right, pd.DatetimeIndex) return construct_result(left, result, index=left.index, name=res_name, dtype=result.dtype) elif (is_extension_array_dtype(left) or (is_extension_array_dtype(right) and not is_scalar(right))): # GH#22378 disallow scalar to exclude e.g. "category", "Int64" return dispatch_to_extension_op(op, left, right) elif is_timedelta64_dtype(left): result = dispatch_to_index_op(op, left, right, pd.TimedeltaIndex) return construct_result(left, result, index=left.index, name=res_name) elif is_timedelta64_dtype(right): # We should only get here with non-scalar or timedelta64('NaT') # values for right # Note: we cannot use dispatch_to_index_op because # that may incorrectly raise TypeError when we # should get NullFrequencyError result = op(pd.Index(left), right) return construct_result(left, result, index=left.index, name=res_name, dtype=result.dtype) lvalues = left.values rvalues = right if isinstance(rvalues, ABCSeries): rvalues = rvalues.values result = safe_na_op(lvalues, rvalues) return construct_result(left, result, index=left.index, name=res_name, dtype=None) wrapper.__name__ = op_name return wrapper
[ "\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 : array-like\n rvalues : array-like\n\n Raises\n ------\n TypeError: invalid operation\n " ]
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 are not called here # Checking that cases that were once handled here are no longer # reachable. assert not (is_categorical_dtype(y) and not is_scalar(y)) if is_object_dtype(x.dtype): result = _comp_method_OBJECT_ARRAY(op, x, y) elif is_datetimelike_v_numeric(x, y): return invalid_comparison(x, y, op) else: # we want to compare like types # we only want to convert to integer like if # we are not NotImplemented, otherwise # we would allow datetime64 (but viewed as i8) against # integer comparisons # we have a datetime/timedelta and may need to convert assert not needs_i8_conversion(x) mask = None if not is_scalar(y) and needs_i8_conversion(y): mask = isna(x) | isna(y) y = y.view('i8') x = x.view('i8') method = getattr(x, op_name, None) if method is not None: with np.errstate(all='ignore'): result = method(y) if result is NotImplemented: return invalid_comparison(x, y, op) else: result = op(x, y) if mask is not None and mask.any(): result[mask] = masker return result def wrapper(self, other, axis=None): # Validate the axis parameter if axis is not None: self._get_axis_number(axis) res_name = get_op_result_name(self, other) if isinstance(other, list): # TODO: same for tuples? other = np.asarray(other) if isinstance(other, ABCDataFrame): # pragma: no cover # Defer to DataFrame implementation; fail early return NotImplemented elif isinstance(other, ABCSeries) and not self._indexed_same(other): raise ValueError("Can only compare identically-labeled " "Series objects") elif is_categorical_dtype(self): # Dispatch to Categorical implementation; pd.CategoricalIndex # behavior is non-canonical GH#19513 res_values = dispatch_to_index_op(op, self, other, pd.Categorical) return self._constructor(res_values, index=self.index, name=res_name) elif is_datetime64_dtype(self) or is_datetime64tz_dtype(self): # Dispatch to DatetimeIndex to ensure identical # Series/Index behavior if (isinstance(other, datetime.date) and not isinstance(other, datetime.datetime)): # https://github.com/pandas-dev/pandas/issues/21152 # Compatibility for difference between Series comparison w/ # datetime and date msg = ( "Comparing Series of datetimes with 'datetime.date'. " "Currently, the 'datetime.date' is coerced to a " "datetime. In the future pandas will not coerce, " "and {future}. " "To retain the current behavior, " "convert the 'datetime.date' to a datetime with " "'pd.Timestamp'." ) if op in {operator.lt, operator.le, operator.gt, operator.ge}: future = "a TypeError will be raised" else: future = ( "'the values will not compare equal to the " "'datetime.date'" ) msg = '\n'.join(textwrap.wrap(msg.format(future=future))) warnings.warn(msg, FutureWarning, stacklevel=2) other = pd.Timestamp(other) res_values = dispatch_to_index_op(op, self, other, pd.DatetimeIndex) return self._constructor(res_values, index=self.index, name=res_name) elif is_timedelta64_dtype(self): res_values = dispatch_to_index_op(op, self, other, pd.TimedeltaIndex) return self._constructor(res_values, index=self.index, name=res_name) elif (is_extension_array_dtype(self) or (is_extension_array_dtype(other) and not is_scalar(other))): # Note: the `not is_scalar(other)` condition rules out # e.g. other == "category" return dispatch_to_extension_op(op, self, other) elif isinstance(other, ABCSeries): # By this point we have checked that self._indexed_same(other) res_values = na_op(self.values, other.values) # rename is needed in case res_name is None and res_values.name # is not. return self._constructor(res_values, index=self.index, name=res_name).rename(res_name) elif isinstance(other, (np.ndarray, pd.Index)): # do not check length of zerodim array # as it will broadcast if other.ndim != 0 and len(self) != len(other): raise ValueError('Lengths must match to compare') res_values = na_op(self.values, np.asarray(other)) result = self._constructor(res_values, index=self.index) # rename is needed in case res_name is None and self.name # is not. return result.__finalize__(self).rename(res_name) elif is_scalar(other) and isna(other): # numpy does not like comparisons vs None if op is operator.ne: res_values = np.ones(len(self), dtype=bool) else: res_values = np.zeros(len(self), dtype=bool) return self._constructor(res_values, index=self.index, name=res_name, dtype='bool') else: values = self.get_values() with np.errstate(all='ignore'): res = na_op(values, other) if is_scalar(res): raise TypeError('Could not compare {typ} type with Series' .format(typ=type(other))) # always return a full value series here res_values = com.values_from_object(res) return self._constructor(res_values, index=self.index, name=res_name, dtype='bool') wrapper.__name__ = op_name return wrapper
[ "\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(y, np.ndarray): # bool-bool dtype operations should be OK, should not get here assert not (is_bool_dtype(x) and is_bool_dtype(y)) x = ensure_object(x) y = ensure_object(y) result = libops.vec_binop(x, y, op) else: # let null fall thru assert lib.is_scalar(y) if not isna(y): y = bool(y) try: result = libops.scalar_binop(x, y, op) except (TypeError, ValueError, AttributeError, OverflowError, NotImplementedError): raise TypeError("cannot compare a dtyped [{dtype}] array " "with a scalar of type [{typ}]" .format(dtype=x.dtype, typ=type(y).__name__)) return result fill_int = lambda x: x.fillna(0) fill_bool = lambda x: x.fillna(False).astype(bool) def wrapper(self, other): is_self_int_dtype = is_integer_dtype(self.dtype) self, other = _align_method_SERIES(self, other, align_asobject=True) res_name = get_op_result_name(self, other) if isinstance(other, ABCDataFrame): # Defer to DataFrame implementation; fail early return NotImplemented elif isinstance(other, (ABCSeries, ABCIndexClass)): is_other_int_dtype = is_integer_dtype(other.dtype) other = fill_int(other) if is_other_int_dtype else fill_bool(other) ovalues = other.values finalizer = lambda x: x else: # scalars, list, tuple, np.array is_other_int_dtype = is_integer_dtype(np.asarray(other)) if is_list_like(other) and not isinstance(other, np.ndarray): # TODO: Can we do this before the is_integer_dtype check? # could the is_integer_dtype check be checking the wrong # thing? e.g. other = [[0, 1], [2, 3], [4, 5]]? other = construct_1d_object_array_from_listlike(other) ovalues = other finalizer = lambda x: x.__finalize__(self) # For int vs int `^`, `|`, `&` are bitwise operators and return # integer dtypes. Otherwise these are boolean ops filler = (fill_int if is_self_int_dtype and is_other_int_dtype else fill_bool) res_values = na_op(self.values, ovalues) unfilled = self._constructor(res_values, index=self.index, name=res_name) filled = filler(unfilled) return finalizer(filled) wrapper.__name__ = op_name return wrapper
[ "\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)) if axis is not None: axis = self._get_axis_number(axis) if axis == 0: return self._combine_match_index(other, func, level=level) else: return self._combine_match_columns(other, func, level=level) else: if not len(other): return self * np.nan if not len(self): # Ambiguous case, use _series so works with DataFrame return self._constructor(data=self._series, index=self.index, columns=self.columns) # default axis is columns return self._combine_match_columns(other, func, level=level)
[ "\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, 'columns', 'index', None}, default None\n level : int or None, default None\n\n Returns\n -------\n result : DataFrame\n " ]
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(left.index) != len(right): raise ValueError(msg.format(req_len=len(left.index), given_len=len(right))) right = left._constructor_sliced(right, index=left.index) else: if len(left.columns) != len(right): raise ValueError(msg.format(req_len=len(left.columns), given_len=len(right))) right = left._constructor_sliced(right, index=left.columns) return right if isinstance(right, np.ndarray): if right.ndim == 1: right = to_series(right) elif right.ndim == 2: if right.shape == left.shape: right = left._constructor(right, index=left.index, columns=left.columns) elif right.shape[0] == left.shape[0] and right.shape[1] == 1: # Broadcast across columns right = np.broadcast_to(right, left.shape) right = left._constructor(right, index=left.index, columns=left.columns) elif right.shape[1] == left.shape[1] and right.shape[0] == 1: # Broadcast along rows right = to_series(right[0, :]) else: raise ValueError("Unable to coerce to DataFrame, shape " "must be {req_shape}: given {given_shape}" .format(req_shape=left.shape, given_shape=right.shape)) elif right.ndim > 2: raise ValueError('Unable to coerce to Series/DataFrame, dim ' 'must be <= 2: {dim}'.format(dim=right.shape)) elif (is_list_like(right) and not isinstance(right, (ABCSeries, ABCDataFrame))): # GH17901 right = to_series(right) return right
[ " 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 float64 if result should have NaN/inf if opname in ('floordiv', 'mod') and (right.values == 0).any(): left = left.astype(SparseDtype(np.float64, left.fill_value)) right = right.astype(SparseDtype(np.float64, right.fill_value)) elif opname in ('rfloordiv', 'rmod') and (left.values == 0).any(): left = left.astype(SparseDtype(np.float64, left.fill_value)) right = right.astype(SparseDtype(np.float64, right.fill_value)) return left, right
[ "\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 isinstance(other, ABCSparseSeries): other = other.to_sparse(fill_value=self.fill_value) return _sparse_series_op(self, other, op, op_name) elif is_scalar(other): with np.errstate(all='ignore'): new_values = op(self.values, other) return self._constructor(new_values, index=self.index, name=self.name) else: # pragma: no cover raise TypeError('operation with {other} not supported' .format(other=type(other))) wrapper.__name__ = op_name return wrapper
[ "\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, np.ndarray): if len(self) != len(other): raise AssertionError("length mismatch: {self} vs. {other}" .format(self=len(self), other=len(other))) if not isinstance(other, SparseArray): dtype = getattr(other, 'dtype', None) other = SparseArray(other, fill_value=self.fill_value, dtype=dtype) return _sparse_array_op(self, other, op, op_name) elif is_scalar(other): with np.errstate(all='ignore'): fill = op(_get_fill(self), np.asarray(other)) result = op(self.sp_values, other) return _wrap_result(op_name, result, self.sp_index, fill) else: # pragma: no cover raise TypeError('operation with {other} not supported' .format(other=type(other))) wrapper.__name__ = op_name return wrapper
[ "\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}' .format(periods=periods)) return periods
[ "\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, or int\n " ]
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 else: raise ValueError("Closed has to be either 'left', 'right' or None") return left_closed, right_closed
[ "\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 conform to passed frequency ' '{passed}' .format(inferred=inferred_freq, passed=freq.freqstr)) elif freq is None: freq = inferred_freq freq_infer = False return freq, freq_infer
[ "\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 : bool\n\n Notes\n -----\n We assume at this point that `maybe_infer_freq` has been called, so\n `freq` is either a DateOffset object or None.\n " ]
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 = True freq = None return freq, freq_infer
[ "\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 : {DateOffset, None, str}\n\n Returns\n -------\n freq : {DateOffset, None}\n freq_infer : bool\n " ]
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, DatetimeLikeArrayMixin)): # convert tz if needed if getattr(other, 'tz', None) is not None: if to_utc: other = other.tz_convert('UTC') else: other = other.tz_localize(None) else: try: return np.array(other, copy=False).view('i8') except TypeError: # period array cannot be coerced to int other = Index(other) return other.asi8
[ "\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 array\n " ]
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 ``self._check_compatible_with`` before\n unboxing the result.\n " ]
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 10000000000\n " ]
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 ----------\n other\n\n Raises\n ------\n Exception\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 Parameters\n ----------\n date_format : str\n Date format string (e.g. \"%%Y-%%m-%%d\").\n\n Returns\n -------\n Index\n Index of formatted strings.\n\n See Also\n --------\n to_datetime : Convert the given argument to datetime.\n DatetimeIndex.normalize : Return DatetimeIndex with times to midnight.\n DatetimeIndex.round : Round the DatetimeIndex to the specified freq.\n DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq.\n\n Examples\n --------\n >>> rng = pd.date_range(pd.Timestamp(\"2018-03-10 09:00\"),\n ... periods=3, freq='s')\n >>> rng.strftime('%%B %%d, %%Y, %%r')\n Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM',\n 'March 10, 2018, 09:00:02 AM'],\n dtype='object')\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 ValueError("Unexpected type for 'value': {valtype}" .format(valtype=type(value))) self._check_compatible_with(value) if isinstance(value, type(self)): value = value.asi8 else: value = self._unbox_scalar(value) return self.asi8.searchsorted(value, side=side, sorter=sorter)
[ "\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 ----------\n value : array_like\n Values to insert into `self`.\n side : {'left', 'right'}, optional\n If 'left', the index of the first suitable location found is given.\n If 'right', return the last such index. If there is no suitable\n index, return either 0 or N (where N is the length of `self`).\n sorter : 1-D array_like, optional\n Optional array of integer indices that sort `self` into ascending\n order. They are typically the result of ``np.argsort``.\n\n Returns\n -------\n indices : array of ints\n Array of insertion points with the same shape as `value`.\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, dropna=dropna) index = Index(cls(result.index.view('i8'), dtype=self.dtype), name=result.index.name) return Series(result.values, index=index, name=result.name)
[ "\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._isnan] = fill_value return result
[ "\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 dtype if its not\n None\n\n This is an internal routine.\n " ]
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 == freq.freqstr: return None try: on_freq = cls._generate_range(start=index[0], end=None, periods=len(index), freq=freq, **kwargs) if not np.array_equal(index.asi8, on_freq.asi8): raise ValueError except ValueError as e: if "non-fixed" in str(e): # non-fixed frequencies are not meaningful for timedelta64; # we retain that error message raise e # GH#11587 the main way this is reached is if the `np.array_equal` # check above is False. This can also be reached if index[0] # is `NaT`, in which case the call to `cls._generate_range` will # raise a ValueError, which we re-raise with a more targeted # message. raise ValueError('Inferred frequency {infer} from passed values ' 'does not conform to passed frequency {passed}' .format(infer=inferred, passed=freq.freqstr))
[ "\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 : DateOffset\n The frequency to validate\n " ]
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 new_values = self._add_delta_tdi(other) return new_values
[ "\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 : ndarray[int64]\n\n Notes\n -----\n The result's name is set outside of _add_delta by the calling\n method (__add__ or __sub__), if necessary (i.e. for Indexes).\n " ]
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_values inc = delta_to_nanoseconds(other) new_values = checked_add_with_arr(self.asi8, inc, arr_mask=self._isnan).view('i8') new_values = self._maybe_mask_results(new_values) return new_values.view('i8')
[ "\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 pandas import TimedeltaIndex other = TimedeltaIndex(other) self_i8 = self.asi8 other_i8 = other.asi8 new_values = checked_add_with_arr(self_i8, other_i8, arr_mask=self._isnan, b_mask=other._isnan) if self._hasnans or other._hasnans: mask = (self._isnan) | (other._isnan) new_values[mask] = iNaT return new_values.view('i8')
[ "\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 treated like a timedelta for both timedelta # and datetime dtypes result = np.zeros(len(self), dtype=np.int64) result.fill(iNaT) return type(self)(result, dtype=self.dtype, freq=None)
[ "\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 # this subtraction returns a timedelta64 dtype. # For period dtype, timedelta64 is a close-enough return dtype. result = np.zeros(len(self), dtype=np.int64) result.fill(iNaT) return result.view('timedelta64[ns]')
[ "\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__)) if len(self) != len(other): raise ValueError("cannot subtract arrays/indices of " "unequal length") if self.freq != other.freq: msg = DIFFERENT_FREQ.format(cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr) raise IncompatibleFrequency(msg) new_values = checked_add_with_arr(self.asi8, -other.asi8, arr_mask=self._isnan, b_mask=other._isnan) new_values = np.array([self.freq.base * x for x in new_values]) if self._hasnans or other._hasnans: mask = (self._isnan) | (other._isnan) new_values[mask] = NaT return new_values
[ "\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 result : np.ndarray[object]\n Array of DateOffset objects; nulls represented by NaT.\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 NullFrequencyError("Cannot shift with no freq") elif isinstance(self.freq, Tick): # easy case where we can convert to timedelta64 operation td = Timedelta(self.freq) return op(self, td * other) # We should only get here with DatetimeIndex; dispatch # to _addsub_offset_array assert not is_timedelta64_dtype(self) return op(self, np.array(other) * self.freq)
[ "\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 result : same class as self\n " ]
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 vectorized" .format(cls=type(self).__name__), PerformanceWarning) # For EA self.astype('O') returns a numpy array, not an Index left = lib.values_from_object(self.astype('O')) res_values = op(left, np.array(other)) kwargs = {} if not is_period_dtype(self): kwargs['freq'] = 'infer' return self._from_sequence(res_values, **kwargs)
[ "\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 return result if periods == 0: # immutable so OK return self.copy() if self.freq is None: raise NullFrequencyError("Cannot shift with no freq") start = self[0] + periods * self.freq end = self[-1] + periods * self.freq # Note: in the DatetimeTZ case, _generate_range will infer the # appropriate timezone from `start` and `end`, so tz does not need # to be passed explicitly. return self._generate_range(start=start, end=end, periods=None, freq=self.freq)
[ "\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 freq : pandas.DateOffset, pandas.Timedelta, or string\n Frequency increment 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)): arg = self._simple_new(arg) if from_utc: arg = arg.tz_localize('UTC').tz_convert(self.tz) else: arg = arg.tz_localize( self.tz, ambiguous=ambiguous, nonexistent=nonexistent ) return arg
[ "\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, bool, or bool-ndarray, default 'raise'\n nonexistent : str, default 'raise'\n from_utc : bool, default False\n If True, localize the i8 ndarray to UTC first before converting to\n the appropriate tz. If False, localize directly to the tz.\n\n Returns\n -------\n localized array\n " ]
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_ordinal does not handle np.nan gracefully return NaT return self._box_func(result)
[ "\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() if skipna: values = self[~mask].asi8 elif mask.any(): return NaT else: values = self.asi8 if not len(values): # short-circut for empty max / min return NaT result = nanops.nanmax(values, skipna=skipna) # Don't have to worry about NA `result`, since no NA went in. return self._box_func(result)
[ "\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)): return NotImplemented if is_list_like(other) and len(other) != len(self): raise ValueError("Lengths must match") if isinstance(other, Period): self._check_compatible_with(other) result = op(other.ordinal) elif isinstance(other, cls): self._check_compatible_with(other) result = op(other.asi8) mask = self._isnan | other._isnan if mask.any(): result[mask] = nat_result return result elif other is NaT: result = np.empty(len(self.asi8), dtype=bool) result.fill(nat_result) else: other = Period(other, freq=self.freq) result = op(other.ordinal) if self._hasnans: result[self._isnan] = nat_result return result return compat.set_function_name(wrapper, opname, cls)
[ "\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_freq = right.freqstr else: other_freq = _delta_to_tick(Timedelta(right)).freqstr msg = DIFFERENT_FREQ.format(cls=type(left).__name__, own_freq=left.freqstr, other_freq=other_freq) raise IncompatibleFrequency(msg)
[ "\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, (ABCPeriodIndex, ABCSeries, PeriodArray)): return PeriodArray(data, freq) # other iterable of some kind if not isinstance(data, (np.ndarray, list, tuple)): data = list(data) data = np.asarray(data) if freq: dtype = PeriodDtype(freq) else: dtype = None if is_float_dtype(data) and len(data) > 0: raise TypeError("PeriodIndex does not allow " "floating point in construction") data = ensure_object(data) return PeriodArray._from_sequence(data, dtype=dtype)
[ "\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 freq : str, Tick, or Offset\n The frequency of every element of the array. This can be specified\n to avoid inferring the `freq` from `data`.\n copy : bool, default False\n Whether to ensure a copy of the data is made.\n\n Returns\n -------\n PeriodArray\n\n See Also\n --------\n PeriodArray\n pandas.PeriodIndex\n\n Examples\n --------\n >>> period_array([pd.Period('2017', freq='A'),\n ... pd.Period('2018', freq='A')])\n <PeriodArray>\n ['2017', '2018']\n Length: 2, dtype: period[A-DEC]\n\n >>> period_array([pd.Period('2017', freq='A'),\n ... pd.Period('2018', freq='A'),\n ... pd.NaT])\n <PeriodArray>\n ['2017', '2018', 'NaT']\n Length: 3, dtype: period[A-DEC]\n\n Integers that look like years are handled\n\n >>> period_array([2000, 2001, 2002], freq='D')\n ['2000-01-01', '2001-01-01', '2002-01-01']\n Length: 3, dtype: period[D]\n\n Datetime-like strings may also be passed\n\n >>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')\n <PeriodArray>\n ['2000Q1', '2000Q2', '2000Q3', '2000Q4']\n Length: 4, dtype: period[Q-DEC]\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') if freq is None: freq = dtype.freq elif freq != dtype.freq: raise IncompatibleFrequency('specified freq and dtype ' 'are different') return freq
[ "\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-period dtype\n IncompatibleFrequency : mismatch between dtype and freq\n " ]
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, data.freq elif isinstance(data, ABCSeries): data, freq = data._values, data.dt.freq freq = Period._maybe_convert_freq(freq) if isinstance(data, (ABCIndexClass, ABCSeries)): data = data._values base, mult = libfrequencies.get_freq_code(freq) return libperiod.dt64arr_to_periodarr(data.view('i8'), base, tz), freq
[ "\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 tz : Optional[tzinfo]\n\n Returns\n -------\n ordinals : ndarray[int]\n freq : Tick\n The frequencey extracted from the Series or DatetimeIndex if that's\n used.\n\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 land on B date adjust = Timedelta(1, 'D') - Timedelta(1, 'ns') return self.to_timestamp(how='start') + adjust else: adjust = Timedelta(1, 'ns') return (self + self.freq).to_timestamp(how='start') - adjust if freq is None: base, mult = libfrequencies.get_freq_code(self.freq) freq = libfrequencies.get_to_timestamp_base(base) else: freq = Period._maybe_convert_freq(freq) base, mult = libfrequencies.get_freq_code(freq) new_data = self.asfreq(freq, how=how) new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base) return DatetimeArray._from_sequence(new_data, freq='infer')
[ "\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 DatetimeArray/Index\n " ]
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 = self.asi8 + periods * self.freq.n if self._hasnans: values[self._isnan] = iNaT return type(self)(values, freq=self.freq)
[ "\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 freq : pandas.DateOffset, pandas.Timedelta, or string\n Frequency increment 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) asi8 = self.asi8 # mult1 can't be negative or 0 end = how == 'E' if end: ordinal = asi8 + mult1 - 1 else: ordinal = asi8 new_data = period_asfreq_arr(ordinal, base1, base2, end) if self._hasnans: new_data[self._isnan] = iNaT return type(self)(new_data, freq=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 elements should be aligned to the end\n or start within pa period. January 31st ('END') vs.\n January 1st ('START') for example.\n\n Returns\n -------\n new : Period Array/Index with the new frequency\n\n Examples\n --------\n >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')\n >>> pidx\n PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],\n dtype='period[A-DEC]', freq='A-DEC')\n\n >>> pidx.asfreq('M')\n PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',\n '2015-12'], dtype='period[M]', freq='M')\n\n >>> pidx.asfreq('M', how='S')\n PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',\n '2015-01'], dtype='period[M]', freq='M')\n " ]
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 self._hasnans: mask = self._isnan values[mask] = na_rep imask = ~mask values[imask] = np.array([formatter(dt) for dt in values[imask]]) else: values = np.array([formatter(dt) for dt in values]) return values
[ "\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"), avoid calling # _check_timedeltalike_freq_compat as that would raise TypeError other = self._check_timedeltalike_freq_compat(other) # Note: when calling parent class's _add_timedeltalike_scalar, # it will call delta_to_nanoseconds(delta). Because delta here # is an integer, delta_to_nanoseconds will return it unchanged. ordinals = super()._add_timedeltalike_scalar(other) return ordinals
[ "\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)(new_ordinals, freq=self.freq)
[ "\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 : PeriodArray\n " ]
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(other, (timedelta, np.timedelta64, Tick)): nanos = delta_to_nanoseconds(other) elif isinstance(other, np.ndarray): # numpy timedelta64 array; all entries must be compatible assert other.dtype.kind == 'm' if other.dtype != _TD_DTYPE: # i.e. non-nano unit # TODO: disallow unit-less timedelta64 other = other.astype(_TD_DTYPE) nanos = other.view('i8') else: # TimedeltaArray/Index nanos = other.asi8 if np.all(nanos % base_nanos == 0): # nanos being added is an integer multiple of the # base-frequency to self.freq delta = nanos // base_nanos # delta is the integer (or integer-array) number of periods # by which will be added to self. return delta _raise_on_incompatible(self, other)
[ "\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 ----------\n other : timedelta, np.timedelta64, Tick,\n ndarray[timedelta64], TimedeltaArray, TimedeltaIndex\n\n Returns\n -------\n multiple : int or ndarray[int64]\n\n Raises\n ------\n IncompatibleFrequency\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 isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): return obj._constructor(obj._data.isna(func=_isna_old)) elif isinstance(obj, list): return _isna_ndarraylike_old(np.asarray(obj, dtype=object)) elif hasattr(obj, '__array__'): return _isna_ndarraylike_old(np.asarray(obj)) else: return obj is None
[ "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 (new way).\n\n Notes\n -----\n This approach to setting global module values is discussed and\n approved here:\n\n * http://stackoverflow.com/questions/4859217/\n programmatically-creating-variables-in-python/4859312#4859312\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 this path for NumPy 1.7.1 compat if is_string_dtype(left) or is_string_dtype(right): if not strict_nan: # isna considers NaN and None to be equivalent. return lib.array_equivalent_object( ensure_object(left.ravel()), ensure_object(right.ravel())) for left_value, right_value in zip(left, right): if left_value is NaT and right_value is not NaT: return False elif isinstance(left_value, float) and np.isnan(left_value): if (not isinstance(right_value, float) or not np.isnan(right_value)): return False else: if left_value != right_value: return False return True # NaNs can occur in float and complex arrays. if is_float_dtype(left) or is_complex_dtype(left): # empty if not (np.prod(left.shape) and np.prod(right.shape)): return True return ((left == right) | (isna(left) & isna(right))).all() # numpy will will not allow this type of datetimelike vs integer comparison elif is_datetimelike_v_numeric(left, right): return False # M8/m8 elif needs_i8_conversion(left) and needs_i8_conversion(right): if not is_dtype_equal(left.dtype, right.dtype): return False left = left.view('i8') right = right.view('i8') # if we have structured dtypes, compare first if (left.dtype.type is np.void or right.dtype.type is np.void): if left.dtype != right.dtype: return False return np.array_equal(left, right)
[ "\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 different.\n\n Parameters\n ----------\n left, right : ndarrays\n strict_nan : bool, default False\n If True, consider NaN and None to be different.\n\n Returns\n -------\n b : bool\n Returns True if the arrays are equivalent.\n\n Examples\n --------\n >>> array_equivalent(\n ... np.array([1, 2, np.nan]),\n ... np.array([1, 2, np.nan]))\n True\n >>> array_equivalent(\n ... np.array([1, np.nan, 2]),\n ... np.array([1, 2, np.nan]))\n False\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_object(val), skipna=False) if dtype in ['datetime', 'datetime64']: return np.array('NaT', dtype=_NS_DTYPE) elif dtype in ['timedelta', 'timedelta64']: return np.array('NaT', dtype=_TD_DTYPE) return np.nan
[ "\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_dtype(dtype)): return NaT elif is_float_dtype(dtype): return np.nan elif is_integer_dtype(dtype): if compat: return 0 return np.nan elif is_bool_dtype(dtype): return False return np.nan
[ "\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('int64'), compat=False)\n nan\n >>> na_value_for_dtype(np.dtype('float64'))\n nan\n >>> na_value_for_dtype(np.dtype('bool'))\n False\n >>> na_value_for_dtype(np.dtype('datetime64[ns]'))\n NaT\n " ]
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 rowLabels is None: rowLabels = data.index if colLabels is None: colLabels = data.columns cellText = data.values import matplotlib.table table = matplotlib.table.table(ax, cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, **kwargs) return table
[ "\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 If `rowLabels` or `colLabels` is not specified, data index or column\n name will be used.\n\n Returns\n -------\n matplotlib table object\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 None: fig = plt.figure(**fig_kw) else: if is_list_like(ax): ax = _flatten(ax) if layout is not None: warnings.warn("When passing multiple axes, layout keyword is " "ignored", UserWarning) if sharex or sharey: warnings.warn("When passing multiple axes, sharex and sharey " "are ignored. These settings must be specified " "when creating axes", UserWarning, stacklevel=4) if len(ax) == naxes: fig = ax[0].get_figure() return fig, ax else: raise ValueError("The number of passed axes must be {0}, the " "same as the output plot".format(naxes)) fig = ax.get_figure() # if ax is passed and a number of subplots is 1, return ax as it is if naxes == 1: if squeeze: return fig, ax else: return fig, _flatten(ax) else: warnings.warn("To output multiple subplots, the figure containing " "the passed axes is being cleared", UserWarning, stacklevel=4) fig.clear() nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type) nplots = nrows * ncols # Create empty object array to hold all axes. It's easiest to make it 1-d # so we can just append subplots upon creation, and then axarr = np.empty(nplots, dtype=object) # Create first subplot separately, so we can share it if requested ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw) if sharex: subplot_kw['sharex'] = ax0 if sharey: subplot_kw['sharey'] = ax0 axarr[0] = ax0 # Note off-by-one counting because add_subplot uses the MATLAB 1-based # convention. for i in range(1, nplots): kwds = subplot_kw.copy() # Set sharex and sharey to None for blank/dummy axes, these can # interfere with proper axis limits on the visible axes if # they share axes e.g. issue #7528 if i >= naxes: kwds['sharex'] = None kwds['sharey'] = None ax = fig.add_subplot(nrows, ncols, i + 1, **kwds) axarr[i] = ax if naxes != nplots: for ax in axarr[naxes:]: ax.set_visible(False) _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey) if squeeze: # Reshape the array to have the final desired dimension (nrow,ncol), # though discarding unneeded dimensions that equal 1. If we only have # one subplot, just return it instead of a 1-element array. if nplots == 1: axes = axarr[0] else: axes = axarr.reshape(nrows, ncols).squeeze() else: # returned axis array will be always 2-d, even if nrows=ncols=1 axes = axarr.reshape(nrows, ncols) return fig, axes
[ "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. Default is\n nrows * ncols.\n\n sharex : bool\n If True, the X axis will be shared amongst all subplots.\n\n sharey : bool\n If True, the Y axis will be shared amongst all subplots.\n\n squeeze : bool\n\n If True, extra dimensions are squeezed out from the returned axis object:\n - if only one subplot is constructed (nrows=ncols=1), the resulting\n single Axis object is returned as a scalar.\n - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object\n array of Axis objects are returned as numpy 1-d arrays.\n - for NxM subplots with N>1 and M>1 are returned as a 2d array.\n\n If False, no squeezing is done: the returned axis object is always\n a 2-d array containing Axis instances, even if it ends up being 1x1.\n\n subplot_kw : dict\n Dict with keywords passed to the add_subplot() call used to create each\n subplots.\n\n ax : Matplotlib axis object, optional\n\n layout : tuple\n Number of rows and columns of the subplot grid.\n If not specified, calculated from naxes and layout_type\n\n layout_type : {'box', 'horziontal', 'vertical'}, default 'box'\n Specify how to layout the subplot grid.\n\n fig_kw : Other keyword arguments to be passed to the figure() call.\n Note that all keywords not recognized above will be\n automatically included here.\n\n Returns:\n\n fig, ax : tuple\n - fig is the Matplotlib Figure object\n - ax can be either a single axis object or an array of axis objects if\n more than one subplot was created. The dimensions of the resulting array\n can be controlled with the squeeze keyword, see above.\n\n **Examples:**\n\n x = np.linspace(0, 2*np.pi, 400)\n y = np.sin(x**2)\n\n # Just a figure and one subplot\n f, ax = plt.subplots()\n ax.plot(x, y)\n ax.set_title('Simple plot')\n\n # Two subplots, unpack the output array immediately\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.plot(x, y)\n ax1.set_title('Sharing Y axis')\n ax2.scatter(x, y)\n\n # Four polar axes\n plt.subplots(2, 2, subplot_kw=dict(polar=True))\n " ]
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: # Avoid trying to look up numpy when installing from sdist # https://github.com/pandas-dev/pandas/issues/25193 # TODO: See if this can be removed after pyproject.toml added. return extensions numpy_incl = pkg_resources.resource_filename('numpy', 'core/include') # TODO: Is this really necessary here? for ext in extensions: if (hasattr(ext, 'include_dirs') and numpy_incl not in ext.include_dirs): ext.include_dirs.append(numpy_incl) build_ext.render_templates(_pxifiles) return cythonize(extensions, *args, **kwargs)
[ "\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 original frame # by take operation ids, _, ngroup = self.grouper.group_info output = [] for i, _ in enumerate(result.columns): res = algorithms.take_1d(result.iloc[:, i].values, ids) if cast: res = self._try_cast(res, obj.iloc[:, i]) output.append(res) return DataFrame._from_arrays(output, columns=result.columns, index=obj.index)
[ "\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) res = func(group, *args, **kwargs) try: res = res.squeeze() except AttributeError: # allow e.g., scalars and frames to pass pass # interpret the result of the filter if is_bool(res) or (is_scalar(res) and isna(res)): if res and notna(res): indices.append(self._get_index(name)) else: # non scalars aren't allowed raise TypeError("filter function returned a %s, " "but expected a scalar bool" % type(res).__name__) return self._apply_filter(indices, dropna)
[ "\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 that do not pass the filter. True by default;\n if False, groups that evaluate False are filled with NaNs.\n\n Returns\n -------\n filtered : DataFrame\n\n Notes\n -----\n Each subframe is endowed the attribute 'name' in case you need to know\n which group you are working on.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',\n ... 'foo', 'bar'],\n ... 'B' : [1, 2, 3, 4, 5, 6],\n ... 'C' : [2.0, 5., 8., 1., 2., 9.]})\n >>> grouped = df.groupby('A')\n >>> grouped.filter(lambda x: x['B'].mean() > 3.)\n A B C\n 1 bar 2 5.0\n 3 bar 4 1.0\n 5 bar 6 9.0\n " ]
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 is None: name = self._selected_obj.name return Series(output, index=index, name=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, ids) if cast: out = self._try_cast(out, self.obj) return Series(out, index=self.obj.index, name=self.obj.name)
[ "\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 False. def true_and_notna(x, *args, **kwargs): b = wrapper(x, *args, **kwargs) return b and notna(b) try: indices = [self._get_index(name) for name, group in self if true_and_notna(group)] except ValueError: raise TypeError("the filter must return a boolean result") except TypeError: raise TypeError("the filter must return a boolean result") filtered = self._apply_filter(indices, dropna) return filtered
[ "\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 pass the filter. True by default;\n if False, groups that evaluate False are filled with NaNs.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',\n ... 'foo', 'bar'],\n ... 'B' : [1, 2, 3, 4, 5, 6],\n ... 'C' : [2.0, 5., 8., 1., 2., 9.]})\n >>> grouped = df.groupby('A')\n >>> df.groupby('A').B.filter(lambda x: x.mean() > 3.)\n 1 2\n 3 4\n 5 6\n Name: B, dtype: int64\n\n Returns\n -------\n filtered : Series\n " ]
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, got {}'.format(val.dtype) assert val.dtype == object, msg val, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((val, ids)) _isna = lambda a: a == -1 else: _isna = isna ids, val = ids[sorter], val[sorter] # group boundaries are where group ids change # unique observations are where sorted values change idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] inc = np.r_[1, val[1:] != val[:-1]] # 1st item of each group is a new unique observation mask = _isna(val) if dropna: inc[idx] = 1 inc[mask] = 0 else: inc[mask & np.r_[False, mask[:-1]]] = 0 inc[idx] = 1 out = np.add.reduceat(inc, idx).astype('int64', copy=False) if len(ids): # NaN/NaT group exists if the head of ids is -1, # so remove it from res and exclude its index from idx if ids[0] == -1: res = out[1:] idx = idx[np.flatnonzero(idx)] else: res = out else: res = out[1:] ri = self.grouper.result_index # we might have duplications among the bins if len(res) != len(ri): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out return Series(res, index=ri, name=self._selection_name)
[ "\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=minlength) return Series(out, index=self.grouper.result_index, name=self._selection_name, dtype='int64')
[ " 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, fill_method=fill_method, limit=limit, freq=freq)) filled = getattr(self, fill_method)(limit=limit) fill_grp = filled.groupby(self.grouper.labels) shifted = fill_grp.shift(periods=periods, freq=freq) return (filled / shifted) - 1
[ "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, exclusions=self.exclusions, as_index=self.as_index, observed=self.observed) elif ndim == 1: if subset is None: subset = self.obj[key] return SeriesGroupBy(subset, selection=key, grouper=self.grouper) raise AssertionError("invalid ndim for _gotitem")
[ "\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: return result elif len(groupings) == 1: return result # if we only care about the observed values # we are done elif self.observed: return result # reindexing only applies to a Categorical grouper elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex)) for ping in groupings): return result levels_list = [ping.group_index for ping in groupings] index, _ = MultiIndex.from_product( levels_list, names=self.grouper.names).sortlevel() if self.as_index: d = {self.obj._get_axis_name(self.axis): index, 'copy': False} return result.reindex(**d) # GH 13204 # Here, the categorical in-axis groupers, which need to be fully # expanded, are columns in `result`. An idea is to do: # result = result.set_index(self.grouper.names) # .reindex(index).reset_index() # but special care has to be taken because of possible not-in-axis # groupers. # So, we manually select and drop the in-axis grouper columns, # reindex `result`, and then reset the in-axis grouper columns. # Select in-axis groupers in_axis_grps = ((i, ping.name) for (i, ping) in enumerate(groupings) if ping.in_axis) g_nums, g_names = zip(*in_axis_grps) result = result.drop(labels=list(g_names), axis=1) # Set a temp index and reindex (possibly expanding) result = result.set_index(self.grouper.result_index ).reindex(index, copy=False) # Reset in-axis grouper columns # (using level numbers `g_nums` because level names may not be unique) result = result.reset_index(level=g_nums) return result.reset_index(drop=True)
[ "\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_transformed_output(output), res), axis=1)
[ "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.get_values()))) for blk in data.blocks) loc = (blk.mgr_locs for blk in data.blocks) counter = partial( lib.count_level_2d, labels=ids, max_bin=ngroups, axis=1) blk = map(make_block, map(counter, val), loc) return self._wrap_agged_blocks(data.items, list(blk))
[ " 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=dropna) if isinstance(obj, Series): results = groupby_series(obj) else: from pandas.core.reshape.concat import concat results = [groupby_series(obj[col], col) for col in obj.columns] results = concat(results, axis=1) results.columns.names = obj.columns.names if not self.as_index: results.index = ibase.default_index(len(results)) return results
[ "\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 nunique: DataFrame\n\n Examples\n --------\n >>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam',\n ... 'ham', 'ham'],\n ... 'value1': [1, 5, 5, 2, 5, 5],\n ... 'value2': list('abbaxy')})\n >>> df\n id value1 value2\n 0 spam 1 a\n 1 egg 5 b\n 2 egg 5 b\n 3 spam 2 a\n 4 ham 5 x\n 5 ham 5 y\n\n >>> df.groupby('id').nunique()\n id value1 value2\n id\n egg 1 1 1\n ham 1 1 2\n spam 1 2 1\n\n Check for rows with the same id but conflicting values:\n\n >>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any())\n id value1 value2\n 0 spam 1 a\n 3 spam 2 a\n 4 ham 5 x\n 5 ham 5 y\n " ]
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 extracted.\n\n extract_numpy : bool, default False\n Whether to extract the ndarray from a PandasArray\n\n Returns\n -------\n arr : object\n\n Examples\n --------\n >>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))\n [a, b, c]\n Categories (3, object): [a, b, c]\n\n Other objects like lists, arrays, and DataFrames are just passed through.\n\n >>> extract_array([1, 2, 3])\n [1, 2, 3]\n\n For an ndarray-backed Series / Index a PandasArray is returned.\n\n >>> extract_array(pd.Series([1, 2, 3]))\n <PandasArray>\n [1, 2, 3]\n Length: 3, dtype: int64\n\n To extract all the way down to the ndarray, pass ``extract_numpy=True``.\n\n >>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)\n array([1, 2, 3])\n " ]
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.object_: key = np.asarray(values_from_object(key)) if not lib.is_bool_array(key): if isna(key).any(): raise ValueError(na_msg) return False return True elif is_bool_dtype(key.dtype): # an ndarray with bool-dtype by definition has no missing values. # So we only need to check for NAs in ExtensionArrays if is_extension_array_dtype(key.dtype): if np.any(key.isna()): raise ValueError(na_msg) return True elif isinstance(key, list): try: arr = np.asarray(key) return arr.dtype == np.bool_ and len(arr) == len(key) except TypeError: # pragma: no cover return False return False
[ "\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_boolean`` set are considered boolean indexers.\n\n Returns\n -------\n bool\n\n Raises\n ------\n ValueError\n When the array is an object-dtype ndarray or ExtensionArray\n and contains missing values.\n " ]
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 labels = [labels] labels = asarray_tuplesafe(labels, dtype=dtype) return labels
[ "\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.Mapping): raise TypeError('unsupported type: {into}'.format(into=into)) elif into == collections.defaultdict: raise TypeError( 'to_dict() only accepts initialized defaultdicts') return into
[ "\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 Returns\n -------\n mapping : a collections.abc.Mapping subclass or other constructor\n a callable object that can accept an iterator to create\n the desired Mapping.\n\n See Also\n --------\n DataFrame.to_dict\n Series.to_dict\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 must be an integer, a numpy " "RandomState, or None")
[ "\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`, returns np.random.\n If receives anything else, raises an informative ValueError.\n Default None.\n\n Returns\n -------\n np.random.RandomState\n " ]
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 return func(*args, **kwargs) else: return func(obj, *args, **kwargs)
[ "\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\n element of the tuple.\n\n Parameters\n ----------\n func : callable or tuple of (callable, string)\n Function to apply to this object or, alternatively, a\n ``(callable, data_keyword)`` tuple where ``data_keyword`` is a\n string indicating the keyword of `callable`` that expects the\n object.\n args : iterable, optional\n positional arguments passed into ``func``.\n kwargs : dict, optional\n a dictionary of keyword arguments passed into ``func``.\n\n Returns\n -------\n object : the return type of ``func``.\n " ]
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 np.inf else: return -np.inf else: if fill_value_typ is None: return tslibs.iNaT else: if fill_value_typ == '+inf': # need the max int here return _int64_max else: return tslibs.iNaT
[ " 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 = getattr(dtype, 'tz', None) assert not isna(fill_value), "Expected non-null fill_value" if result == fill_value: result = np.nan result = tslibs.Timestamp(result, tz=tz) else: result = result.view(dtype) elif is_timedelta64_dtype(dtype): if not isinstance(result, np.ndarray): if result == fill_value: result = np.nan # raise if we have a timedelta64[ns] which is too large if np.fabs(result) > _int64_max: raise ValueError("overflow in timedelta operation") result = tslibs.Timedelta(result, unit='ns') else: result = result.astype('i8').view(dtype) return result
[ " 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: result_shape = (values.shape[:axis] + values.shape[axis + 1:]) result = np.empty(result_shape, dtype=values.dtype) result.fill(fill_value) return result
[ "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 1-D array where each element is missing.\n " ]
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 --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 2])\n >>> nanops.nanany(s)\n True\n\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([np.nan])\n >>> nanops.nanany(s)\n False\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 >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 2, np.nan])\n >>> nanops.nanall(s)\n True\n\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 0])\n >>> nanops.nanall(s)\n False\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): dtype_sum = dtype elif is_timedelta64_dtype(dtype): dtype_sum = np.float64 the_sum = values.sum(axis, dtype=dtype_sum) the_sum = _maybe_null_out(the_sum, axis, mask, min_count=min_count) return _wrap_results(the_sum, dtype)
[ "\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\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 2, np.nan])\n >>> nanops.nansum(s)\n 3.0\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 is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)): dtype_sum = np.float64 elif is_float_dtype(dtype): dtype_sum = dtype dtype_count = dtype count = _get_counts(mask, axis, dtype=dtype_count) the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum)) if axis is not None and getattr(the_sum, 'ndim', False): with np.errstate(all="ignore"): # suppress division by zero warnings the_mean = the_sum / count ct_mask = count == 0 if ct_mask.any(): the_mean[ct_mask] = np.nan else: the_mean = the_sum / count if count > 0 else np.nan return _wrap_results(the_mean, dtype)
[ "\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 a float array, in which case use the same\n precision as the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 2, np.nan])\n >>> nanops.nanmean(s)\n 1.5\n " ]
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, skipna, mask=mask) if not is_float_dtype(values): values = values.astype('f8') values[mask] = np.nan if axis is None: values = values.ravel() notempty = values.size # an array from a frame if values.ndim > 1: # there's a non-empty array to apply over otherwise numpy raises if notempty: if not skipna: return _wrap_results( np.apply_along_axis(get_median, axis, values), dtype) # fastpath for the skipna case return _wrap_results(np.nanmedian(values, axis), dtype) # must return the correct shape, but median is not defined for the # empty set so return nans of shape "everything but the passed axis" # since "axis" is where the reduction would occur if we had a nonempty # array shp = np.array(values.shape) dims = np.arange(values.ndim) ret = np.empty(shp[dims != axis]) ret.fill(np.nan) return _wrap_results(ret, dtype) # otherwise return a scalar value return _wrap_results(get_median(values) if notempty else np.nan, dtype)
[ "\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 the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, np.nan, 2, 2])\n >>> nanops.nanmedian(s)\n 2.0\n " ]
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 represents the number of elements.\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 the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, np.nan, 2, 3])\n >>> nanops.nanstd(s)\n 1.0\n " ]
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] = np.nan if is_float_dtype(values): count, d = _get_counts_nanvar(mask, axis, ddof, values.dtype) else: count, d = _get_counts_nanvar(mask, axis, ddof) if skipna: values = values.copy() np.putmask(values, mask, 0) # xref GH10242 # Compute variance via two-pass algorithm, which is stable against # cancellation errors and relatively accurate for small numbers of # observations. # # See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance avg = _ensure_numeric(values.sum(axis=axis, dtype=np.float64)) / count if axis is not None: avg = np.expand_dims(avg, axis) sqr = _ensure_numeric((avg - values) ** 2) np.putmask(sqr, mask, 0) result = sqr.sum(axis=axis, dtype=np.float64) / d # Return variance as np.float64 (the datatype used in the accumulator), # unless we were dealing with a float array, in which case use the same # precision as the original values array. if is_float_dtype(dtype): result = result.astype(dtype) return _wrap_results(result, values.dtype)
[ "\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 the number of elements.\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 the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, np.nan, 2, 3])\n >>> nanops.nanvar(s)\n 1.0\n " ]
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 = isna(values) if not is_float_dtype(values.dtype): values = values.astype('f8') count, _ = _get_counts_nanvar(mask, axis, ddof, values.dtype) var = nanvar(values, axis, skipna, ddof=ddof) return np.sqrt(var) / np.sqrt(count)
[ "\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 where N represents the number of elements.\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : float64\n Unless input is a float array, in which case use the same\n precision as the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, np.nan, 2, 3])\n >>> nanops.nansem(s)\n 0.5773502691896258\n " ]
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 result
[ "\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 --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 2, 3, np.nan, 4])\n >>> nanops.nanargmax(s)\n 4\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 result
[ "\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 --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1, 2, 3, np.nan, 4])\n >>> nanops.nanargmin(s)\n 0\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) else: count = _get_counts(mask, axis, dtype=values.dtype) if skipna: values = values.copy() np.putmask(values, mask, 0) mean = values.sum(axis, dtype=np.float64) / count if axis is not None: mean = np.expand_dims(mean, axis) adjusted = values - mean if skipna: np.putmask(adjusted, mask, 0) adjusted2 = adjusted ** 2 adjusted3 = adjusted2 * adjusted m2 = adjusted2.sum(axis, dtype=np.float64) m3 = adjusted3.sum(axis, dtype=np.float64) # floating point error # # #18044 in _libs/windows.pyx calc_skew follow this behavior # to fix the fperr to treat m2 <1e-14 as zero m2 = _zero_out_fperr(m2) m3 = _zero_out_fperr(m3) with np.errstate(invalid='ignore', divide='ignore'): result = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2 ** 1.5) dtype = values.dtype if is_float_dtype(dtype): result = result.astype(dtype) if isinstance(result, np.ndarray): result = np.where(m2 == 0, 0, result) result[count < 3] = np.nan return result else: result = 0 if m2 == 0 else result if count < 3: return np.nan return result
[ " 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 skipna : bool, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : float64\n Unless input is a float array, in which case use the same\n precision as the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1,np.nan, 1, 2])\n >>> nanops.nanskew(s)\n 1.7320508075688787\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) else: count = _get_counts(mask, axis, dtype=values.dtype) if skipna: values = values.copy() np.putmask(values, mask, 0) mean = values.sum(axis, dtype=np.float64) / count if axis is not None: mean = np.expand_dims(mean, axis) adjusted = values - mean if skipna: np.putmask(adjusted, mask, 0) adjusted2 = adjusted ** 2 adjusted4 = adjusted2 ** 2 m2 = adjusted2.sum(axis, dtype=np.float64) m4 = adjusted4.sum(axis, dtype=np.float64) with np.errstate(invalid='ignore', divide='ignore'): adj = 3 * (count - 1) ** 2 / ((count - 2) * (count - 3)) numer = count * (count + 1) * (count - 1) * m4 denom = (count - 2) * (count - 3) * m2 ** 2 # floating point error # # #18044 in _libs/windows.pyx calc_kurt follow this behavior # to fix the fperr to treat denom <1e-14 as zero numer = _zero_out_fperr(numer) denom = _zero_out_fperr(denom) if not isinstance(denom, np.ndarray): # if ``denom`` is a scalar, check these corner cases first before # doing division if count < 4: return np.nan if denom == 0: return 0 with np.errstate(invalid='ignore', divide='ignore'): result = numer / denom - adj dtype = values.dtype if is_float_dtype(dtype): result = result.astype(dtype) if isinstance(result, np.ndarray): result = np.where(denom == 0, 0, result) result[count < 4] = np.nan return result
[ "\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, default True\n mask : ndarray[bool], optional\n nan-mask if known\n\n Returns\n -------\n result : float64\n Unless input is a float array, in which case use the same\n precision as the input array.\n\n Examples\n --------\n >>> import pandas.core.nanops as nanops\n >>> s = pd.Series([1,np.nan, 1, 3, 2])\n >>> nanops.nankurt(s)\n -1.2892561983471076\n " ]
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_null_out(result, axis, mask, min_count=min_count)
[ "\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.core.nanops as nanops\n >>> s = pd.Series([1, 2, 3, np.nan])\n >>> nanops.nanprod(s)\n 6.0\n\n Returns\n --------\n The product of all elements on a given axis. ( NaNs are treated as 1)\n " ]