diff --git a/pandas/_typing.py b/pandas/_typing.py index 5f8ea79046235..9c20eb12dc7fc 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -101,11 +101,11 @@ ] Timezone = Union[str, tzinfo] -# FrameOrSeries is stricter and ensures that the same subclass of NDFrame always is -# used. E.g. `def func(a: FrameOrSeries) -> FrameOrSeries: ...` means that if a +# NDFrameT is stricter and ensures that the same subclass of NDFrame always is +# used. E.g. `def func(a: NDFrameT) -> NDFrameT: ...` means that if a # Series is passed into a function, a Series is always returned and if a DataFrame is # passed in, a DataFrame is always returned. -FrameOrSeries = TypeVar("FrameOrSeries", bound="NDFrame") +NDFrameT = TypeVar("NDFrameT", bound="NDFrame") Axis = Union[str, int] IndexLabel = Union[Hashable, Sequence[Hashable]] diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 7dd8b54c0cabf..99df6d256bc75 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -30,7 +30,7 @@ AggFuncTypeDict, AggObjType, Axis, - FrameOrSeries, + NDFrameT, ) from pandas.util._decorators import cache_readonly from pandas.util._exceptions import find_stack_level @@ -1120,7 +1120,7 @@ def apply_standard(self) -> DataFrame | Series: class GroupByApply(Apply): def __init__( self, - obj: GroupBy[FrameOrSeries], + obj: GroupBy[NDFrameT], func: AggFuncType, args, kwargs, diff --git a/pandas/core/base.py b/pandas/core/base.py index 790daa7e42b39..376360cfa392d 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -22,8 +22,8 @@ from pandas._typing import ( ArrayLike, DtypeObj, - FrameOrSeries, IndexLabel, + NDFrameT, Shape, npt, ) @@ -181,13 +181,13 @@ class SpecificationError(Exception): pass -class SelectionMixin(Generic[FrameOrSeries]): +class SelectionMixin(Generic[NDFrameT]): """ mixin implementing the selection & aggregation interface on a group-like object sub-classes need to define: obj, exclusions """ - obj: FrameOrSeries + obj: NDFrameT _selection: IndexLabel | None = None exclusions: frozenset[Hashable] _internal_names = ["_cache", "__setstate__"] diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 148b37cafbf78..a4bd0270f9451 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -15,7 +15,6 @@ import numpy as np -from pandas._typing import FrameOrSeries from pandas.errors import PerformanceWarning from pandas.core.dtypes.generic import ( @@ -28,14 +27,15 @@ from pandas.core.computation.common import result_type_many if TYPE_CHECKING: + from pandas.core.generic import NDFrame from pandas.core.indexes.api import Index def _align_core_single_unary_op( term, -) -> tuple[partial | type[FrameOrSeries], dict[str, Index] | None]: +) -> tuple[partial | type[NDFrame], dict[str, Index] | None]: - typ: partial | type[FrameOrSeries] + typ: partial | type[NDFrame] axes: dict[str, Index] | None = None if isinstance(term.value, np.ndarray): @@ -49,7 +49,7 @@ def _align_core_single_unary_op( def _zip_axes_from_type( - typ: type[FrameOrSeries], new_axes: Sequence[Index] + typ: type[NDFrame], new_axes: Sequence[Index] ) -> dict[str, Index]: return {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)} diff --git a/pandas/core/describe.py b/pandas/core/describe.py index fd45da4a3ccc7..2c4a340e8c8ea 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -22,7 +22,7 @@ import numpy as np from pandas._libs.tslibs import Timestamp -from pandas._typing import FrameOrSeries +from pandas._typing import NDFrameT from pandas.util._validators import validate_percentile from pandas.core.dtypes.common import ( @@ -45,12 +45,12 @@ def describe_ndframe( *, - obj: FrameOrSeries, + obj: NDFrameT, include: str | Sequence[str] | None, exclude: str | Sequence[str] | None, datetime_is_numeric: bool, percentiles: Sequence[float] | np.ndarray | None, -) -> FrameOrSeries: +) -> NDFrameT: """Describe series or dataframe. Called from pandas.core.generic.NDFrame.describe() @@ -91,7 +91,7 @@ def describe_ndframe( ) result = describer.describe(percentiles=percentiles) - return cast(FrameOrSeries, result) + return cast(NDFrameT, result) class NDFrameDescriberAbstract(ABC): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d770488e9ceb4..91a446dd99334 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -42,12 +42,12 @@ DtypeArg, DtypeObj, FilePathOrBuffer, - FrameOrSeries, IndexKeyFunc, IndexLabel, JSONSerializable, Level, Manager, + NDFrameT, RandomState, Renamer, StorageOptions, @@ -297,9 +297,7 @@ def _from_mgr(cls, mgr: Manager): object.__setattr__(obj, "_attrs", {}) return obj - def _as_manager( - self: FrameOrSeries, typ: str, copy: bool_t = True - ) -> FrameOrSeries: + def _as_manager(self: NDFrameT, typ: str, copy: bool_t = True) -> NDFrameT: """ Private helper function to create a DataFrame with specific manager. @@ -388,11 +386,11 @@ def flags(self) -> Flags: @final def set_flags( - self: FrameOrSeries, + self: NDFrameT, *, copy: bool_t = False, allows_duplicate_labels: bool_t | None = None, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Return a new object with updated flags. @@ -457,7 +455,7 @@ def _validate_dtype(cls, dtype) -> DtypeObj | None: # Construction @property - def _constructor(self: FrameOrSeries) -> type[FrameOrSeries]: + def _constructor(self: NDFrameT) -> type[NDFrameT]: """ Used when a manipulation result has the same dimensions as the original. @@ -704,8 +702,8 @@ def size(self) -> int: @overload def set_axis( - self: FrameOrSeries, labels, axis: Axis = ..., inplace: Literal[False] = ... - ) -> FrameOrSeries: + self: NDFrameT, labels, axis: Axis = ..., inplace: Literal[False] = ... + ) -> NDFrameT: ... @overload @@ -718,8 +716,8 @@ def set_axis(self, labels, *, inplace: Literal[True]) -> None: @overload def set_axis( - self: FrameOrSeries, labels, axis: Axis = ..., inplace: bool_t = ... - ) -> FrameOrSeries | None: + self: NDFrameT, labels, axis: Axis = ..., inplace: bool_t = ... + ) -> NDFrameT | None: ... def set_axis(self, labels, axis: Axis = 0, inplace: bool_t = False): @@ -768,7 +766,7 @@ def _set_axis(self, axis: int, labels: Index) -> None: self._clear_item_cache() @final - def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: + def swapaxes(self: NDFrameT, axis1, axis2, copy=True) -> NDFrameT: """ Interchange axes and swap values axes appropriately. @@ -806,7 +804,7 @@ def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: @final @doc(klass=_shared_doc_kwargs["klass"]) - def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: + def droplevel(self: NDFrameT, level, axis=0) -> NDFrameT: """ Return {klass} with requested index / column level(s) removed. @@ -989,7 +987,7 @@ def squeeze(self, axis=None): # Rename def rename( - self: FrameOrSeries, + self: NDFrameT, mapper: Renamer | None = None, *, index: Renamer | None = None, @@ -999,7 +997,7 @@ def rename( inplace: bool_t = False, level: Level | None = None, errors: str = "ignore", - ) -> FrameOrSeries | None: + ) -> NDFrameT | None: """ Alter axes input function or functions. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left @@ -1592,11 +1590,11 @@ def bool(self): self.__nonzero__() @final - def __abs__(self: FrameOrSeries) -> FrameOrSeries: + def __abs__(self: NDFrameT) -> NDFrameT: return self.abs() @final - def __round__(self: FrameOrSeries, decimals: int = 0) -> FrameOrSeries: + def __round__(self: NDFrameT, decimals: int = 0) -> NDFrameT: return self.round(decimals) # ------------------------------------------------------------------------- @@ -3538,8 +3536,8 @@ def _clear_item_cache(self) -> None: # Indexing Methods def take( - self: FrameOrSeries, indices, axis=0, is_copy: bool_t | None = None, **kwargs - ) -> FrameOrSeries: + self: NDFrameT, indices, axis=0, is_copy: bool_t | None = None, **kwargs + ) -> NDFrameT: """ Return the elements in the given *positional* indices along an axis. @@ -3636,7 +3634,7 @@ class max_speed ) return self._constructor(new_data).__finalize__(self, method="take") - def _take_with_is_copy(self: FrameOrSeries, indices, axis=0) -> FrameOrSeries: + def _take_with_is_copy(self: NDFrameT, indices, axis=0) -> NDFrameT: """ Internal version of the `take` method that sets the `_is_copy` attribute to keep track of the parent dataframe (using in indexing @@ -3836,7 +3834,7 @@ class animal locomotion def __getitem__(self, item): raise AbstractMethodError(self) - def _slice(self: FrameOrSeries, slobj: slice, axis=0) -> FrameOrSeries: + def _slice(self: NDFrameT, slobj: slice, axis=0) -> NDFrameT: """ Construct a slice of this container. @@ -4056,13 +4054,13 @@ def _is_view(self) -> bool_t: @final def reindex_like( - self: FrameOrSeries, + self: NDFrameT, other, method: str | None = None, copy: bool_t = True, limit=None, tolerance=None, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Return an object with matching indices as other object. @@ -4204,14 +4202,14 @@ def drop( @final def _drop_axis( - self: FrameOrSeries, + self: NDFrameT, labels, axis, level=None, errors: str = "raise", consolidate: bool_t = True, only_slice: bool_t = False, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Drop labels from specified axis. Used in the ``drop`` method internally. @@ -4307,7 +4305,7 @@ def _update_inplace(self, result, verify_is_copy: bool_t = True) -> None: self._maybe_update_cacher(verify_is_copy=verify_is_copy) @final - def add_prefix(self: FrameOrSeries, prefix: str) -> FrameOrSeries: + def add_prefix(self: NDFrameT, prefix: str) -> NDFrameT: """ Prefix labels with string `prefix`. @@ -4364,14 +4362,14 @@ def add_prefix(self: FrameOrSeries, prefix: str) -> FrameOrSeries: f = functools.partial("{prefix}{}".format, prefix=prefix) mapper = {self._info_axis_name: f} - # error: Incompatible return value type (got "Optional[FrameOrSeries]", - # expected "FrameOrSeries") + # error: Incompatible return value type (got "Optional[NDFrameT]", + # expected "NDFrameT") # error: Argument 1 to "rename" of "NDFrame" has incompatible type # "**Dict[str, partial[str]]"; expected "Union[str, int, None]" return self.rename(**mapper) # type: ignore[return-value, arg-type] @final - def add_suffix(self: FrameOrSeries, suffix: str) -> FrameOrSeries: + def add_suffix(self: NDFrameT, suffix: str) -> NDFrameT: """ Suffix labels with string `suffix`. @@ -4428,8 +4426,8 @@ def add_suffix(self: FrameOrSeries, suffix: str) -> FrameOrSeries: f = functools.partial("{}{suffix}".format, suffix=suffix) mapper = {self._info_axis_name: f} - # error: Incompatible return value type (got "Optional[FrameOrSeries]", - # expected "FrameOrSeries") + # error: Incompatible return value type (got "Optional[NDFrameT]", + # expected "NDFrameT") # error: Argument 1 to "rename" of "NDFrame" has incompatible type # "**Dict[str, partial[str]]"; expected "Union[str, int, None]" return self.rename(**mapper) # type: ignore[return-value, arg-type] @@ -4642,7 +4640,7 @@ def sort_index( optional_labels="", optional_axis="", ) - def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: + def reindex(self: NDFrameT, *args, **kwargs) -> NDFrameT: """ Conform {klass} to new index with optional filling logic. @@ -4888,8 +4886,8 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: ).__finalize__(self, method="reindex") def _reindex_axes( - self: FrameOrSeries, axes, level, limit, tolerance, method, fill_value, copy - ) -> FrameOrSeries: + self: NDFrameT, axes, level, limit, tolerance, method, fill_value, copy + ) -> NDFrameT: """Perform the reindex for all the axes.""" obj = self for a in self._AXIS_ORDERS: @@ -4928,12 +4926,12 @@ def _reindex_multi(self, axes, copy, fill_value): @final def _reindex_with_indexers( - self: FrameOrSeries, + self: NDFrameT, reindexers, fill_value=None, copy: bool_t = False, allow_dups: bool_t = False, - ) -> FrameOrSeries: + ) -> NDFrameT: """allow_dups indicates an internal call here""" # reindex doing multiple operations on different axes if indicated new_data = self._mgr @@ -4966,12 +4964,12 @@ def _reindex_with_indexers( return self._constructor(new_data).__finalize__(self) def filter( - self: FrameOrSeries, + self: NDFrameT, items=None, like: str | None = None, regex: str | None = None, axis=None, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Subset the dataframe rows or columns according to the specified index labels. @@ -5069,7 +5067,7 @@ def f(x) -> bool_t: raise TypeError("Must pass either `items`, `like`, or `regex`") @final - def head(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: + def head(self: NDFrameT, n: int = 5) -> NDFrameT: """ Return the first `n` rows. @@ -5142,7 +5140,7 @@ def head(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: return self.iloc[:n] @final - def tail(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: + def tail(self: NDFrameT, n: int = 5) -> NDFrameT: """ Return the last `n` rows. @@ -5218,7 +5216,7 @@ def tail(self: FrameOrSeries, n: int = 5) -> FrameOrSeries: @final def sample( - self: FrameOrSeries, + self: NDFrameT, n: int | None = None, frac: float | None = None, replace: bool_t = False, @@ -5226,7 +5224,7 @@ def sample( random_state: RandomState | None = None, axis: Axis | None = None, ignore_index: bool_t = False, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Return a random sample of items from an axis of object. @@ -5437,8 +5435,8 @@ def pipe( @final def __finalize__( - self: FrameOrSeries, other, method: str | None = None, **kwargs - ) -> FrameOrSeries: + self: NDFrameT, other, method: str | None = None, **kwargs + ) -> NDFrameT: """ Propagate metadata from other to self. @@ -5662,8 +5660,8 @@ def dtypes(self): return self._constructor_sliced(data, index=self._info_axis, dtype=np.object_) def astype( - self: FrameOrSeries, dtype, copy: bool_t = True, errors: str = "raise" - ) -> FrameOrSeries: + self: NDFrameT, dtype, copy: bool_t = True, errors: str = "raise" + ) -> NDFrameT: """ Cast a pandas object to a specified dtype ``dtype``. @@ -5826,10 +5824,10 @@ def astype( result = concat(results, axis=1, copy=False) result.columns = self.columns # https://github.com/python/mypy/issues/8354 - return cast(FrameOrSeries, result) + return cast(NDFrameT, result) @final - def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: + def copy(self: NDFrameT, deep: bool_t = True) -> NDFrameT: """ Make a copy of this object's indices and data. @@ -5939,11 +5937,11 @@ def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: return self._constructor(data).__finalize__(self, method="copy") @final - def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: + def __copy__(self: NDFrameT, deep: bool_t = True) -> NDFrameT: return self.copy(deep=deep) @final - def __deepcopy__(self: FrameOrSeries, memo=None) -> FrameOrSeries: + def __deepcopy__(self: NDFrameT, memo=None) -> NDFrameT: """ Parameters ---------- @@ -5954,11 +5952,11 @@ def __deepcopy__(self: FrameOrSeries, memo=None) -> FrameOrSeries: @final def _convert( - self: FrameOrSeries, + self: NDFrameT, datetime: bool_t = False, numeric: bool_t = False, timedelta: bool_t = False, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Attempt to infer better dtype for object columns @@ -5989,7 +5987,7 @@ def _convert( ).__finalize__(self) @final - def infer_objects(self: FrameOrSeries) -> FrameOrSeries: + def infer_objects(self: NDFrameT) -> NDFrameT: """ Attempt to infer better dtypes for object columns. @@ -6036,13 +6034,13 @@ def infer_objects(self: FrameOrSeries) -> FrameOrSeries: @final def convert_dtypes( - self: FrameOrSeries, + self: NDFrameT, infer_objects: bool_t = True, convert_string: bool_t = True, convert_integer: bool_t = True, convert_boolean: bool_t = True, convert_floating: bool_t = True, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Convert columns to best possible dtypes using dtypes supporting ``pd.NA``. @@ -6190,7 +6188,7 @@ def convert_dtypes( ] if len(results) > 0: # https://github.com/python/mypy/issues/8354 - return cast(FrameOrSeries, concat(results, axis=1, copy=False)) + return cast(NDFrameT, concat(results, axis=1, copy=False)) else: return self.copy() @@ -6199,14 +6197,14 @@ def convert_dtypes( @doc(**_shared_doc_kwargs) def fillna( - self: FrameOrSeries, + self: NDFrameT, value=None, method=None, axis=None, inplace: bool_t = False, limit=None, downcast=None, - ) -> FrameOrSeries | None: + ) -> NDFrameT | None: """ Fill NA/NaN values using the specified method. @@ -6412,12 +6410,12 @@ def fillna( @doc(klass=_shared_doc_kwargs["klass"]) def ffill( - self: FrameOrSeries, + self: NDFrameT, axis: None | Axis = None, inplace: bool_t = False, limit: None | int = None, downcast=None, - ) -> FrameOrSeries | None: + ) -> NDFrameT | None: """ Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``. @@ -6434,12 +6432,12 @@ def ffill( @doc(klass=_shared_doc_kwargs["klass"]) def bfill( - self: FrameOrSeries, + self: NDFrameT, axis: None | Axis = None, inplace: bool_t = False, limit: None | int = None, downcast=None, - ) -> FrameOrSeries | None: + ) -> NDFrameT | None: """ Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``. @@ -6638,7 +6636,7 @@ def replace( return result.__finalize__(self, method="replace") def interpolate( - self: FrameOrSeries, + self: NDFrameT, method: str = "linear", axis: Axis = 0, limit: int | None = None, @@ -6647,7 +6645,7 @@ def interpolate( limit_area: str | None = None, downcast: str | None = None, **kwargs, - ) -> FrameOrSeries | None: + ) -> NDFrameT | None: """ Fill NaN values using an interpolation method. @@ -7108,7 +7106,7 @@ def asof(self, where, subset=None): # Action Methods @doc(klass=_shared_doc_kwargs["klass"]) - def isna(self: FrameOrSeries) -> FrameOrSeries: + def isna(self: NDFrameT) -> NDFrameT: """ Detect missing values. @@ -7171,11 +7169,11 @@ def isna(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isna") @doc(isna, klass=_shared_doc_kwargs["klass"]) - def isnull(self: FrameOrSeries) -> FrameOrSeries: + def isnull(self: NDFrameT) -> NDFrameT: return isna(self).__finalize__(self, method="isnull") @doc(klass=_shared_doc_kwargs["klass"]) - def notna(self: FrameOrSeries) -> FrameOrSeries: + def notna(self: NDFrameT) -> NDFrameT: """ Detect existing (non-missing) values. @@ -7238,7 +7236,7 @@ def notna(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notna") @doc(notna, klass=_shared_doc_kwargs["klass"]) - def notnull(self: FrameOrSeries) -> FrameOrSeries: + def notnull(self: NDFrameT) -> NDFrameT: return notna(self).__finalize__(self, method="notnull") @final @@ -7302,14 +7300,14 @@ def _clip_with_one_bound(self, threshold, method, axis, inplace): return self.where(subset, threshold, axis=axis, inplace=inplace) def clip( - self: FrameOrSeries, + self: NDFrameT, lower=None, upper=None, axis: Axis | None = None, inplace: bool_t = False, *args, **kwargs, - ) -> FrameOrSeries | None: + ) -> NDFrameT | None: """ Trim values at input threshold(s). @@ -7462,13 +7460,13 @@ def clip( @doc(**_shared_doc_kwargs) def asfreq( - self: FrameOrSeries, + self: NDFrameT, freq, method=None, how: str | None = None, normalize: bool_t = False, fill_value=None, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Convert time series to specified frequency. @@ -7586,9 +7584,7 @@ def asfreq( ) @final - def at_time( - self: FrameOrSeries, time, asof: bool_t = False, axis=None - ) -> FrameOrSeries: + def at_time(self: NDFrameT, time, asof: bool_t = False, axis=None) -> NDFrameT: """ Select values at particular time of day (e.g., 9:30AM). @@ -7644,14 +7640,14 @@ def at_time( @final def between_time( - self: FrameOrSeries, + self: NDFrameT, start_time, end_time, include_start: bool_t | lib.NoDefault = lib.no_default, include_end: bool_t | lib.NoDefault = lib.no_default, inclusive: str | None = None, axis=None, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Select values between particular times of the day (e.g., 9:00-9:30 AM). @@ -8205,7 +8201,7 @@ def resample( ) @final - def first(self: FrameOrSeries, offset) -> FrameOrSeries: + def first(self: NDFrameT, offset) -> NDFrameT: """ Select initial periods of time series data based on a date offset. @@ -8278,7 +8274,7 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries: return self.loc[:end] @final - def last(self: FrameOrSeries, offset) -> FrameOrSeries: + def last(self: NDFrameT, offset) -> NDFrameT: """ Select final periods of time series data based on a date offset. @@ -8343,14 +8339,14 @@ def last(self: FrameOrSeries, offset) -> FrameOrSeries: @final def rank( - self: FrameOrSeries, + self: NDFrameT, axis=0, method: str = "average", numeric_only: bool_t | None = None, na_option: str = "keep", ascending: bool_t = True, pct: bool_t = False, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Compute numerical data ranks (1 through n) along axis. @@ -9205,8 +9201,8 @@ def mask( @doc(klass=_shared_doc_kwargs["klass"]) def shift( - self: FrameOrSeries, periods=1, freq=None, axis=0, fill_value=None - ) -> FrameOrSeries: + self: NDFrameT, periods=1, freq=None, axis=0, fill_value=None + ) -> NDFrameT: """ Shift index by desired number of periods with an optional time `freq`. @@ -9350,7 +9346,7 @@ def shift( return result.__finalize__(self, method="shift") @final - def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: + def slice_shift(self: NDFrameT, periods: int = 1, axis=0) -> NDFrameT: """ Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the @@ -9399,9 +9395,7 @@ def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: return new_obj.__finalize__(self, method="slice_shift") @final - def tshift( - self: FrameOrSeries, periods: int = 1, freq=None, axis: Axis = 0 - ) -> FrameOrSeries: + def tshift(self: NDFrameT, periods: int = 1, freq=None, axis: Axis = 0) -> NDFrameT: """ Shift the time index, using the index's frequency if available. @@ -9443,8 +9437,8 @@ def tshift( return self.shift(periods, freq, axis) def truncate( - self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True - ) -> FrameOrSeries: + self: NDFrameT, before=None, after=None, axis=None, copy: bool_t = True + ) -> NDFrameT: """ Truncate a Series or DataFrame before and after some index value. @@ -9600,8 +9594,8 @@ def truncate( @final def tz_convert( - self: FrameOrSeries, tz, axis=0, level=None, copy: bool_t = True - ) -> FrameOrSeries: + self: NDFrameT, tz, axis=0, level=None, copy: bool_t = True + ) -> NDFrameT: """ Convert tz-aware axis to target time zone. @@ -9658,14 +9652,14 @@ def _tz_convert(ax, tz): @final def tz_localize( - self: FrameOrSeries, + self: NDFrameT, tz, axis=0, level=None, copy: bool_t = True, ambiguous="raise", nonexistent: str = "raise", - ) -> FrameOrSeries: + ) -> NDFrameT: """ Localize tz-naive index of a Series or DataFrame to target time zone. @@ -9829,7 +9823,7 @@ def _tz_localize(ax, tz, ambiguous, nonexistent): # Numeric Methods @final - def abs(self: FrameOrSeries) -> FrameOrSeries: + def abs(self: NDFrameT) -> NDFrameT: """ Return a Series/DataFrame with absolute numeric value of each element. @@ -9897,17 +9891,17 @@ def abs(self: FrameOrSeries) -> FrameOrSeries: 3 7 40 -50 """ # error: Incompatible return value type (got "ndarray[Any, dtype[Any]]", - # expected "FrameOrSeries") + # expected "NDFrameT") return np.abs(self) # type: ignore[return-value] @final def describe( - self: FrameOrSeries, + self: NDFrameT, percentiles=None, include=None, exclude=None, datetime_is_numeric=False, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Generate descriptive statistics. @@ -10159,13 +10153,13 @@ def describe( @final def pct_change( - self: FrameOrSeries, + self: NDFrameT, periods=1, fill_method="pad", limit=None, freq=None, **kwargs, - ) -> FrameOrSeries: + ) -> NDFrameT: """ Percentage change between the current and a prior element. @@ -10289,7 +10283,7 @@ def pct_change( data = _data shifted = data.shift(periods=periods, freq=freq, axis=axis, **kwargs) - # Unsupported left operand type for / ("FrameOrSeries") + # Unsupported left operand type for / ("NDFrameT") rs = data / shifted - 1 # type: ignore[operator] if freq is not None: # Shift method is implemented differently when freq is not None @@ -11829,8 +11823,8 @@ def _doc_params(cls): def _align_as_utc( - left: FrameOrSeries, right: FrameOrSeries, join_index: Index | None -) -> tuple[FrameOrSeries, FrameOrSeries]: + left: NDFrameT, right: NDFrameT, join_index: Index | None +) -> tuple[NDFrameT, NDFrameT]: """ If we are aligning timezone-aware DatetimeIndexes and the timezones do not match, convert both to UTC. diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 37e5440903e5b..c5633b6809676 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -30,7 +30,6 @@ from pandas._libs import reduction as libreduction from pandas._typing import ( ArrayLike, - FrameOrSeries, Manager, Manager2D, SingleManager, @@ -98,7 +97,7 @@ ScalarResult = TypeVar("ScalarResult") -def generate_property(name: str, klass: type[FrameOrSeries]): +def generate_property(name: str, klass: type[DataFrame | Series]): """ Create a property for a GroupBy subclass to dispatch to DataFrame/Series. @@ -121,7 +120,9 @@ def prop(self): return property(prop) -def pin_allowlisted_properties(klass: type[FrameOrSeries], allowlist: frozenset[str]): +def pin_allowlisted_properties( + klass: type[DataFrame | Series], allowlist: frozenset[str] +): """ Create GroupBy member defs for DataFrame/Series names in a allowlist. diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 96448b319203f..89755ec5f7863 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -44,8 +44,8 @@ class providing the base-class of operations. import pandas._libs.groupby as libgroupby from pandas._typing import ( ArrayLike, - FrameOrSeries, IndexLabel, + NDFrameT, RandomState, Scalar, T, @@ -567,7 +567,7 @@ def group_selection_context(groupby: GroupBy) -> Iterator[GroupBy]: ] -class BaseGroupBy(PandasObject, SelectionMixin[FrameOrSeries]): +class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT]): _group_selection: IndexLabel | None = None _apply_allowlist: frozenset[str] = frozenset() _hidden_attrs = PandasObject._hidden_attrs | { @@ -755,7 +755,7 @@ def get_group(self, name, obj=None) -> DataFrame | Series: return obj._take_with_is_copy(inds, axis=self.axis) @final - def __iter__(self) -> Iterator[tuple[Hashable, FrameOrSeries]]: + def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: """ Groupby iterator. @@ -771,7 +771,7 @@ def __iter__(self) -> Iterator[tuple[Hashable, FrameOrSeries]]: OutputFrameOrSeries = TypeVar("OutputFrameOrSeries", bound=NDFrame) -class GroupBy(BaseGroupBy[FrameOrSeries]): +class GroupBy(BaseGroupBy[NDFrameT]): """ Class for grouping and aggregating relational data. @@ -845,7 +845,7 @@ class GroupBy(BaseGroupBy[FrameOrSeries]): @final def __init__( self, - obj: FrameOrSeries, + obj: NDFrameT, keys: _KeysArgType | None = None, axis: int = 0, level: IndexLabel | None = None, @@ -1598,7 +1598,7 @@ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform_general(func, *args, **kwargs) @final - def _wrap_transform_fast_result(self, result: FrameOrSeries) -> FrameOrSeries: + def _wrap_transform_fast_result(self, result: NDFrameT) -> NDFrameT: """ Fast transform path for aggregations. """ @@ -2061,7 +2061,7 @@ def max(self, numeric_only: bool = False, min_count: int = -1): @final @doc(_groupby_agg_method_template, fname="first", no=False, mc=-1) def first(self, numeric_only: bool = False, min_count: int = -1): - def first_compat(obj: FrameOrSeries, axis: int = 0): + def first_compat(obj: NDFrameT, axis: int = 0): def first(x: Series): """Helper function for first item that isn't NA.""" arr = x.array[notna(x.array)] @@ -2086,7 +2086,7 @@ def first(x: Series): @final @doc(_groupby_agg_method_template, fname="last", no=False, mc=-1) def last(self, numeric_only: bool = False, min_count: int = -1): - def last_compat(obj: FrameOrSeries, axis: int = 0): + def last_compat(obj: NDFrameT, axis: int = 0): def last(x: Series): """Helper function for last item that isn't NA.""" arr = x.array[notna(x.array)] diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 22270fdca4b20..02f2024091877 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -16,7 +16,7 @@ from pandas._typing import ( ArrayLike, - FrameOrSeries, + NDFrameT, ) from pandas.errors import InvalidIndexError from pandas.util._decorators import cache_readonly @@ -305,8 +305,8 @@ def ax(self) -> Index: return index def _get_grouper( - self, obj: FrameOrSeries, validate: bool = True - ) -> tuple[Any, ops.BaseGrouper, FrameOrSeries]: + self, obj: NDFrameT, validate: bool = True + ) -> tuple[Any, ops.BaseGrouper, NDFrameT]: """ Parameters ---------- @@ -319,7 +319,7 @@ def _get_grouper( a tuple of binner, grouper, obj (possibly sorted) """ self._set_grouper(obj) - # error: Value of type variable "FrameOrSeries" of "get_grouper" cannot be + # error: Value of type variable "NDFrameT" of "get_grouper" cannot be # "Optional[Any]" # error: Incompatible types in assignment (expression has type "BaseGrouper", # variable has type "None") @@ -334,7 +334,7 @@ def _get_grouper( ) # error: Incompatible return value type (got "Tuple[None, None, None]", - # expected "Tuple[Any, BaseGrouper, FrameOrSeries]") + # expected "Tuple[Any, BaseGrouper, NDFrameT]") return self.binner, self.grouper, self.obj # type: ignore[return-value] @final @@ -409,7 +409,7 @@ def _set_grouper(self, obj: NDFrame, sort: bool = False): obj = obj.take(indexer, axis=self.axis) # error: Incompatible types in assignment (expression has type - # "FrameOrSeries", variable has type "None") + # "NDFrameT", variable has type "None") self.obj = obj # type: ignore[assignment] self._gpr_index = ax return self._gpr_index @@ -697,7 +697,7 @@ def groups(self) -> dict[Hashable, np.ndarray]: def get_grouper( - obj: FrameOrSeries, + obj: NDFrameT, key=None, axis: int = 0, level=None, @@ -706,7 +706,7 @@ def get_grouper( mutated: bool = False, validate: bool = True, dropna: bool = True, -) -> tuple[ops.BaseGrouper, frozenset[Hashable], FrameOrSeries]: +) -> tuple[ops.BaseGrouper, frozenset[Hashable], NDFrameT]: """ Create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index a7ac2c7a1dba6..07353863cdc0b 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -30,7 +30,7 @@ from pandas._typing import ( ArrayLike, DtypeObj, - FrameOrSeries, + NDFrameT, Shape, npt, ) @@ -684,8 +684,8 @@ def nkeys(self) -> int: return len(self.groupings) def get_iterator( - self, data: FrameOrSeries, axis: int = 0 - ) -> Iterator[tuple[Hashable, FrameOrSeries]]: + self, data: NDFrameT, axis: int = 0 + ) -> Iterator[tuple[Hashable, NDFrameT]]: """ Groupby iterator @@ -1166,10 +1166,10 @@ def _is_indexed_like(obj, axes, axis: int) -> bool: # Splitting / application -class DataSplitter(Generic[FrameOrSeries]): +class DataSplitter(Generic[NDFrameT]): def __init__( self, - data: FrameOrSeries, + data: NDFrameT, labels: npt.NDArray[np.intp], ngroups: int, axis: int = 0, @@ -1205,7 +1205,7 @@ def __iter__(self): yield self._chop(sdata, slice(start, end)) @cache_readonly - def sorted_data(self) -> FrameOrSeries: + def sorted_data(self) -> NDFrameT: return self.data.take(self._sort_idx, axis=self.axis) def _chop(self, sdata, slice_obj: slice) -> NDFrame: diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 11ed7cb47ea3e..eb839a6e01266 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -25,8 +25,8 @@ to_offset, ) from pandas._typing import ( - FrameOrSeries, IndexLabel, + NDFrameT, T, TimedeltaConvertibleTypes, TimestampConvertibleTypes, @@ -198,9 +198,9 @@ def __getattr__(self, attr: str): # error: Signature of "obj" incompatible with supertype "BaseGroupBy" @property - def obj(self) -> FrameOrSeries: # type: ignore[override] + def obj(self) -> NDFrameT: # type: ignore[override] # error: Incompatible return value type (got "Optional[Any]", - # expected "FrameOrSeries") + # expected "NDFrameT") return self.groupby.obj # type: ignore[return-value] @property @@ -220,7 +220,7 @@ def _from_selection(self) -> bool: self.groupby.key is not None or self.groupby.level is not None ) - def _convert_obj(self, obj: FrameOrSeries) -> FrameOrSeries: + def _convert_obj(self, obj: NDFrameT) -> NDFrameT: """ Provide any conversions for the object in order to correctly handle. @@ -1260,7 +1260,7 @@ def _get_binner_for_time(self): return super()._get_binner_for_time() return self.groupby._get_period_bins(self.ax) - def _convert_obj(self, obj: FrameOrSeries) -> FrameOrSeries: + def _convert_obj(self, obj: NDFrameT) -> NDFrameT: obj = super()._convert_obj(obj) if self._from_selection: @@ -1795,12 +1795,12 @@ def _get_period_bins(self, ax: PeriodIndex): def _take_new_index( - obj: FrameOrSeries, indexer: npt.NDArray[np.intp], new_index: Index, axis: int = 0 -) -> FrameOrSeries: + obj: NDFrameT, indexer: npt.NDArray[np.intp], new_index: Index, axis: int = 0 +) -> NDFrameT: if isinstance(obj, ABCSeries): new_values = algos.take_nd(obj._values, indexer) - # error: Incompatible return value type (got "Series", expected "FrameOrSeries") + # error: Incompatible return value type (got "Series", expected "NDFrameT") return obj._constructor( # type: ignore[return-value] new_values, index=new_index, name=obj.name ) @@ -1809,7 +1809,7 @@ def _take_new_index( raise NotImplementedError("axis 1 is not supported") new_mgr = obj._mgr.reindex_indexer(new_axis=new_index, indexer=indexer, axis=1) # error: Incompatible return value type - # (got "DataFrame", expected "FrameOrSeries") + # (got "DataFrame", expected "NDFrameT") return obj._constructor(new_mgr) # type: ignore[return-value] else: raise ValueError("'obj' should be either a Series or a DataFrame") @@ -2039,13 +2039,13 @@ def _adjust_dates_anchored( def asfreq( - obj: FrameOrSeries, + obj: NDFrameT, freq, method=None, how=None, normalize: bool = False, fill_value=None, -) -> FrameOrSeries: +) -> NDFrameT: """ Utility frequency conversion method for Series/DataFrame. diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index fd53481778001..79102c2bc82ee 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -12,7 +12,6 @@ import pandas._libs.window.aggregations as window_aggregations from pandas._typing import ( Axis, - FrameOrSeries, TimedeltaConvertibleTypes, ) @@ -114,9 +113,9 @@ def _calculate_deltas( np.ndarray Diff of the times divided by the half-life """ - # error: Item "str" of "Union[str, ndarray, FrameOrSeries, None]" has no + # error: Item "str" of "Union[str, ndarray, NDFrameT, None]" has no # attribute "view" - # error: Item "None" of "Union[str, ndarray, FrameOrSeries, None]" has no + # error: Item "None" of "Union[str, ndarray, NDFrameT, None]" has no # attribute "view" _times = np.asarray( times.view(np.int64), dtype=np.float64 # type: ignore[union-attr] @@ -282,7 +281,7 @@ class ExponentialMovingWindow(BaseWindow): def __init__( self, - obj: FrameOrSeries, + obj: NDFrame, com: float | None = None, span: float | None = None, halflife: float | TimedeltaConvertibleTypes | None = None, @@ -291,7 +290,7 @@ def __init__( adjust: bool = True, ignore_na: bool = False, axis: Axis = 0, - times: str | np.ndarray | FrameOrSeries | None = None, + times: str | np.ndarray | NDFrame | None = None, method: str = "single", *, selection=None, @@ -330,7 +329,7 @@ def __init__( if not is_datetime64_ns_dtype(self.times): raise ValueError("times must be datetime64[ns] dtype.") # error: Argument 1 to "len" has incompatible type "Union[str, ndarray, - # FrameOrSeries, None]"; expected "Sized" + # NDFrameT, None]"; expected "Sized" if len(self.times) != len(obj): # type: ignore[arg-type] raise ValueError("times must be the same length as the object.") if not isinstance(self.halflife, (str, datetime.timedelta)): @@ -745,7 +744,7 @@ def _get_window_indexer(self) -> GroupbyIndexer: class OnlineExponentialMovingWindow(ExponentialMovingWindow): def __init__( self, - obj: FrameOrSeries, + obj: NDFrame, com: float | None = None, span: float | None = None, halflife: float | TimedeltaConvertibleTypes | None = None, @@ -754,7 +753,7 @@ def __init__( adjust: bool = True, ignore_na: bool = False, axis: Axis = 0, - times: str | np.ndarray | FrameOrSeries | None = None, + times: str | np.ndarray | NDFrame | None = None, engine: str = "numba", engine_kwargs: dict[str, bool] | None = None, *, diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 94a5a9797d43d..ea40e8d816f45 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -27,7 +27,7 @@ from pandas._typing import ( ArrayLike, Axis, - FrameOrSeries, + NDFrameT, WindowingRankType, ) from pandas.compat._optional import import_optional_dependency @@ -227,7 +227,7 @@ def _validate(self) -> None: if self.method not in ["table", "single"]: raise ValueError("method must be 'table' or 'single") - def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries: + def _create_data(self, obj: NDFrameT) -> NDFrameT: """ Split data into blocks & return conformed data. """ @@ -796,7 +796,7 @@ def _apply_pairwise( result.index = result_index return result - def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries: + def _create_data(self, obj: NDFrameT) -> NDFrameT: """ Split data into blocks & return conformed data. """ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 67f92c4a67e14..6e7a7593e56e0 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -22,7 +22,6 @@ from pandas._typing import ( Axis, FilePathOrBuffer, - FrameOrSeries, IndexLabel, Level, Scalar, @@ -3190,10 +3189,10 @@ def pipe(self, func: Callable, *args, **kwargs): def _validate_apply_axis_arg( - arg: FrameOrSeries | Sequence | np.ndarray, + arg: NDFrame | Sequence | np.ndarray, arg_name: str, dtype: Any | None, - data: FrameOrSeries, + data: NDFrame, ) -> np.ndarray: """ For the apply-type methods, ``axis=None`` creates ``data`` as DataFrame, and for @@ -3310,10 +3309,10 @@ def css(rgba, text_only) -> str: def _highlight_between( - data: FrameOrSeries, + data: NDFrame, props: str, - left: Scalar | Sequence | np.ndarray | FrameOrSeries | None = None, - right: Scalar | Sequence | np.ndarray | FrameOrSeries | None = None, + left: Scalar | Sequence | np.ndarray | NDFrame | None = None, + right: Scalar | Sequence | np.ndarray | NDFrame | None = None, inclusive: bool | str = True, ) -> np.ndarray: """