diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0c11e0d469155..876d86a68f0db 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -298,11 +298,6 @@ repos: files: ^pandas/core/ exclude: ^pandas/core/api\.py$ types: [python] - - id: no-bool-in-core-generic - name: Use bool_t instead of bool in pandas/core/generic.py - entry: python scripts/no_bool_in_generic.py - language: python - files: ^pandas/core/generic\.py$ - id: no-return-exception name: Use raise instead of return for exceptions language: pygrep diff --git a/doc/redirects.csv b/doc/redirects.csv index 8b6d4dae94316..1f12ba08b8005 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -325,7 +325,6 @@ generated/pandas.DataFrame.axes,../reference/api/pandas.DataFrame.axes generated/pandas.DataFrame.between_time,../reference/api/pandas.DataFrame.between_time generated/pandas.DataFrame.bfill,../reference/api/pandas.DataFrame.bfill generated/pandas.DataFrame.blocks,../reference/api/pandas.DataFrame.blocks -generated/pandas.DataFrame.bool,../reference/api/pandas.DataFrame.bool generated/pandas.DataFrame.boxplot,../reference/api/pandas.DataFrame.boxplot generated/pandas.DataFrame.clip,../reference/api/pandas.DataFrame.clip generated/pandas.DataFrame.clip_lower,../reference/api/pandas.DataFrame.clip_lower @@ -930,7 +929,6 @@ generated/pandas.Series.between,../reference/api/pandas.Series.between generated/pandas.Series.between_time,../reference/api/pandas.Series.between_time generated/pandas.Series.bfill,../reference/api/pandas.Series.bfill generated/pandas.Series.blocks,../reference/api/pandas.Series.blocks -generated/pandas.Series.bool,../reference/api/pandas.Series.bool generated/pandas.Series.cat.add_categories,../reference/api/pandas.Series.cat.add_categories generated/pandas.Series.cat.as_ordered,../reference/api/pandas.Series.cat.as_ordered generated/pandas.Series.cat.as_unordered,../reference/api/pandas.Series.cat.as_unordered diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index 8da87968cecae..149498a4d2b85 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -48,7 +48,6 @@ Conversion DataFrame.convert_dtypes DataFrame.infer_objects DataFrame.copy - DataFrame.bool DataFrame.to_numpy Indexing, iteration diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 749c26d2f0eed..02a9921bc252d 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -47,7 +47,6 @@ Conversion Series.convert_dtypes Series.infer_objects Series.copy - Series.bool Series.to_numpy Series.to_period Series.to_timestamp diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst index f7d89110e6c8f..73b7a0a7bc333 100644 --- a/doc/source/user_guide/basics.rst +++ b/doc/source/user_guide/basics.rst @@ -299,8 +299,7 @@ Boolean reductions ~~~~~~~~~~~~~~~~~~ You can apply the reductions: :attr:`~DataFrame.empty`, :meth:`~DataFrame.any`, -:meth:`~DataFrame.all`, and :meth:`~DataFrame.bool` to provide a -way to summarize a boolean result. +:meth:`~DataFrame.all`. .. ipython:: python diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index b8cb2c324d132..45fa01859a8ea 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -104,9 +104,11 @@ Deprecations Removal of prior version deprecations/changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - All arguments except the first ``path``-like argument in IO writers are now keyword only (:issue:`54229`) +- Removed ``DataFrame.bool`` and ``Series.bool`` (:issue:`51756`) - Removed ``DataFrame.first`` and ``DataFrame.last`` (:issue:`53710`) - Removed ``DataFrameGroupBy.grouper`` and ``SeriesGroupBy.grouper`` (:issue:`56521`) - Removed ``DataFrameGroupby.fillna`` and ``SeriesGroupBy.fillna``` (:issue:`55719`) +- Removed ``Series.__int__`` and ``Series.__float__``. Call ``int(Series.iloc[0])`` or ``float(Series.iloc[0])`` instead. (:issue:`51131`) - Removed ``Series.ravel`` (:issue:`56053`) - Removed ``Series.view`` (:issue:`56054`) - Removed ``axis`` argument from :meth:`DataFrame.groupby`, :meth:`Series.groupby`, :meth:`DataFrame.rolling`, :meth:`Series.rolling`, :meth:`DataFrame.resample`, and :meth:`Series.resample` (:issue:`51203`) diff --git a/pandas/conftest.py b/pandas/conftest.py index 54d7122cd73de..868bd365fa0ba 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -161,11 +161,6 @@ def pytest_collection_modifyitems(items, config) -> None: "to_pydatetime", "The behavior of DatetimeProperties.to_pydatetime is deprecated", ), - ( - "pandas.core.generic.NDFrame.bool", - "(Series|DataFrame).bool is now deprecated and will be removed " - "in future version of pandas", - ), ( "pandas.core.generic.NDFrame.first", "first is deprecated and will be removed in a future version. " diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3c71784ad81c4..5459e755b268d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -228,9 +228,6 @@ } -bool_t = bool # Need alias because NDFrame has def bool: - - class NDFrame(PandasObject, indexing.IndexingMixin): """ N-dimensional analogue of DataFrame. Store multi-dimensional in a @@ -274,7 +271,7 @@ def _init_mgr( mgr: Manager, axes: dict[Literal["index", "columns"], Axes | None], dtype: DtypeObj | None = None, - copy: bool_t = False, + copy: bool = False, ) -> Manager: """passed a manager and a axes dict""" for a, axe in axes.items(): @@ -408,8 +405,8 @@ def flags(self) -> Flags: def set_flags( self, *, - copy: bool_t = False, - allows_duplicate_labels: bool_t | None = None, + copy: bool = False, + allows_duplicate_labels: bool | None = None, ) -> Self: """ Return a new object with updated flags. @@ -711,7 +708,7 @@ def set_axis( labels, *, axis: Axis = 0, - copy: bool_t | None = None, + copy: bool | None = None, ) -> Self: """ Assign desired index to given axis. @@ -755,9 +752,7 @@ def set_axis( return self._set_axis_nocheck(labels, axis, inplace=False, copy=copy) @final - def _set_axis_nocheck( - self, labels, axis: Axis, inplace: bool_t, copy: bool_t | None - ): + def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool, copy: bool | None): if inplace: setattr(self, self._get_axis_name(axis), labels) else: @@ -777,7 +772,7 @@ def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None: self._mgr.set_axis(axis, labels) @final - def swapaxes(self, axis1: Axis, axis2: Axis, copy: bool_t | None = None) -> Self: + def swapaxes(self, axis1: Axis, axis2: Axis, copy: bool | None = None) -> Self: """ Interchange axes and swap values axes appropriately. @@ -1036,8 +1031,8 @@ def _rename( index: Renamer | None = None, columns: Renamer | None = None, axis: Axis | None = None, - copy: bool_t | None = None, - inplace: bool_t = False, + copy: bool | None = None, + inplace: bool = False, level: Level | None = None, errors: str = "ignore", ) -> Self | None: @@ -1107,7 +1102,7 @@ def rename_axis( index=..., columns=..., axis: Axis = ..., - copy: bool_t | None = ..., + copy: bool | None = ..., inplace: Literal[False] = ..., ) -> Self: ... @@ -1120,7 +1115,7 @@ def rename_axis( index=..., columns=..., axis: Axis = ..., - copy: bool_t | None = ..., + copy: bool | None = ..., inplace: Literal[True], ) -> None: ... @@ -1133,8 +1128,8 @@ def rename_axis( index=..., columns=..., axis: Axis = ..., - copy: bool_t | None = ..., - inplace: bool_t = ..., + copy: bool | None = ..., + inplace: bool = ..., ) -> Self | None: ... @@ -1145,8 +1140,8 @@ def rename_axis( index=lib.no_default, columns=lib.no_default, axis: Axis = 0, - copy: bool_t | None = None, - inplace: bool_t = False, + copy: bool | None = None, + inplace: bool = False, ) -> Self | None: """ Set the name of the axis for the index or columns. @@ -1312,7 +1307,7 @@ class name @final def _set_axis_name( - self, name, axis: Axis = 0, inplace: bool_t = False, copy: bool_t | None = True + self, name, axis: Axis = 0, inplace: bool = False, copy: bool | None = True ): """ Set the name(s) of the axis. @@ -1382,13 +1377,13 @@ def _set_axis_name( # Comparison Methods @final - def _indexed_same(self, other) -> bool_t: + def _indexed_same(self, other) -> bool: return all( self._get_axis(a).equals(other._get_axis(a)) for a in self._AXIS_ORDERS ) @final - def equals(self, other: object) -> bool_t: + def equals(self, other: object) -> bool: """ Test whether two objects contain the same elements. @@ -1526,73 +1521,6 @@ def __nonzero__(self) -> NoReturn: __bool__ = __nonzero__ - @final - def bool(self) -> bool_t: - """ - Return the bool of a single element Series or DataFrame. - - .. deprecated:: 2.1.0 - - bool is deprecated and will be removed in future version of pandas. - For ``Series`` use ``pandas.Series.item``. - - This must be a boolean scalar value, either True or False. It will raise a - ValueError if the Series or DataFrame does not have exactly 1 element, or that - element is not boolean (integer values 0 and 1 will also raise an exception). - - Returns - ------- - bool - The value in the Series or DataFrame. - - See Also - -------- - Series.astype : Change the data type of a Series, including to boolean. - DataFrame.astype : Change the data type of a DataFrame, including to boolean. - numpy.bool_ : NumPy boolean data type, used by pandas for boolean values. - - Examples - -------- - The method will only work for single element objects with a boolean value: - - >>> pd.Series([True]).bool() # doctest: +SKIP - True - >>> pd.Series([False]).bool() # doctest: +SKIP - False - - >>> pd.DataFrame({"col": [True]}).bool() # doctest: +SKIP - True - >>> pd.DataFrame({"col": [False]}).bool() # doctest: +SKIP - False - - This is an alternative method and will only work - for single element objects with a boolean value: - - >>> pd.Series([True]).item() # doctest: +SKIP - True - >>> pd.Series([False]).item() # doctest: +SKIP - False - """ - - warnings.warn( - f"{type(self).__name__}.bool is now deprecated and will be removed " - "in future version of pandas", - FutureWarning, - stacklevel=find_stack_level(), - ) - v = self.squeeze() - if isinstance(v, (bool, np.bool_)): - return bool(v) - elif is_scalar(v): - raise ValueError( - "bool cannot act on a non-boolean single element " - f"{type(self).__name__}" - ) - - self.__nonzero__() - # for mypy (__nonzero__ raises) - return True - @final def abs(self) -> Self: """ @@ -1681,7 +1609,7 @@ def __round__(self, decimals: int = 0) -> Self: # have consistent precedence and validation logic throughout the library. @final - def _is_level_reference(self, key: Level, axis: Axis = 0) -> bool_t: + def _is_level_reference(self, key: Level, axis: Axis = 0) -> bool: """ Test whether a key is a level reference for a given axis. @@ -1712,7 +1640,7 @@ def _is_level_reference(self, key: Level, axis: Axis = 0) -> bool_t: ) @final - def _is_label_reference(self, key: Level, axis: Axis = 0) -> bool_t: + def _is_label_reference(self, key: Level, axis: Axis = 0) -> bool: """ Test whether a key is a label reference for a given axis. @@ -1742,7 +1670,7 @@ def _is_label_reference(self, key: Level, axis: Axis = 0) -> bool_t: ) @final - def _is_label_or_level_reference(self, key: Level, axis: AxisInt = 0) -> bool_t: + def _is_label_or_level_reference(self, key: Level, axis: AxisInt = 0) -> bool: """ Test whether a key is a label or level reference for a given axis. @@ -2019,12 +1947,12 @@ def __len__(self) -> int: return len(self._info_axis) @final - def __contains__(self, key) -> bool_t: + def __contains__(self, key) -> bool: """True if the key is in the info axis""" return key in self._info_axis @property - def empty(self) -> bool_t: + def empty(self) -> bool: """ Indicator whether Series/DataFrame is empty. @@ -2219,13 +2147,13 @@ def to_excel( na_rep: str = "", float_format: str | None = None, columns: Sequence[Hashable] | None = None, - header: Sequence[Hashable] | bool_t = True, - index: bool_t = True, + header: Sequence[Hashable] | bool = True, + index: bool = True, index_label: IndexLabel | None = None, startrow: int = 0, startcol: int = 0, engine: Literal["openpyxl", "xlsxwriter"] | None = None, - merge_cells: bool_t = True, + merge_cells: bool = True, inf_rep: str = "inf", freeze_panes: tuple[int, int] | None = None, storage_options: StorageOptions | None = None, @@ -2384,12 +2312,12 @@ def to_json( | None = None, date_format: str | None = None, double_precision: int = 10, - force_ascii: bool_t = True, + force_ascii: bool = True, date_unit: TimeUnit = "ms", default_handler: Callable[[Any], JSONSerializable] | None = None, - lines: bool_t = False, + lines: bool = False, compression: CompressionOptions = "infer", - index: bool_t | None = None, + index: bool | None = None, indent: int | None = None, storage_options: StorageOptions | None = None, mode: Literal["a", "w"] = "w", @@ -2669,12 +2597,12 @@ def to_hdf( mode: Literal["a", "w", "r+"] = "a", complevel: int | None = None, complib: Literal["zlib", "lzo", "bzip2", "blosc"] | None = None, - append: bool_t = False, + append: bool = False, format: Literal["fixed", "table"] | None = None, - index: bool_t = True, + index: bool = True, min_itemsize: int | dict[str, int] | None = None, nan_rep=None, - dropna: bool_t | None = None, + dropna: bool | None = None, data_columns: Literal[True] | list[str] | None = None, errors: OpenFileErrors = "strict", encoding: str = "UTF-8", @@ -2821,7 +2749,7 @@ def to_sql( *, schema: str | None = None, if_exists: Literal["fail", "replace", "append"] = "fail", - index: bool_t = True, + index: bool = True, index_label: IndexLabel | None = None, chunksize: int | None = None, dtype: DtypeArg | None = None, @@ -3112,7 +3040,7 @@ def to_pickle( @final def to_clipboard( - self, *, excel: bool_t = True, sep: str | None = None, **kwargs + self, *, excel: bool = True, sep: str | None = None, **kwargs ) -> None: r""" Copy object to the system clipboard. @@ -3281,22 +3209,22 @@ def to_latex( buf: None = ..., *, columns: Sequence[Hashable] | None = ..., - header: bool_t | SequenceNotStr[str] = ..., - index: bool_t = ..., + header: bool | SequenceNotStr[str] = ..., + index: bool = ..., na_rep: str = ..., formatters: FormattersType | None = ..., float_format: FloatFormatType | None = ..., - sparsify: bool_t | None = ..., - index_names: bool_t = ..., - bold_rows: bool_t = ..., + sparsify: bool | None = ..., + index_names: bool = ..., + bold_rows: bool = ..., column_format: str | None = ..., - longtable: bool_t | None = ..., - escape: bool_t | None = ..., + longtable: bool | None = ..., + escape: bool | None = ..., encoding: str | None = ..., decimal: str = ..., - multicolumn: bool_t | None = ..., + multicolumn: bool | None = ..., multicolumn_format: str | None = ..., - multirow: bool_t | None = ..., + multirow: bool | None = ..., caption: str | tuple[str, str] | None = ..., label: str | None = ..., position: str | None = ..., @@ -3309,22 +3237,22 @@ def to_latex( buf: FilePath | WriteBuffer[str], *, columns: Sequence[Hashable] | None = ..., - header: bool_t | SequenceNotStr[str] = ..., - index: bool_t = ..., + header: bool | SequenceNotStr[str] = ..., + index: bool = ..., na_rep: str = ..., formatters: FormattersType | None = ..., float_format: FloatFormatType | None = ..., - sparsify: bool_t | None = ..., - index_names: bool_t = ..., - bold_rows: bool_t = ..., + sparsify: bool | None = ..., + index_names: bool = ..., + bold_rows: bool = ..., column_format: str | None = ..., - longtable: bool_t | None = ..., - escape: bool_t | None = ..., + longtable: bool | None = ..., + escape: bool | None = ..., encoding: str | None = ..., decimal: str = ..., - multicolumn: bool_t | None = ..., + multicolumn: bool | None = ..., multicolumn_format: str | None = ..., - multirow: bool_t | None = ..., + multirow: bool | None = ..., caption: str | tuple[str, str] | None = ..., label: str | None = ..., position: str | None = ..., @@ -3337,22 +3265,22 @@ def to_latex( buf: FilePath | WriteBuffer[str] | None = None, *, columns: Sequence[Hashable] | None = None, - header: bool_t | SequenceNotStr[str] = True, - index: bool_t = True, + header: bool | SequenceNotStr[str] = True, + index: bool = True, na_rep: str = "NaN", formatters: FormattersType | None = None, float_format: FloatFormatType | None = None, - sparsify: bool_t | None = None, - index_names: bool_t = True, - bold_rows: bool_t = False, + sparsify: bool | None = None, + index_names: bool = True, + bold_rows: bool = False, column_format: str | None = None, - longtable: bool_t | None = None, - escape: bool_t | None = None, + longtable: bool | None = None, + escape: bool | None = None, encoding: str | None = None, decimal: str = ".", - multicolumn: bool_t | None = None, + multicolumn: bool | None = None, multicolumn_format: str | None = None, - multirow: bool_t | None = None, + multirow: bool | None = None, caption: str | tuple[str, str] | None = None, label: str | None = None, position: str | None = None, @@ -3694,8 +3622,8 @@ def to_csv( na_rep: str = ..., float_format: str | Callable | None = ..., columns: Sequence[Hashable] | None = ..., - header: bool_t | list[str] = ..., - index: bool_t = ..., + header: bool | list[str] = ..., + index: bool = ..., index_label: IndexLabel | None = ..., mode: str = ..., encoding: str | None = ..., @@ -3705,7 +3633,7 @@ def to_csv( lineterminator: str | None = ..., chunksize: int | None = ..., date_format: str | None = ..., - doublequote: bool_t = ..., + doublequote: bool = ..., escapechar: str | None = ..., decimal: str = ..., errors: OpenFileErrors = ..., @@ -3722,8 +3650,8 @@ def to_csv( na_rep: str = ..., float_format: str | Callable | None = ..., columns: Sequence[Hashable] | None = ..., - header: bool_t | list[str] = ..., - index: bool_t = ..., + header: bool | list[str] = ..., + index: bool = ..., index_label: IndexLabel | None = ..., mode: str = ..., encoding: str | None = ..., @@ -3733,7 +3661,7 @@ def to_csv( lineterminator: str | None = ..., chunksize: int | None = ..., date_format: str | None = ..., - doublequote: bool_t = ..., + doublequote: bool = ..., escapechar: str | None = ..., decimal: str = ..., errors: OpenFileErrors = ..., @@ -3754,8 +3682,8 @@ def to_csv( na_rep: str = "", float_format: str | Callable | None = None, columns: Sequence[Hashable] | None = None, - header: bool_t | list[str] = True, - index: bool_t = True, + header: bool | list[str] = True, + index: bool = True, index_label: IndexLabel | None = None, mode: str = "w", encoding: str | None = None, @@ -3765,7 +3693,7 @@ def to_csv( lineterminator: str | None = None, chunksize: int | None = None, date_format: str | None = None, - doublequote: bool_t = True, + doublequote: bool = True, escapechar: str | None = None, decimal: str = ".", errors: OpenFileErrors = "strict", @@ -4059,7 +3987,7 @@ def xs( key: IndexLabel, axis: Axis = 0, level: IndexLabel | None = None, - drop_level: bool_t = True, + drop_level: bool = True, ) -> Self: """ Return cross-section from the Series/DataFrame. @@ -4302,7 +4230,7 @@ def __delitem__(self, key) -> None: # Unsorted @final - def _check_inplace_and_allows_duplicate_labels(self, inplace: bool_t) -> None: + def _check_inplace_and_allows_duplicate_labels(self, inplace: bool) -> None: if inplace and not self.flags.allows_duplicate_labels: raise ValueError( "Cannot specify 'inplace=True' when " @@ -4370,7 +4298,7 @@ def get(self, key, default=None): @final @property - def _is_view(self) -> bool_t: + def _is_view(self) -> bool: """Return boolean indicating if self is view of another array""" return self._mgr.is_view @@ -4379,7 +4307,7 @@ def reindex_like( self, other, method: Literal["backfill", "bfill", "pad", "ffill", "nearest"] | None = None, - copy: bool_t | None = None, + copy: bool | None = None, limit: int | None = None, tolerance=None, ) -> Self: @@ -4536,7 +4464,7 @@ def drop( index: IndexLabel | ListLike = ..., columns: IndexLabel | ListLike = ..., level: Level | None = ..., - inplace: bool_t = ..., + inplace: bool = ..., errors: IgnoreRaise = ..., ) -> Self | None: ... @@ -4549,7 +4477,7 @@ def drop( index: IndexLabel | ListLike = None, columns: IndexLabel | ListLike = None, level: Level | None = None, - inplace: bool_t = False, + inplace: bool = False, errors: IgnoreRaise = "raise", ) -> Self | None: inplace = validate_bool_kwarg(inplace, "inplace") @@ -4587,7 +4515,7 @@ def _drop_axis( axis, level=None, errors: IgnoreRaise = "raise", - only_slice: bool_t = False, + only_slice: bool = False, ) -> Self: """ Drop labels from specified axis. Used in the ``drop`` method @@ -4832,11 +4760,11 @@ def sort_values( self, *, axis: Axis = ..., - ascending: bool_t | Sequence[bool_t] = ..., + ascending: bool | Sequence[bool] = ..., inplace: Literal[False] = ..., kind: SortKind = ..., na_position: NaPosition = ..., - ignore_index: bool_t = ..., + ignore_index: bool = ..., key: ValueKeyFunc = ..., ) -> Self: ... @@ -4846,11 +4774,11 @@ def sort_values( self, *, axis: Axis = ..., - ascending: bool_t | Sequence[bool_t] = ..., + ascending: bool | Sequence[bool] = ..., inplace: Literal[True], kind: SortKind = ..., na_position: NaPosition = ..., - ignore_index: bool_t = ..., + ignore_index: bool = ..., key: ValueKeyFunc = ..., ) -> None: ... @@ -4860,11 +4788,11 @@ def sort_values( self, *, axis: Axis = ..., - ascending: bool_t | Sequence[bool_t] = ..., - inplace: bool_t = ..., + ascending: bool | Sequence[bool] = ..., + inplace: bool = ..., kind: SortKind = ..., na_position: NaPosition = ..., - ignore_index: bool_t = ..., + ignore_index: bool = ..., key: ValueKeyFunc = ..., ) -> Self | None: ... @@ -4873,11 +4801,11 @@ def sort_values( self, *, axis: Axis = 0, - ascending: bool_t | Sequence[bool_t] = True, - inplace: bool_t = False, + ascending: bool | Sequence[bool] = True, + inplace: bool = False, kind: SortKind = "quicksort", na_position: NaPosition = "last", - ignore_index: bool_t = False, + ignore_index: bool = False, key: ValueKeyFunc | None = None, ) -> Self | None: """ @@ -5030,12 +4958,12 @@ def sort_index( *, axis: Axis = ..., level: IndexLabel = ..., - ascending: bool_t | Sequence[bool_t] = ..., + ascending: bool | Sequence[bool] = ..., inplace: Literal[True], kind: SortKind = ..., na_position: NaPosition = ..., - sort_remaining: bool_t = ..., - ignore_index: bool_t = ..., + sort_remaining: bool = ..., + ignore_index: bool = ..., key: IndexKeyFunc = ..., ) -> None: ... @@ -5046,12 +4974,12 @@ def sort_index( *, axis: Axis = ..., level: IndexLabel = ..., - ascending: bool_t | Sequence[bool_t] = ..., + ascending: bool | Sequence[bool] = ..., inplace: Literal[False] = ..., kind: SortKind = ..., na_position: NaPosition = ..., - sort_remaining: bool_t = ..., - ignore_index: bool_t = ..., + sort_remaining: bool = ..., + ignore_index: bool = ..., key: IndexKeyFunc = ..., ) -> Self: ... @@ -5062,12 +4990,12 @@ def sort_index( *, axis: Axis = ..., level: IndexLabel = ..., - ascending: bool_t | Sequence[bool_t] = ..., - inplace: bool_t = ..., + ascending: bool | Sequence[bool] = ..., + inplace: bool = ..., kind: SortKind = ..., na_position: NaPosition = ..., - sort_remaining: bool_t = ..., - ignore_index: bool_t = ..., + sort_remaining: bool = ..., + ignore_index: bool = ..., key: IndexKeyFunc = ..., ) -> Self | None: ... @@ -5077,12 +5005,12 @@ def sort_index( *, axis: Axis = 0, level: IndexLabel | None = None, - ascending: bool_t | Sequence[bool_t] = True, - inplace: bool_t = False, + ascending: bool | Sequence[bool] = True, + inplace: bool = False, kind: SortKind = "quicksort", na_position: NaPosition = "last", - sort_remaining: bool_t = True, - ignore_index: bool_t = False, + sort_remaining: bool = True, + ignore_index: bool = False, key: IndexKeyFunc | None = None, ) -> Self | None: inplace = validate_bool_kwarg(inplace, "inplace") @@ -5137,7 +5065,7 @@ def reindex( columns=None, axis: Axis | None = None, method: ReindexMethod | None = None, - copy: bool_t | None = None, + copy: bool | None = None, level: Level | None = None, fill_value: Scalar | None = np.nan, limit: int | None = None, @@ -5408,7 +5336,7 @@ def _reindex_axes( tolerance, method, fill_value: Scalar | None, - copy: bool_t | None, + copy: bool | None, ) -> Self: """Perform the reindex for all the axes.""" obj = self @@ -5434,7 +5362,7 @@ def _reindex_axes( return obj - def _needs_reindex_multi(self, axes, method, level: Level | None) -> bool_t: + def _needs_reindex_multi(self, axes, method, level: Level | None) -> bool: """Check if we do need a multi reindex.""" return ( (common.count_not_none(*axes.values()) == self._AXIS_LEN) @@ -5453,8 +5381,8 @@ def _reindex_with_indexers( self, reindexers, fill_value=None, - copy: bool_t | None = False, - allow_dups: bool_t = False, + copy: bool | None = False, + allow_dups: bool = False, ) -> Self: """allow_dups indicates an internal call here""" # reindex doing multiple operations on different axes if indicated @@ -5588,7 +5516,7 @@ def filter( return self.reindex(**{name: items}) # type: ignore[misc] elif like: - def f(x) -> bool_t: + def f(x) -> bool: assert like is not None # needed for mypy return like in ensure_str(x) @@ -5596,7 +5524,7 @@ def f(x) -> bool_t: return self.loc(axis=axis)[values] elif regex: - def f(x) -> bool_t: + def f(x) -> bool: return matcher.search(ensure_str(x)) is not None matcher = re.compile(regex) @@ -5794,11 +5722,11 @@ def sample( self, n: int | None = None, frac: float | None = None, - replace: bool_t = False, + replace: bool = False, weights=None, random_state: RandomState | None = None, axis: Axis | None = None, - ignore_index: bool_t = False, + ignore_index: bool = False, ) -> Self: """ Return a random sample of items from an axis of object. @@ -6214,7 +6142,7 @@ def _consolidate(self): @final @property - def _is_mixed_type(self) -> bool_t: + def _is_mixed_type(self) -> bool: if self._mgr.is_single_block: # Includes all Series cases return False @@ -6285,7 +6213,7 @@ def dtypes(self): @final def astype( - self, dtype, copy: bool_t | None = None, errors: IgnoreRaise = "raise" + self, dtype, copy: bool | None = None, errors: IgnoreRaise = "raise" ) -> Self: """ Cast a pandas object to a specified dtype ``dtype``. @@ -6477,7 +6405,7 @@ def astype( return cast(Self, result) @final - def copy(self, deep: bool_t | None = True) -> Self: + def copy(self, deep: bool | None = True) -> Self: """ Make a copy of this object's indices and data. @@ -6616,7 +6544,7 @@ def copy(self, deep: bool_t | None = True) -> Self: ) @final - def __copy__(self, deep: bool_t = True) -> Self: + def __copy__(self, deep: bool = True) -> Self: return self.copy(deep=deep) @final @@ -6630,7 +6558,7 @@ def __deepcopy__(self, memo=None) -> Self: return self.copy(deep=True) @final - def infer_objects(self, copy: bool_t | None = None) -> Self: + def infer_objects(self, copy: bool | None = None) -> Self: """ Attempt to infer better dtypes for object columns. @@ -6693,11 +6621,11 @@ def infer_objects(self, copy: bool_t | None = None) -> Self: @final def convert_dtypes( self, - 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, + infer_objects: bool = True, + convert_string: bool = True, + convert_integer: bool = True, + convert_boolean: bool = True, + convert_floating: bool = True, dtype_backend: DtypeBackend = "numpy_nullable", ) -> Self: """ @@ -6865,7 +6793,7 @@ def _pad_or_backfill( method: Literal["ffill", "bfill", "pad", "backfill"], *, axis: None | Axis = None, - inplace: bool_t = False, + inplace: bool = False, limit: None | int = None, limit_area: Literal["inside", "outside"] | None = None, downcast: dict | None = None, @@ -6934,7 +6862,7 @@ def fillna( *, method: FillnaOptions | None = ..., axis: Axis | None = ..., - inplace: bool_t = ..., + inplace: bool = ..., limit: int | None = ..., downcast: dict | None = ..., ) -> Self | None: @@ -6951,7 +6879,7 @@ def fillna( *, method: FillnaOptions | None = None, axis: Axis | None = None, - inplace: bool_t = False, + inplace: bool = False, limit: int | None = None, downcast: dict | None | lib.NoDefault = lib.no_default, ) -> Self | None: @@ -7263,7 +7191,7 @@ def ffill( self, *, axis: None | Axis = ..., - inplace: bool_t = ..., + inplace: bool = ..., limit: None | int = ..., limit_area: Literal["inside", "outside"] | None = ..., downcast: dict | None | lib.NoDefault = ..., @@ -7279,7 +7207,7 @@ def ffill( self, *, axis: None | Axis = None, - inplace: bool_t = False, + inplace: bool = False, limit: None | int = None, limit_area: Literal["inside", "outside"] | None = None, downcast: dict | None | lib.NoDefault = lib.no_default, @@ -7388,7 +7316,7 @@ def pad( self, *, axis: None | Axis = None, - inplace: bool_t = False, + inplace: bool = False, limit: None | int = None, downcast: dict | None | lib.NoDefault = lib.no_default, ) -> Self | None: @@ -7444,7 +7372,7 @@ def bfill( self, *, axis: None | Axis = ..., - inplace: bool_t = ..., + inplace: bool = ..., limit: None | int = ..., limit_area: Literal["inside", "outside"] | None = ..., downcast: dict | None | lib.NoDefault = ..., @@ -7460,7 +7388,7 @@ def bfill( self, *, axis: None | Axis = None, - inplace: bool_t = False, + inplace: bool = False, limit: None | int = None, limit_area: Literal["inside", "outside"] | None = None, downcast: dict | None | lib.NoDefault = lib.no_default, @@ -7576,7 +7504,7 @@ def backfill( self, *, axis: None | Axis = None, - inplace: bool_t = False, + inplace: bool = False, limit: None | int = None, downcast: dict | None | lib.NoDefault = lib.no_default, ) -> Self | None: @@ -7612,7 +7540,7 @@ def replace( *, inplace: Literal[False] = ..., limit: int | None = ..., - regex: bool_t = ..., + regex: bool = ..., method: Literal["pad", "ffill", "bfill"] | lib.NoDefault = ..., ) -> Self: ... @@ -7625,7 +7553,7 @@ def replace( *, inplace: Literal[True], limit: int | None = ..., - regex: bool_t = ..., + regex: bool = ..., method: Literal["pad", "ffill", "bfill"] | lib.NoDefault = ..., ) -> None: ... @@ -7636,9 +7564,9 @@ def replace( to_replace=..., value=..., *, - inplace: bool_t = ..., + inplace: bool = ..., limit: int | None = ..., - regex: bool_t = ..., + regex: bool = ..., method: Literal["pad", "ffill", "bfill"] | lib.NoDefault = ..., ) -> Self | None: ... @@ -7654,9 +7582,9 @@ def replace( to_replace=None, value=lib.no_default, *, - inplace: bool_t = False, + inplace: bool = False, limit: int | None = None, - regex: bool_t = False, + regex: bool = False, method: Literal["pad", "ffill", "bfill"] | lib.NoDefault = lib.no_default, ) -> Self | None: if method is not lib.no_default: @@ -7928,7 +7856,7 @@ def interpolate( *, axis: Axis = ..., limit: int | None = ..., - inplace: bool_t = ..., + inplace: bool = ..., limit_direction: Literal["forward", "backward", "both"] | None = ..., limit_area: Literal["inside", "outside"] | None = ..., downcast: Literal["infer"] | None | lib.NoDefault = ..., @@ -7943,7 +7871,7 @@ def interpolate( *, axis: Axis = 0, limit: int | None = None, - inplace: bool_t = False, + inplace: bool = False, limit_direction: Literal["forward", "backward", "both"] | None = None, limit_area: Literal["inside", "outside"] | None = None, downcast: Literal["infer"] | None | lib.NoDefault = lib.no_default, @@ -8574,7 +8502,7 @@ def notnull(self) -> Self: return notna(self).__finalize__(self, method="notnull") @final - def _clip_with_scalar(self, lower, upper, inplace: bool_t = False): + def _clip_with_scalar(self, lower, upper, inplace: bool = False): if (lower is not None and np.any(isna(lower))) or ( upper is not None and np.any(isna(upper)) ): @@ -8657,7 +8585,7 @@ def clip( upper=..., *, axis: Axis | None = ..., - inplace: bool_t = ..., + inplace: bool = ..., **kwargs, ) -> Self | None: ... @@ -8669,7 +8597,7 @@ def clip( upper=None, *, axis: Axis | None = None, - inplace: bool_t = False, + inplace: bool = False, **kwargs, ) -> Self | None: """ @@ -8863,7 +8791,7 @@ def asfreq( freq: Frequency, method: FillnaOptions | None = None, how: Literal["start", "end"] | None = None, - normalize: bool_t = False, + normalize: bool = False, fill_value: Hashable | None = None, ) -> Self: """ @@ -8983,7 +8911,7 @@ def asfreq( ) @final - def at_time(self, time, asof: bool_t = False, axis: Axis | None = None) -> Self: + def at_time(self, time, asof: bool = False, axis: Axis | None = None) -> Self: """ Select values at particular time of day (e.g., 9:30AM). @@ -9137,7 +9065,7 @@ def resample( level: Level | None = None, origin: str | TimestampConvertibleTypes = "start_day", offset: TimedeltaConvertibleTypes | None = None, - group_keys: bool_t = False, + group_keys: bool = False, ) -> Resampler: """ Resample time-series data. @@ -9507,10 +9435,10 @@ def rank( self, axis: Axis = 0, method: Literal["average", "min", "max", "first", "dense"] = "average", - numeric_only: bool_t = False, + numeric_only: bool = False, na_option: Literal["keep", "top", "bottom"] = "keep", - ascending: bool_t = True, - pct: bool_t = False, + ascending: bool = True, + pct: bool = False, ) -> Self: """ Compute numerical data ranks (1 through n) along axis. @@ -9667,8 +9595,8 @@ def compare( self, other, align_axis: Axis = 1, - keep_shape: bool_t = False, - keep_equal: bool_t = False, + keep_shape: bool = False, + keep_equal: bool = False, result_names: Suffixes = ("self", "other"), ): if type(self) is not type(other): @@ -9752,7 +9680,7 @@ def align( join: AlignJoin = "outer", axis: Axis | None = None, level: Level | None = None, - copy: bool_t | None = None, + copy: bool | None = None, fill_value: Hashable | None = None, method: FillnaOptions | None | lib.NoDefault = lib.no_default, limit: int | None | lib.NoDefault = lib.no_default, @@ -10042,7 +9970,7 @@ def _align_frame( join: AlignJoin = "outer", axis: Axis | None = None, level=None, - copy: bool_t | None = None, + copy: bool | None = None, fill_value=None, method=None, limit: int | None = None, @@ -10098,7 +10026,7 @@ def _align_series( join: AlignJoin = "outer", axis: Axis | None = None, level=None, - copy: bool_t | None = None, + copy: bool | None = None, fill_value=None, method=None, limit: int | None = None, @@ -10176,7 +10104,7 @@ def _where( self, cond, other=lib.no_default, - inplace: bool_t = False, + inplace: bool = False, axis: Axis | None = None, level=None, ): @@ -10352,7 +10280,7 @@ def where( cond, other=..., *, - inplace: bool_t = ..., + inplace: bool = ..., axis: Axis | None = ..., level: Level = ..., ) -> Self | None: @@ -10371,7 +10299,7 @@ def where( cond, other=np.nan, *, - inplace: bool_t = False, + inplace: bool = False, axis: Axis | None = None, level: Level | None = None, ) -> Self | None: @@ -10574,7 +10502,7 @@ def mask( cond, other=..., *, - inplace: bool_t = ..., + inplace: bool = ..., axis: Axis | None = ..., level: Level = ..., ) -> Self | None: @@ -10594,7 +10522,7 @@ def mask( cond, other=lib.no_default, *, - inplace: bool_t = False, + inplace: bool = False, axis: Axis | None = None, level: Level | None = None, ) -> Self | None: @@ -10836,7 +10764,7 @@ def truncate( before=None, after=None, axis: Axis | None = None, - copy: bool_t | None = None, + copy: bool | None = None, ) -> Self: """ Truncate a Series or DataFrame before and after some index value. @@ -11011,7 +10939,7 @@ def truncate( @final @doc(klass=_shared_doc_kwargs["klass"]) def tz_convert( - self, tz, axis: Axis = 0, level=None, copy: bool_t | None = None + self, tz, axis: Axis = 0, level=None, copy: bool | None = None ) -> Self: """ Convert tz-aware axis to target time zone. @@ -11107,7 +11035,7 @@ def tz_localize( tz, axis: Axis = 0, level=None, - copy: bool_t | None = None, + copy: bool | None = None, ambiguous: TimeAmbiguous = "raise", nonexistent: TimeNonexistent = "raise", ) -> Self: @@ -11761,10 +11689,10 @@ def _logical_func( name: str, func, axis: Axis | None = 0, - bool_only: bool_t = False, - skipna: bool_t = True, + bool_only: bool = False, + skipna: bool = True, **kwargs, - ) -> Series | bool_t: + ) -> Series | bool: nv.validate_logical_func((), kwargs, fname=name) validate_bool_kwarg(skipna, "skipna", none_allowed=False) @@ -11806,10 +11734,10 @@ def _logical_func( def any( self, axis: Axis | None = 0, - bool_only: bool_t = False, - skipna: bool_t = True, + bool_only: bool = False, + skipna: bool = True, **kwargs, - ) -> Series | bool_t: + ) -> Series | bool: return self._logical_func( "any", nanops.nanany, axis, bool_only, skipna, **kwargs ) @@ -11817,10 +11745,10 @@ def any( def all( self, axis: Axis = 0, - bool_only: bool_t = False, - skipna: bool_t = True, + bool_only: bool = False, + skipna: bool = True, **kwargs, - ) -> Series | bool_t: + ) -> Series | bool: return self._logical_func( "all", nanops.nanall, axis, bool_only, skipna, **kwargs ) @@ -11831,7 +11759,7 @@ def _accum_func( name: str, func, axis: Axis | None = None, - skipna: bool_t = True, + skipna: bool = True, *args, **kwargs, ): @@ -11869,20 +11797,20 @@ def block_accum_func(blk_values): self, method=name ) - def cummax(self, axis: Axis | None = None, skipna: bool_t = True, *args, **kwargs): + def cummax(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): return self._accum_func( "cummax", np.maximum.accumulate, axis, skipna, *args, **kwargs ) - def cummin(self, axis: Axis | None = None, skipna: bool_t = True, *args, **kwargs): + def cummin(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): return self._accum_func( "cummin", np.minimum.accumulate, axis, skipna, *args, **kwargs ) - def cumsum(self, axis: Axis | None = None, skipna: bool_t = True, *args, **kwargs): + def cumsum(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): return self._accum_func("cumsum", np.cumsum, axis, skipna, *args, **kwargs) - def cumprod(self, axis: Axis | None = None, skipna: bool_t = True, *args, **kwargs): + def cumprod(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): return self._accum_func("cumprod", np.cumprod, axis, skipna, *args, **kwargs) @final @@ -11891,9 +11819,9 @@ def _stat_function_ddof( name: str, func, axis: Axis | None | lib.NoDefault = lib.no_default, - skipna: bool_t = True, + skipna: bool = True, ddof: int = 1, - numeric_only: bool_t = False, + numeric_only: bool = False, **kwargs, ) -> Series | float: nv.validate_stat_ddof_func((), kwargs, fname=name) @@ -11920,9 +11848,9 @@ def _stat_function_ddof( def sem( self, axis: Axis | None = 0, - skipna: bool_t = True, + skipna: bool = True, ddof: int = 1, - numeric_only: bool_t = False, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function_ddof( @@ -11932,9 +11860,9 @@ def sem( def var( self, axis: Axis | None = 0, - skipna: bool_t = True, + skipna: bool = True, ddof: int = 1, - numeric_only: bool_t = False, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function_ddof( @@ -11944,9 +11872,9 @@ def var( def std( self, axis: Axis | None = 0, - skipna: bool_t = True, + skipna: bool = True, ddof: int = 1, - numeric_only: bool_t = False, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function_ddof( @@ -11959,8 +11887,8 @@ def _stat_function( name: str, func, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ): assert name in ["median", "mean", "min", "max", "kurt", "skew"], name @@ -11975,8 +11903,8 @@ def _stat_function( def min( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ): return self._stat_function( @@ -11991,8 +11919,8 @@ def min( def max( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ): return self._stat_function( @@ -12007,8 +11935,8 @@ def max( def mean( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function( @@ -12018,8 +11946,8 @@ def mean( def median( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function( @@ -12029,8 +11957,8 @@ def median( def skew( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function( @@ -12040,8 +11968,8 @@ def skew( def kurt( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, **kwargs, ) -> Series | float: return self._stat_function( @@ -12056,8 +11984,8 @@ def _min_count_stat_function( name: str, func, axis: Axis | None | lib.NoDefault = lib.no_default, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, min_count: int = 0, **kwargs, ): @@ -12092,8 +12020,8 @@ def _min_count_stat_function( def sum( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, min_count: int = 0, **kwargs, ): @@ -12104,8 +12032,8 @@ def sum( def prod( self, axis: Axis | None = 0, - skipna: bool_t = True, - numeric_only: bool_t = False, + skipna: bool = True, + numeric_only: bool = False, min_count: int = 0, **kwargs, ): @@ -12127,7 +12055,7 @@ def rolling( self, window: int | dt.timedelta | str | BaseOffset | BaseIndexer, min_periods: int | None = None, - center: bool_t = False, + center: bool = False, win_type: str | None = None, on: str | None = None, closed: IntervalClosedType | None = None, @@ -12177,8 +12105,8 @@ def ewm( halflife: float | TimedeltaConvertibleTypes | None = None, alpha: float | None = None, min_periods: int | None = 0, - adjust: bool_t = True, - ignore_na: bool_t = False, + adjust: bool = True, + ignore_na: bool = False, times: np.ndarray | DataFrame | Series | None = None, method: Literal["single", "table"] = "single", ) -> ExponentialMovingWindow: diff --git a/pandas/core/series.py b/pandas/core/series.py index 9c51c44e7b291..4ca9592221b2b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -221,28 +221,6 @@ Unused.""", } - -def _coerce_method(converter): - """ - Install the scalar coercion methods. - """ - - def wrapper(self): - if len(self) == 1: - warnings.warn( - f"Calling {converter.__name__} on a single element Series is " - "deprecated and will raise a TypeError in the future. " - f"Use {converter.__name__}(ser.iloc[0]) instead", - FutureWarning, - stacklevel=find_stack_level(), - ) - return converter(self.iloc[0]) - raise TypeError(f"cannot convert the series to {converter}") - - wrapper.__name__ = f"__{converter.__name__}__" - return wrapper - - # ---------------------------------------------------------------------- # Series class @@ -889,13 +867,6 @@ def __column_consortium_standard__(self, *, api_version: str | None = None) -> A ) ) - # ---------------------------------------------------------------------- - # Unary Methods - - # coercion - __float__ = _coerce_method(float) - __int__ = _coerce_method(int) - # ---------------------------------------------------------------------- # indexers diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index 371bca6b9fc33..81676a5d8520a 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -46,28 +46,11 @@ def test_set_axis_name_mi(self, func): assert result.index.names == (None, None) def test_nonzero_single_element(self): - # allow single item via bool method - msg_warn = ( - "DataFrame.bool is now deprecated and will be removed " - "in future version of pandas" - ) - df = DataFrame([[True]]) - df1 = DataFrame([[False]]) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - assert df.bool() - - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - assert not df1.bool() - df = DataFrame([[False, False]]) msg_err = "The truth value of a DataFrame is ambiguous" with pytest.raises(ValueError, match=msg_err): bool(df) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err): - df.bool() - def test_metadata_propagation_indiv_groupby(self): # groupby df = DataFrame( diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 6564e381af0ea..277ea4e72c6a2 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -493,12 +493,3 @@ def test_flags_identity(self, frame_or_series): assert obj.flags is obj.flags obj2 = obj.copy() assert obj2.flags is not obj.flags - - def test_bool_dep(self) -> None: - # GH-51749 - msg_warn = ( - "DataFrame.bool is now deprecated and will be removed " - "in future version of pandas" - ) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - DataFrame({"col": [False]}).bool() diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index 67e8ca2106840..cbaf064c379ea 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -39,19 +39,6 @@ def test_get_bool_data_preserve_dtype(self): result = ser._get_bool_data() tm.assert_series_equal(result, ser) - def test_nonzero_single_element(self): - # allow single item via bool method - msg_warn = ( - "Series.bool is now deprecated and will be removed " - "in future version of pandas" - ) - ser = Series([True]) - ser1 = Series([False]) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - assert ser.bool() - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - assert not ser1.bool() - @pytest.mark.parametrize("data", [np.nan, pd.NaT, True, False]) def test_nonzero_single_element_raise_1(self, data): # single item nan to raise @@ -61,48 +48,21 @@ def test_nonzero_single_element_raise_1(self, data): with pytest.raises(ValueError, match=msg): bool(series) - @pytest.mark.parametrize("data", [np.nan, pd.NaT]) - def test_nonzero_single_element_raise_2(self, data): - msg_warn = ( - "Series.bool is now deprecated and will be removed " - "in future version of pandas" - ) - msg_err = "bool cannot act on a non-boolean single element Series" - series = Series([data]) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err): - series.bool() - @pytest.mark.parametrize("data", [(True, True), (False, False)]) def test_nonzero_multiple_element_raise(self, data): # multiple bool are still an error - msg_warn = ( - "Series.bool is now deprecated and will be removed " - "in future version of pandas" - ) msg_err = "The truth value of a Series is ambiguous" series = Series([data]) with pytest.raises(ValueError, match=msg_err): bool(series) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err): - series.bool() @pytest.mark.parametrize("data", [1, 0, "a", 0.0]) def test_nonbool_single_element_raise(self, data): # single non-bool are an error - msg_warn = ( - "Series.bool is now deprecated and will be removed " - "in future version of pandas" - ) msg_err1 = "The truth value of a Series is ambiguous" - msg_err2 = "bool cannot act on a non-boolean single element Series" series = Series([data]) with pytest.raises(ValueError, match=msg_err1): bool(series) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err2): - series.bool() def test_metadata_propagation_indiv_resample(self): # resample diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 7fb78edf7a63f..691308633a796 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -284,10 +284,3 @@ def test_numeric_only(self, kernel, has_numeric_only, dtype): else: # reducer assert result == expected - - -@pytest.mark.parametrize("converter", [int, float, complex]) -def test_float_int_deprecated(converter): - # GH 51101 - with tm.assert_produces_warning(FutureWarning): - assert converter(Series([1])) == converter(1) diff --git a/scripts/no_bool_in_generic.py b/scripts/no_bool_in_generic.py deleted file mode 100644 index 15bc2247469c7..0000000000000 --- a/scripts/no_bool_in_generic.py +++ /dev/null @@ -1,98 +0,0 @@ -""" -Check that pandas/core/generic.py doesn't use bool as a type annotation. - -There is already the method `bool`, so the alias `bool_t` should be used instead. - -This is meant to be run as a pre-commit hook - to run it manually, you can do: - - pre-commit run no-bool-in-core-generic --all-files - -The function `visit` is adapted from a function by the same name in pyupgrade: -https://github.com/asottile/pyupgrade/blob/5495a248f2165941c5d3b82ac3226ba7ad1fa59d/pyupgrade/_data.py#L70-L113 -Licence at LICENSES/PYUPGRADE_LICENSE -""" -from __future__ import annotations - -import argparse -import ast -import collections -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from collections.abc import Sequence - - -def visit(tree: ast.Module) -> dict[int, list[int]]: - """Step through tree, recording when nodes are in annotations.""" - in_annotation = False - nodes: list[tuple[bool, ast.AST]] = [(in_annotation, tree)] - to_replace = collections.defaultdict(list) - - while nodes: - in_annotation, node = nodes.pop() - - if isinstance(node, ast.Name) and in_annotation and node.id == "bool": - to_replace[node.lineno].append(node.col_offset) - - for name in reversed(node._fields): - value = getattr(node, name) - if name in {"annotation", "returns"}: - next_in_annotation = True - else: - next_in_annotation = in_annotation - if isinstance(value, ast.AST): - nodes.append((next_in_annotation, value)) - elif isinstance(value, list): - nodes.extend( - (next_in_annotation, value) - for value in reversed(value) - if isinstance(value, ast.AST) - ) - - return to_replace - - -def replace_bool_with_bool_t(to_replace, content: str) -> str: - new_lines = [] - - for n, line in enumerate(content.splitlines(), start=1): - replaced_line = line - if n in to_replace: - for col_offset in reversed(to_replace[n]): - replaced_line = ( - replaced_line[:col_offset] - + "bool_t" - + replaced_line[col_offset + 4 :] - ) - new_lines.append(replaced_line) - return "\n".join(new_lines) + "\n" - - -def check_for_bool_in_generic(content: str) -> tuple[bool, str]: - tree = ast.parse(content) - to_replace = visit(tree) - - if not to_replace: - mutated = False - return mutated, content - - mutated = True - return mutated, replace_bool_with_bool_t(to_replace, content) - - -def main(argv: Sequence[str] | None = None) -> None: - parser = argparse.ArgumentParser() - parser.add_argument("paths", nargs="*") - args = parser.parse_args(argv) - - for path in args.paths: - with open(path, encoding="utf-8") as fd: - content = fd.read() - mutated, new_content = check_for_bool_in_generic(content) - if mutated: - with open(path, "w", encoding="utf-8") as fd: - fd.write(new_content) - - -if __name__ == "__main__": - main() diff --git a/scripts/tests/test_no_bool_in_generic.py b/scripts/tests/test_no_bool_in_generic.py deleted file mode 100644 index 20ac214ce8a4a..0000000000000 --- a/scripts/tests/test_no_bool_in_generic.py +++ /dev/null @@ -1,20 +0,0 @@ -from scripts.no_bool_in_generic import check_for_bool_in_generic - -BAD_FILE = "def foo(a: bool) -> bool:\n return bool(0)\n" -GOOD_FILE = "def foo(a: bool_t) -> bool_t:\n return bool(0)\n" - - -def test_bad_file_with_replace() -> None: - content = BAD_FILE - mutated, result = check_for_bool_in_generic(content) - expected = GOOD_FILE - assert result == expected - assert mutated - - -def test_good_file_with_replace() -> None: - content = GOOD_FILE - mutated, result = check_for_bool_in_generic(content) - expected = content - assert result == expected - assert not mutated