text
stringlengths
81
112k
Find the appropriate operation-wrappers to use when defining flex/special arithmetic, boolean, and comparison operations with the given class. Parameters ---------- cls : class Returns ------- arith_flex : function or None comp_flex : function or None arith_special : function c...
Adds the full suite of special arithmetic methods (``__add__``, ``__sub__``, etc.) to the class. Parameters ---------- cls : class special methods will be defined and pinned to this class def add_special_arithmetic_methods(cls): """ Adds the full suite of special arithmetic methods (``...
Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``) to the class. Parameters ---------- cls : class flex methods will be defined and pinned to this class def add_flex_arithmetic_methods(cls): """ Adds the full suite of flex arithmetic methods (``pow``, ``mul``, `...
align lhs and rhs Series def _align_method_SERIES(left, right, align_asobject=False): """ align lhs and rhs Series """ # ToDo: Different from _align_method_FRAME, list, tuple and ndarray # are not coerced here # because Series has inconsistencies described in #13637 if isinstance(right, ABCSeries...
If the raw op result has a non-None name (e.g. it is an Index object) and the name argument is None, then passing name to the constructor will not be enough; we still need to override the name attribute. def _construct_result(left, result, index, name, dtype=None): """ If the raw op result has a non-No...
divmod returns a tuple of like indexed series instead of a single series. def _construct_divmod_result(left, result, index, name, dtype=None): """divmod returns a tuple of like indexed series instead of a single series. """ return ( _construct_result(left, result[0], index=index, name=name, ...
Wrapper function for Series arithmetic operations, to avoid code duplication. def _arith_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ str_rep = _get_opstr(op, cls) op_name = _get_op_name(op, special) eval_kwargs =...
Wrapper function for Series arithmetic operations, to avoid code duplication. def _comp_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ op_name = _get_op_name(op, special) masker = _gen_eval_kwargs(op_name).get('masker',...
Wrapper function for Series arithmetic operations, to avoid code duplication. def _bool_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ op_name = _get_op_name(op, special) def na_op(x, y): try: resul...
Apply binary operator `func` to self, other using alignment and fill conventions determined by the fill_value, axis, and level kwargs. Parameters ---------- self : DataFrame other : Series func : binary operator fill_value : object, default None axis : {0, 1, 'columns', 'index', None}, ...
convert rhs to meet lhs dims if input is list, tuple or np.ndarray def _align_method_FRAME(left, right, axis): """ convert rhs to meet lhs dims if input is list, tuple or np.ndarray """ def to_series(right): msg = ('Unable to coerce to Series, length must be {req_len}: ' 'given {given_l...
For SparseSeries operation, coerce to float64 if the result is expected to have NaN or inf values Parameters ---------- left : SparseArray right : SparseArray opname : str Returns ------- left : SparseArray right : SparseArray def _cast_sparse_series_op(left, right, opname): ...
Wrapper function for Series arithmetic operations, to avoid code duplication. def _arith_method_SPARSE_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ op_name = _get_op_name(op, special) def wrapper(self, other): if is...
Wrapper function for Series arithmetic operations, to avoid code duplication. def _arith_method_SPARSE_ARRAY(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ op_name = _get_op_name(op, special) def wrapper(self, other): from p...
If a `periods` argument is passed to the Datetime/Timedelta Array/Index constructor, cast it to an integer. Parameters ---------- periods : None, float, int Returns ------- periods : None or int Raises ------ TypeError if periods is None, float, or int def validate_pe...
Check that the `closed` argument is among [None, "left", "right"] Parameters ---------- closed : {None, "left", "right"} Returns ------- left_closed : bool right_closed : bool Raises ------ ValueError : if argument is not among valid values def validate_endpoints(closed): ...
If the user passes a freq and another freq is inferred from passed data, require that they match. Parameters ---------- freq : DateOffset or None inferred_freq : DateOffset or None freq_infer : bool Returns ------- freq : DateOffset or None freq_infer : bool Notes ----...
Comparing a DateOffset to the string "infer" raises, so we need to be careful about comparisons. Make a dummy variable `freq_infer` to signify the case where the given freq is "infer" and set freq to None to avoid comparison trouble later on. Parameters ---------- freq : {DateOffset, None, str...
Helper for coercing an input scalar or array to i8. Parameters ---------- other : 1d array to_utc : bool, default False If True, convert the values to UTC before extracting the i8 values If False, extract the i8 values directly. Returns ------- i8 1d array def _ensure_date...
Construct a scalar type from a string. Parameters ---------- value : str Returns ------- Period, Timestamp, or Timedelta, or NaT Whatever the type of ``self._scalar_type`` is. Notes ----- This should call ``self._check_compatible_wit...
Unbox the integer value of a scalar `value`. Parameters ---------- value : Union[Period, Timestamp, Timedelta] Returns ------- int Examples -------- >>> self._unbox_scalar(Timedelta('10s')) # DOCTEST: +SKIP 10000000000 def _unbox_scala...
Verify that `self` and `other` are compatible. * DatetimeArray verifies that the timezones (if any) match * PeriodArray verifies that the freq matches * Timedelta has no verification In each case, NaT is considered compatible. Parameters ---------- other ...
Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in `python string format doc <%(URL)s>`__. Parameters ...
Find indices where elements should be inserted to maintain order. Find the indices into a sorted array `self` such that, if the corresponding elements in `value` were inserted before the indices, the order of `self` would be preserved. Parameters ---------- value : arra...
Repeat elements of an array. See Also -------- numpy.ndarray.repeat def repeat(self, repeats, *args, **kwargs): """ Repeat elements of an array. See Also -------- numpy.ndarray.repeat """ nv.validate_repeat(args, kwargs) values =...
Return a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaT values. Returns ------- Series def value_counts(self, dropna=False): """ Return a Series containing counts o...
Parameters ---------- result : a ndarray fill_value : object, default iNaT convert : string/dtype or None Returns ------- result : ndarray with values replace by the fill_value mask the result if needed, convert to the provided dtype if its not N...
Validate that a frequency is compatible with the values of a given Datetime Array/Index or Timedelta Array/Index Parameters ---------- index : DatetimeIndex or TimedeltaIndex The index on which to determine if the given frequency is valid freq : DateOffset ...
Add a timedelta-like, Tick or TimedeltaIndex-like object to self, yielding an int64 numpy array Parameters ---------- delta : {timedelta, np.timedelta64, Tick, TimedeltaIndex, ndarray[timedelta64]} Returns ------- result : ndarray[int64] ...
Add a delta of a timedeltalike return the i8 result view def _add_timedeltalike_scalar(self, other): """ Add a delta of a timedeltalike return the i8 result view """ if isna(other): # i.e np.timedelta64("NaT"), not recognized by delta_to_nanoseconds ...
Add a delta of a TimedeltaIndex return the i8 result view def _add_delta_tdi(self, other): """ Add a delta of a TimedeltaIndex return the i8 result view """ if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isins...
Add pd.NaT to self def _add_nat(self): """ Add pd.NaT to self """ if is_period_dtype(self): raise TypeError('Cannot add {cls} and {typ}' .format(cls=type(self).__name__, typ=type(NaT).__name__)) # GH#19...
Subtract pd.NaT from self def _sub_nat(self): """ Subtract pd.NaT from 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 ...
Subtract a Period Array/Index from self. This is only valid if self is itself a Period Array/Index, raises otherwise. Both objects must have the same frequency. Parameters ---------- other : PeriodIndex or PeriodArray Returns ------- result : np.ndarra...
Add or subtract array-like of integers equivalent to applying `_time_shift` pointwise. Parameters ---------- other : Index, ExtensionArray, np.ndarray integer-dtype op : {operator.add, operator.sub} Returns ------- result : same class as self...
Add or subtract array-like of DateOffset objects Parameters ---------- other : Index, np.ndarray object-dtype containing pd.DateOffset objects op : {operator.add, operator.sub} Returns ------- result : same class as self def _addsub_offset_array(sel...
Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int Number of periods to shift by. freq : pandas.DateOf...
Ensure that we are re-localized. This is for compat as we can then call this on all datetimelike arrays generally (ignored for Period/Timedelta) Parameters ---------- arg : Union[DatetimeLikeArray, DatetimeIndexOpsMixin, ndarray] ambiguous : str, bool, or bool-ndarray, ...
Return the minimum value of the Array or minimum along an axis. See Also -------- numpy.ndarray.min Index.min : Return the minimum value in an Index. Series.min : Return the minimum value in a Series. def min(self, axis=None, skipna=True, *args, **kwargs): """ ...
Return the maximum value of the Array or maximum along an axis. See Also -------- numpy.ndarray.max Index.max : Return the maximum value in an Index. Series.max : Return the maximum value in a Series. def max(self, axis=None, skipna=True, *args, **kwargs): """ ...
Wrap comparison operations to convert Period-like to PeriodDtype def _period_array_cmp(cls, op): """ Wrap comparison operations to convert Period-like to PeriodDtype """ opname = '__{name}__'.format(name=op.__name__) nat_result = opname == '__ne__' def wrapper(self, other): op = getatt...
Helper function to render a consistent error message when raising IncompatibleFrequency. Parameters ---------- left : PeriodArray right : DateOffset, Period, ndarray, or timedelta-like Raises ------ IncompatibleFrequency def _raise_on_incompatible(left, right): """ Helper func...
Construct a new PeriodArray from a sequence of Period scalars. Parameters ---------- data : Sequence of Period objects A sequence of Period objects. These are required to all have the same ``freq.`` Missing values can be indicated by ``None`` or ``pandas.NaT``. freq : str, Tick,...
If both a dtype and a freq are available, ensure they match. If only dtype is available, extract the implied freq. Parameters ---------- dtype : dtype freq : DateOffset or None Returns ------- freq : DateOffset Raises ------ ValueError : non-period dtype IncompatibleF...
Convert an datetime-like array to values Period ordinals. Parameters ---------- data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]] freq : Optional[Union[str, Tick]] Must match the `freq` on the `data` if `data` is a DatetimeIndex or Series. tz : Optional[tzin...
Construct a PeriodArray from a datetime64 array Parameters ---------- data : ndarray[datetime64[ns], datetime64[ns, tz]] freq : str or Tick tz : tzinfo, optional Returns ------- PeriodArray[freq] def _from_datetime64(cls, data, freq, tz=None): "...
Cast to DatetimeArray/Index. Parameters ---------- freq : string or DateOffset, optional Target frequency. The default is 'D' for week or longer, 'S' otherwise how : {'s', 'e', 'start', 'end'} Returns ------- DatetimeArray/Index def to_t...
Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int Number of periods to shift by. freq : pandas.DateOf...
Convert the Period Array/Index to the specified frequency `freq`. Parameters ---------- freq : str a frequency how : str {'E', 'S'} 'E', 'END', or 'FINISH' for end, 'S', 'START', or 'BEGIN' for start. Whether the elements should be aligned...
actually format my specific types def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs): """ actually format my specific types """ values = self.astype(object) if date_format: formatter = lambda dt: dt.strftime(date_format) else: ...
Parameters ---------- other : timedelta, Tick, np.timedelta64 Returns ------- result : ndarray[int64] def _add_timedeltalike_scalar(self, other): """ Parameters ---------- other : timedelta, Tick, np.timedelta64 Returns ------- ...
Parameters ---------- other : TimedeltaArray or ndarray[timedelta64] Returns ------- result : ndarray[int64] def _add_delta_tdi(self, other): """ Parameters ---------- other : TimedeltaArray or ndarray[timedelta64] Returns ------...
Add a timedelta-like, Tick, or TimedeltaIndex-like object to self, yielding a new PeriodArray Parameters ---------- other : {timedelta, np.timedelta64, Tick, TimedeltaIndex, ndarray[timedelta64]} Returns ------- result : PeriodArray def _add_de...
Arithmetic operations with timedelta-like scalars or array `other` are only valid if `other` is an integer multiple of `self.freq`. If the operation is valid, find that integer multiple. Otherwise, raise because the operation is invalid. Parameters ---------- other : ti...
Detect missing values. Treat None, NaN, INF, -INF as null. Parameters ---------- arr: ndarray or object value Returns ------- boolean ndarray or boolean def _isna_old(obj): """Detect missing values. Treat None, NaN, INF, -INF as null. Parameters ---------- arr: ndarray or obj...
Option change callback for na/inf behaviour Choose which replacement for numpy.isnan / -numpy.isfinite is used. Parameters ---------- flag: bool True means treat None, NaN, INF, -INF as null (old way), False means None and NaN are null, but INF, -INF are not null (new way). ...
Parameters ---------- arr: a numpy array fill_value: fill value, default to np.nan Returns ------- True if we can fill using this fill_value def _isna_compat(arr, fill_value=np.nan): """ Parameters ---------- arr: a numpy array fill_value: fill value, default to np.nan ...
True if two arrays, left and right, have equal non-NaN elements, and NaNs in corresponding locations. False otherwise. It is assumed that left and right are NumPy arrays of the same dtype. The behavior of this function (particularly with respect to NaNs) is not defined if the dtypes are different. ...
infer the fill value for the nan/NaT from the provided scalar/ndarray/list-like if we are a NaT, return the correct dtyped element to provide proper block construction def _infer_fill_value(val): """ infer the fill value for the nan/NaT from the provided scalar/ndarray/list-like if we are a NaT, re...
if we have a compatible fill_value and arr dtype, then fill def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
Return a dtype compat na value Parameters ---------- dtype : string / dtype compat : boolean, default True Returns ------- np.dtype or a pandas dtype Examples -------- >>> na_value_for_dtype(np.dtype('int64')) 0 >>> na_value_for_dtype(np.dtype('int64'), compat=False) ...
Return array-like containing only true/non-NaN values, possibly empty. def remove_na_arraylike(arr): """ Return array-like containing only true/non-NaN values, possibly empty. """ if is_extension_array_dtype(arr): return arr[notna(arr)] else: return arr[notna(lib.values_from_object(...
Helper function to convert DataFrame and Series to matplotlib.table Parameters ---------- ax : Matplotlib axes object data : DataFrame or Series data for table contents kwargs : keywords, optional keyword arguments which passed to matplotlib.table.table. If `rowLabels` or `c...
Create a figure with a set of subplots already made. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. Keyword arguments: naxes : int Number of required axes. Exceeded axes are set invisible. Default is ...
Render tempita templates before calling cythonize def maybe_cythonize(extensions, *args, **kwargs): """ Render tempita templates before calling cythonize """ if len(sys.argv) > 1 and 'clean' in sys.argv: # Avoid running cythonize on `python setup.py clean` # See https://github.com/cytho...
Fast transform path for aggregations def _transform_fast(self, result, obj, func_nm): """ Fast transform path for aggregations """ # if there were groups with no observations (Categorical only?) # try casting data to original dtype cast = self._transform_should_cast(func...
Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func. Parameters ---------- f : function Function to apply to each subframe. Should return True or False. dropna : Drop groups that do not pass the filt...
common agg/transform wrapping logic def _wrap_output(self, output, index, names=None): """ common agg/transform wrapping logic """ output = output[self._selection_name] if names is not None: return DataFrame(output, index=index, columns=names) else: name = self....
fast version of transform, only applicable to builtin/cythonizable functions def _transform_fast(self, func, func_nm): """ fast version of transform, only applicable to builtin/cythonizable functions """ if isinstance(func, str): func = getattr(self, func) ...
Return a copy of a Series excluding elements from groups that do not satisfy the boolean criterion specified by func. Parameters ---------- func : function To apply to each group. Should return True or False. dropna : Drop groups that do not pass the filter. True by ...
Return number of unique elements in the group. def nunique(self, dropna=True): """ Return number of unique elements in the group. """ ids, _, _ = self.grouper.group_info val = self.obj.get_values() try: sorter = np.lexsort((val, ids)) except TypeErr...
Compute count of group, excluding missing values def count(self): """ Compute count of group, excluding missing values """ ids, _, ngroups = self.grouper.group_info val = self.obj.get_values() mask = (ids != -1) & ~isna(val) ids = ensure_platform_int(ids) minlength = ng...
Calcuate pct_change of each value to previous entry in group def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): """Calcuate pct_change of each value to previous entry in group""" # TODO: Remove this conditional when #23918 is fixed if freq: return self.apply(...
sub-classes to define return a sliced object Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on def _gotitem(self, key, ndim, subset=None): """ ...
If we have categorical groupers, then we want to make sure that we have a fully reindex-output to the levels. These may have not participated in the groupings (e.g. may have all been nan groups); This can re-expand the output space def _reindex_output(self, result): """ ...
Overridden method to join grouped columns in output def _fill(self, direction, limit=None): """Overridden method to join grouped columns in output""" res = super()._fill(direction, limit=limit) output = OrderedDict( (grp.name, grp.grouper) for grp in self.grouper.groupings) ...
Compute count of group, excluding missing values def count(self): """ Compute count of group, excluding missing values """ from pandas.core.dtypes.missing import _isna_ndarraylike as _isna data, _ = self._get_data_to_aggregate() ids, _, ngroups = self.grouper.group_info mask = ...
Return DataFrame with number of distinct observations per group for each column. .. versionadded:: 0.20.0 Parameters ---------- dropna : boolean, default True Don't include NaN in the counts. Returns ------- nunique: DataFrame Examp...
Extract the ndarray or ExtensionArray from a Series or Index. For all other types, `obj` is just returned as is. Parameters ---------- obj : object For Series / Index, the underlying ExtensionArray is unboxed. For Numpy-backed ExtensionArrays, the ndarray is extracted. extract_num...
Flatten an arbitrarily nested sequence. Parameters ---------- l : sequence The non string sequence to flatten Notes ----- This doesn't consider strings sequences. Returns ------- flattened : generator def flatten(l): """ Flatten an arbitrarily nested sequence. ...
Check whether `key` is a valid boolean indexer. Parameters ---------- key : Any Only list-likes may be considered boolean indexers. All other types are not considered a boolean indexer. For array-like input, boolean ndarrays or ExtensionArrays with ``_is_boolean`` set are co...
To avoid numpy DeprecationWarnings, cast float to integer where valid. Parameters ---------- val : scalar Returns ------- outval : scalar def cast_scalar_indexer(val): """ To avoid numpy DeprecationWarnings, cast float to integer where valid. Parameters ---------- val : s...
Transform label or iterable of labels to array, for use in Index. Parameters ---------- dtype : dtype If specified, use as dtype of the resulting array, otherwise infer. Returns ------- array def index_labels_to_array(labels, dtype=None): """ Transform label or iterable of lab...
We have a null slice. def is_null_slice(obj): """ We have a null slice. """ return (isinstance(obj, slice) and obj.start is None and obj.stop is None and obj.step is None)
We have a full length slice. def is_full_slice(obj, l): """ We have a full length slice. """ return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and obj.step is None)
Evaluate possibly callable input using obj and kwargs if it is callable, otherwise return as it is. Parameters ---------- maybe_callable : possibly a callable obj : NDFrame **kwargs def apply_if_callable(maybe_callable, obj, **kwargs): """ Evaluate possibly callable input using obj and...
Helper function to standardize a supplied mapping. .. versionadded:: 0.21.0 Parameters ---------- into : instance or subclass of collections.abc.Mapping Must be a class, an initialized collections.defaultdict, or an instance of a collections.abc.Mapping subclass. Returns -----...
Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. If receives `None`, returns np.rand...
Apply a function ``func`` to object ``obj`` either by passing obj as the first argument to the function or, in the case that the func is a tuple, interpret the first element of the tuple as a function and pass the obj to that function as a keyword argument whose key is the value of the second element of...
Returns a function that will map names/labels, dependent if mapper is a dict, Series or just a function. def _get_rename_function(mapper): """ Returns a function that will map names/labels, dependent if mapper is a dict, Series or just a function. """ if isinstance(mapper, (abc.Mapping, ABCSeri...
return the correct fill value for the dtype of the values def _get_fill_value(dtype, fill_value=None, fill_value_typ=None): """ return the correct fill value for the dtype of the values """ if fill_value is not None: return fill_value if _na_ok_dtype(dtype): if fill_value_typ is None: ...
utility to get the values view, mask, dtype if necessary copy and mask using the specified fill_value copy = True will force the copy def _get_values(values, skipna, fill_value=None, fill_value_typ=None, isfinite=False, copy=True, mask=None): """ utility to get the values view, mask, dtype ...
wrap our results if needed def _wrap_results(result, dtype, fill_value=None): """ wrap our results if needed """ 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): ...
Return the missing value for `values` Parameters ---------- values : ndarray axis : int or None axis for the reduction Returns ------- result : scalar or ndarray For 1-D values, returns a scalar of the correct missing type. For 2-D values, returns a 1-D array where ...
Check if any elements along an axis evaluate to True. Parameters ---------- values : ndarray axis : int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns ------- result : bool Examples -------- >>> import pandas.core...
Check if all elements along an axis evaluate to True. Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns ------- result : bool Examples -------- >>> import pandas.core....
Sum the elements along an axis ignoring NaNs Parameters ---------- values : ndarray[dtype] axis: int, optional skipna : bool, default True min_count: int, default 0 mask : ndarray[bool], optional nan-mask if known Returns ------- result : dtype Examples -------...
Compute the mean of the element along an axis ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns ------- result : float Unless input is a float array, in which...
Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns ------- result : float Unless input is a float array, in which case use the same precision as the input array. Exa...
Compute the standard deviation along given axis while ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number ...