diff --git a/asv_bench/benchmarks/strftime.py b/asv_bench/benchmarks/strftime.py index 47f25b331ab9b..5f2832e361eb5 100644 --- a/asv_bench/benchmarks/strftime.py +++ b/asv_bench/benchmarks/strftime.py @@ -79,12 +79,6 @@ def time_frame_period_formatting_default(self, nobs, freq): def time_frame_period_formatting_default_explicit(self, nobs, freq): self.data["p"].dt.strftime(date_format=self.default_fmt) - def time_frame_period_formatting_index_default(self, nobs, freq): - self.data.index.format() - - def time_frame_period_formatting_index_default_explicit(self, nobs, freq): - self.data.index.format(self.default_fmt) - def time_frame_period_formatting_custom(self, nobs, freq): self.data["p"].dt.strftime(date_format="%Y-%m-%d --- %H:%M:%S") diff --git a/doc/redirects.csv b/doc/redirects.csv index 1f12ba08b8005..5d351680ec03a 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -118,7 +118,6 @@ generated/pandas.api.types.is_int64_dtype,../reference/api/pandas.api.types.is_i generated/pandas.api.types.is_integer_dtype,../reference/api/pandas.api.types.is_integer_dtype generated/pandas.api.types.is_integer,../reference/api/pandas.api.types.is_integer generated/pandas.api.types.is_interval_dtype,../reference/api/pandas.api.types.is_interval_dtype -generated/pandas.api.types.is_interval,../reference/api/pandas.api.types.is_interval generated/pandas.api.types.is_iterator,../reference/api/pandas.api.types.is_iterator generated/pandas.api.types.is_list_like,../reference/api/pandas.api.types.is_list_like generated/pandas.api.types.is_named_tuple,../reference/api/pandas.api.types.is_named_tuple diff --git a/doc/source/reference/arrays.rst b/doc/source/reference/arrays.rst index 93b56d1b48c02..a631cd517e3c2 100644 --- a/doc/source/reference/arrays.rst +++ b/doc/source/reference/arrays.rst @@ -700,7 +700,6 @@ Scalar introspection api.types.is_float api.types.is_hashable api.types.is_integer - api.types.is_interval api.types.is_number api.types.is_re api.types.is_re_compilable diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 3bfe16b29535d..9423adc7b148d 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -108,12 +108,15 @@ Removal of prior version deprecations/changes - 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 ``Index.format``, use :meth:`Index.astype` with ``str`` or :meth:`Index.map` with a ``formatter`` function instead (:issue:`55439`) - 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`) - Removed ``axis`` argument from all groupby operations (:issue:`50405`) +- Removed ``pandas.api.types.is_interval`` and ``pandas.api.types.is_period``, use ``isinstance(obj, pd.Interval)`` and ``isinstance(obj, pd.Period)`` instead (:issue:`55264`) - Removed ``pandas.io.sql.execute`` (:issue:`50185`) +- Removed ``pandas.value_counts``, use :meth:`Series.value_counts` instead (:issue:`53493`) - Removed ``read_gbq`` and ``DataFrame.to_gbq``. Use ``pandas_gbq.read_gbq`` and ``pandas_gbq.to_gbq`` instead https://pandas-gbq.readthedocs.io/en/latest/api.html (:issue:`55525`) - Removed deprecated argument ``obj`` in :meth:`.DataFrameGroupBy.get_group` and :meth:`.SeriesGroupBy.get_group` (:issue:`53545`) - Removed the ``ArrayManager`` (:issue:`55043`) diff --git a/pandas/__init__.py b/pandas/__init__.py index 95601f226a83f..7b5b00d92db1f 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -101,7 +101,6 @@ Grouper, factorize, unique, - value_counts, NamedAgg, array, Categorical, @@ -378,6 +377,5 @@ "to_timedelta", "tseries", "unique", - "value_counts", "wide_to_long", ] diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index c8befabbf86de..34193a9b1d231 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -14,8 +14,6 @@ from typing import ( import numpy as np -from pandas._libs.interval import Interval -from pandas._libs.tslibs import Period from pandas._typing import ( ArrayLike, DtypeObj, @@ -44,8 +42,6 @@ def is_iterator(obj: object) -> bool: ... def is_scalar(val: object) -> bool: ... def is_list_like(obj: object, allow_sets: bool = ...) -> bool: ... def is_pyarrow_array(obj: object) -> bool: ... -def is_period(val: object) -> TypeGuard[Period]: ... -def is_interval(obj: object) -> TypeGuard[Interval]: ... def is_decimal(obj: object) -> TypeGuard[Decimal]: ... def is_complex(obj: object) -> TypeGuard[complex]: ... def is_bool(obj: object) -> TypeGuard[bool | np.bool_]: ... diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 50feda8fb188e..3146b31a2e7e8 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1164,43 +1164,6 @@ cpdef bint is_decimal(object obj): return isinstance(obj, Decimal) -cpdef bint is_interval(object obj): - import warnings - - from pandas.util._exceptions import find_stack_level - - warnings.warn( - # GH#55264 - "is_interval is deprecated and will be removed in a future version. " - "Use isinstance(obj, pd.Interval) instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return getattr(obj, "_typ", "_typ") == "interval" - - -def is_period(val: object) -> bool: - """ - Return True if given object is Period. - - Returns - ------- - bool - """ - import warnings - - from pandas.util._exceptions import find_stack_level - - warnings.warn( - # GH#55264 - "is_period is deprecated and will be removed in a future version. " - "Use isinstance(obj, pd.Period) instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return is_period_object(val) - - def is_list_like(obj: object, allow_sets: bool = True) -> bool: """ Check if the object is list-like. diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index b346cb9b2c175..500f805499a8b 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -818,53 +818,6 @@ def factorize( return codes, uniques -def value_counts( - values, - sort: bool = True, - ascending: bool = False, - normalize: bool = False, - bins=None, - dropna: bool = True, -) -> Series: - """ - Compute a histogram of the counts of non-null values. - - Parameters - ---------- - values : ndarray (1-d) - sort : bool, default True - Sort by values - ascending : bool, default False - Sort in ascending order - normalize: bool, default False - If True then compute a relative histogram - bins : integer, optional - Rather than count values, group them into half-open bins, - convenience for pd.cut, only works with numeric data - dropna : bool, default True - Don't include counts of NaN - - Returns - ------- - Series - """ - warnings.warn( - # GH#53493 - "pandas.value_counts is deprecated and will be removed in a " - "future version. Use pd.Series(obj).value_counts() instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return value_counts_internal( - values, - sort=sort, - ascending=ascending, - normalize=normalize, - bins=bins, - dropna=dropna, - ) - - def value_counts_internal( values, sort: bool = True, diff --git a/pandas/core/api.py b/pandas/core/api.py index 2cfe5ffc0170d..3d2e855831c05 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -23,7 +23,6 @@ from pandas.core.algorithms import ( factorize, unique, - value_counts, ) from pandas.core.arrays import Categorical from pandas.core.arrays.boolean import BooleanDtype @@ -136,5 +135,4 @@ "UInt64Dtype", "UInt8Dtype", "unique", - "value_counts", ] diff --git a/pandas/core/dtypes/api.py b/pandas/core/dtypes/api.py index 254abe330b8e7..e66104d6afcd9 100644 --- a/pandas/core/dtypes/api.py +++ b/pandas/core/dtypes/api.py @@ -20,7 +20,6 @@ is_int64_dtype, is_integer, is_integer_dtype, - is_interval, is_interval_dtype, is_iterator, is_list_like, @@ -63,7 +62,6 @@ "is_int64_dtype", "is_integer", "is_integer_dtype", - "is_interval", "is_interval_dtype", "is_iterator", "is_list_like", diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 99114d996cc4c..8eee15e13791a 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -42,7 +42,6 @@ is_float, is_hashable, is_integer, - is_interval, is_iterator, is_list_like, is_named_tuple, @@ -1710,7 +1709,6 @@ def is_all_strings(value: ArrayLike) -> bool: "is_float_dtype", "is_int64_dtype", "is_integer_dtype", - "is_interval", "is_interval_dtype", "is_iterator", "is_named_tuple", diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index c0d9b418b9e79..bd4e5182b24bf 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -29,8 +29,6 @@ is_decimal = lib.is_decimal -is_interval = lib.is_interval - is_list_like = lib.is_list_like is_iterator = lib.is_iterator diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 83290f7900ab6..68fd49bd6fb54 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1394,36 +1394,6 @@ def _mpl_repr(self) -> np.ndarray: return cast(np.ndarray, self.values) return self.astype(object, copy=False)._values - def format( - self, - name: bool = False, - formatter: Callable | None = None, - na_rep: str_t = "NaN", - ) -> list[str_t]: - """ - Render a string representation of the Index. - """ - warnings.warn( - # GH#55413 - f"{type(self).__name__}.format is deprecated and will be removed " - "in a future version. Convert using index.astype(str) or " - "index.map(formatter) instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - header = [] - if name: - header.append( - pprint_thing(self.name, escape_chars=("\t", "\r", "\n")) - if self.name is not None - else "" - ) - - if formatter is not None: - return header + list(self.map(formatter)) - - return self._format_with_header(header=header, na_rep=na_rep) - _default_na_rep = "NaN" @final diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 451adce4b320e..117de2e6f950c 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -10,11 +10,9 @@ from typing import ( TYPE_CHECKING, Any, - Callable, cast, final, ) -import warnings import numpy as np @@ -43,7 +41,6 @@ cache_readonly, doc, ) -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_integer, @@ -191,39 +188,6 @@ def _convert_tolerance(self, tolerance, target): # Rendering Methods _default_na_rep = "NaT" - def format( - self, - name: bool = False, - formatter: Callable | None = None, - na_rep: str = "NaT", - date_format: str | None = None, - ) -> list[str]: - """ - Render a string representation of the Index. - """ - warnings.warn( - # GH#55413 - f"{type(self).__name__}.format is deprecated and will be removed " - "in a future version. Convert using index.astype(str) or " - "index.map(formatter) instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - header = [] - if name: - header.append( - ibase.pprint_thing(self.name, escape_chars=("\t", "\r", "\n")) - if self.name is not None - else "" - ) - - if formatter is not None: - return header + list(self.map(formatter)) - - return self._format_with_header( - header=header, na_rep=na_rep, date_format=date_format - ) - def _format_with_header( self, *, header: list[str], na_rep: str, date_format: str | None = None ) -> list[str]: diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index c81d76d471a5f..9c6156b97689e 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -107,10 +107,7 @@ lexsort_indexer, ) -from pandas.io.formats.printing import ( - get_adjustment, - pprint_thing, -) +from pandas.io.formats.printing import pprint_thing if TYPE_CHECKING: from pandas import ( @@ -1421,90 +1418,6 @@ def _get_values_for_csv( ) return mi._values - def format( - self, - name: bool | None = None, - formatter: Callable | None = None, - na_rep: str | None = None, - names: bool = False, - space: int = 2, - sparsify=None, - adjoin: bool = True, - ) -> list: - warnings.warn( - # GH#55413 - f"{type(self).__name__}.format is deprecated and will be removed " - "in a future version. Convert using index.astype(str) or " - "index.map(formatter) instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - - if name is not None: - names = name - - if len(self) == 0: - return [] - - formatted: Iterable - stringified_levels = [] - for lev, level_codes in zip(self.levels, self.codes): - na = na_rep if na_rep is not None else _get_na_rep(lev.dtype) - - if len(lev) > 0: - formatted = lev.take(level_codes).format(formatter=formatter) - - # we have some NA - mask = level_codes == -1 - if mask.any(): - formatted = np.array(formatted, dtype=object) - formatted[mask] = na - formatted = formatted.tolist() - - else: - # weird all NA case - formatted = [ - pprint_thing(na if isna(x) else x, escape_chars=("\t", "\r", "\n")) - for x in algos.take_nd(lev._values, level_codes) - ] - stringified_levels.append(formatted) - - result_levels = [] - # Incompatible types in assignment (expression has type "Iterable[Any]", - # variable has type "Index") - for lev, lev_name in zip(stringified_levels, self.names): # type: ignore[assignment] - level = [] - - if names: - level.append( - pprint_thing(lev_name, escape_chars=("\t", "\r", "\n")) - if lev_name is not None - else "" - ) - - level.extend(np.array(lev, dtype=object)) - result_levels.append(level) - - if sparsify is None: - sparsify = get_option("display.multi_sparse") - - if sparsify: - sentinel: Literal[""] | bool | lib.NoDefault = "" - # GH3547 use value of sparsify as sentinel if it's "Falsey" - assert isinstance(sparsify, bool) or sparsify is lib.no_default - if sparsify in [False, lib.no_default]: - sentinel = sparsify - # little bit of a kludge job for #1217 - result_levels = sparsify_labels( - result_levels, start=int(names), sentinel=sentinel - ) - - if adjoin: - adj = get_adjustment() - return adj.adjoin(space, *result_levels).split("\n") - else: - return result_levels - def _format_multi( self, *, diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index 6ed1d07d0cc3d..15b6c9abaea8f 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -133,7 +133,6 @@ class TestPDApi(Base): "show_versions", "timedelta_range", "unique", - "value_counts", "wide_to_long", ] @@ -292,7 +291,6 @@ class TestApi(Base): "is_int64_dtype", "is_integer", "is_integer_dtype", - "is_interval", "is_interval_dtype", "is_iterator", "is_list_like", diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index fbaa6e7e18bca..bf39370c49d76 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -34,7 +34,6 @@ class TestTypes(Base): "is_timedelta64_ns_dtype", "is_unsigned_integer_dtype", "is_period_dtype", - "is_interval", "is_interval_dtype", "is_re", "is_re_compilable", diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index f1f5cb1620345..0434ad7e50568 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -63,7 +63,6 @@ Index, Interval, Period, - PeriodIndex, Series, Timedelta, TimedeltaIndex, @@ -1617,25 +1616,6 @@ def test_to_object_array_width(self): out = lib.to_object_array(rows, min_width=5) tm.assert_numpy_array_equal(out, expected) - def test_is_period(self): - # GH#55264 - msg = "is_period is deprecated and will be removed in a future version" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert lib.is_period(Period("2011-01", freq="M")) - assert not lib.is_period(PeriodIndex(["2011-01"], freq="M")) - assert not lib.is_period(Timestamp("2011-01")) - assert not lib.is_period(1) - assert not lib.is_period(np.nan) - - def test_is_interval(self): - # GH#55264 - msg = "is_interval is deprecated and will be removed in a future version" - item = Interval(1, 2) - with tm.assert_produces_warning(FutureWarning, match=msg): - assert lib.is_interval(item) - assert not lib.is_interval(pd.IntervalIndex([item])) - assert not lib.is_interval(pd.IntervalIndex([item])._engine) - def test_categorical(self): # GH 8974 arr = Categorical(list("abc")) diff --git a/pandas/tests/indexes/base_class/test_formats.py b/pandas/tests/indexes/base_class/test_formats.py index f30b578cfcf56..4580e00069dc1 100644 --- a/pandas/tests/indexes/base_class/test_formats.py +++ b/pandas/tests/indexes/base_class/test_formats.py @@ -144,20 +144,6 @@ def test_summary_bug(self): def test_index_repr_bool_nan(self): # GH32146 arr = Index([True, False, np.nan], dtype=object) - msg = "Index.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - exp1 = arr.format() - out1 = ["True", "False", "NaN"] - assert out1 == exp1 - exp2 = repr(arr) out2 = "Index([True, False, nan], dtype='object')" assert out2 == exp2 - - def test_format_different_scalar_lengths(self): - # GH#35439 - idx = Index(["aaaaaaaaa", "b"]) - expected = ["aaaaaaaaa", "b"] - msg = r"Index\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert idx.format() == expected diff --git a/pandas/tests/indexes/categorical/test_formats.py b/pandas/tests/indexes/categorical/test_formats.py index 522ca1bc2afde..74e738a543300 100644 --- a/pandas/tests/indexes/categorical/test_formats.py +++ b/pandas/tests/indexes/categorical/test_formats.py @@ -7,18 +7,9 @@ import pandas._config.config as cf from pandas import CategoricalIndex -import pandas._testing as tm class TestCategoricalIndexRepr: - def test_format_different_scalar_lengths(self): - # GH#35439 - idx = CategoricalIndex(["aaaaaaaaa", "b"]) - expected = ["aaaaaaaaa", "b"] - msg = r"CategoricalIndex\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert idx.format() == expected - @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different") def test_string_categorical_index_repr(self): # short diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py index f8b01f7985535..6e4e22942ab07 100644 --- a/pandas/tests/indexes/datetimes/test_formats.py +++ b/pandas/tests/indexes/datetimes/test_formats.py @@ -286,66 +286,3 @@ def test_dti_business_repr_etc_smoke(self, tz, freq): repr(dti) dti._summary() dti[2:2]._summary() - - -class TestFormat: - def test_format(self): - # GH#35439 - idx = pd.date_range("20130101", periods=5) - expected = [f"{x:%Y-%m-%d}" for x in idx] - msg = r"DatetimeIndex\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert idx.format() == expected - - def test_format_with_name_time_info(self): - # bug I fixed 12/20/2011 - dates = pd.date_range("2011-01-01 04:00:00", periods=10, name="something") - - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = dates.format(name=True) - assert formatted[0] == "something" - - def test_format_datetime_with_time(self): - dti = DatetimeIndex([datetime(2012, 2, 7), datetime(2012, 2, 7, 23)]) - - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = dti.format() - expected = ["2012-02-07 00:00:00", "2012-02-07 23:00:00"] - assert len(result) == 2 - assert result == expected - - def test_format_datetime(self): - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = pd.to_datetime([datetime(2003, 1, 1, 12), NaT]).format() - assert formatted[0] == "2003-01-01 12:00:00" - assert formatted[1] == "NaT" - - def test_format_date(self): - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = pd.to_datetime([datetime(2003, 1, 1), NaT]).format() - assert formatted[0] == "2003-01-01" - assert formatted[1] == "NaT" - - def test_format_date_tz(self): - dti = pd.to_datetime([datetime(2013, 1, 1)], utc=True) - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = dti.format() - assert formatted[0] == "2013-01-01 00:00:00+00:00" - - dti = pd.to_datetime([datetime(2013, 1, 1), NaT], utc=True) - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = dti.format() - assert formatted[0] == "2013-01-01 00:00:00+00:00" - - def test_format_date_explicit_date_format(self): - dti = pd.to_datetime([datetime(2003, 2, 1), NaT]) - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = dti.format(date_format="%m-%d-%Y", na_rep="UT") - assert formatted[0] == "02-01-2003" - assert formatted[1] == "UT" diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py index 286a048f02dad..cc6a33c22503d 100644 --- a/pandas/tests/indexes/multi/test_formats.py +++ b/pandas/tests/indexes/multi/test_formats.py @@ -6,48 +6,6 @@ Index, MultiIndex, ) -import pandas._testing as tm - - -def test_format(idx): - msg = "MultiIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - idx.format() - idx[:0].format() - - -def test_format_integer_names(): - index = MultiIndex( - levels=[[0, 1], [0, 1]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1] - ) - msg = "MultiIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - index.format(names=True) - - -def test_format_sparse_config(idx): - # GH1538 - msg = "MultiIndex.format is deprecated" - with pd.option_context("display.multi_sparse", False): - with tm.assert_produces_warning(FutureWarning, match=msg): - result = idx.format() - assert result[1] == "foo two" - - -def test_format_sparse_display(): - index = MultiIndex( - levels=[[0, 1], [0, 1], [0, 1], [0]], - codes=[ - [0, 0, 0, 1, 1, 1], - [0, 0, 1, 0, 0, 1], - [0, 1, 0, 0, 1, 0], - [0, 0, 0, 0, 0, 0], - ], - ) - msg = "MultiIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = index.format() - assert result[3] == "1 0 0 0" def test_repr_with_unicode_data(): diff --git a/pandas/tests/indexes/period/test_formats.py b/pandas/tests/indexes/period/test_formats.py index 81c79f7d18f2f..9f36eb1e7a1d1 100644 --- a/pandas/tests/indexes/period/test_formats.py +++ b/pandas/tests/indexes/period/test_formats.py @@ -1,10 +1,3 @@ -from contextlib import nullcontext -from datetime import ( - datetime, - time, -) -import locale - import numpy as np import pytest @@ -16,13 +9,6 @@ import pandas._testing as tm -def get_local_am_pm(): - """Return the AM and PM strings returned by strftime in current locale.""" - am_local = time(1).strftime("%p") - pm_local = time(13).strftime("%p") - return am_local, pm_local - - def test_get_values_for_csv(): index = PeriodIndex(["2017-01-01", "2017-01-02", "2017-01-03"], freq="D") @@ -56,15 +42,6 @@ def test_get_values_for_csv(): class TestPeriodIndexRendering: - def test_format_empty(self): - # GH#35712 - empty_idx = PeriodIndex([], freq="Y") - msg = r"PeriodIndex\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert empty_idx.format() == [] - with tm.assert_produces_warning(FutureWarning, match=msg): - assert empty_idx.format(name=True) == [""] - @pytest.mark.parametrize("method", ["__repr__", "__str__"]) def test_representation(self, method): # GH#7601 @@ -215,136 +192,3 @@ def test_summary(self): ): result = idx._summary() assert result == expected - - -class TestPeriodIndexFormat: - def test_period_format_and_strftime_default(self): - per = PeriodIndex([datetime(2003, 1, 1, 12), None], freq="h") - - # Default formatting - msg = "PeriodIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format() - assert formatted[0] == "2003-01-01 12:00" # default: minutes not shown - assert formatted[1] == "NaT" - # format is equivalent to strftime(None)... - assert formatted[0] == per.strftime(None)[0] - assert per.strftime(None)[1] is np.nan # ...except for NaTs - - # Same test with nanoseconds freq - per = pd.period_range("2003-01-01 12:01:01.123456789", periods=2, freq="ns") - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format() - assert (formatted == per.strftime(None)).all() - assert formatted[0] == "2003-01-01 12:01:01.123456789" - assert formatted[1] == "2003-01-01 12:01:01.123456790" - - def test_period_custom(self): - # GH#46252 custom formatting directives %l (ms) and %u (us) - msg = "PeriodIndex.format is deprecated" - - # 3 digits - per = pd.period_range("2003-01-01 12:01:01.123", periods=2, freq="ms") - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format(date_format="%y %I:%M:%S (ms=%l us=%u ns=%n)") - assert formatted[0] == "03 12:01:01 (ms=123 us=123000 ns=123000000)" - assert formatted[1] == "03 12:01:01 (ms=124 us=124000 ns=124000000)" - - # 6 digits - per = pd.period_range("2003-01-01 12:01:01.123456", periods=2, freq="us") - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format(date_format="%y %I:%M:%S (ms=%l us=%u ns=%n)") - assert formatted[0] == "03 12:01:01 (ms=123 us=123456 ns=123456000)" - assert formatted[1] == "03 12:01:01 (ms=123 us=123457 ns=123457000)" - - # 9 digits - per = pd.period_range("2003-01-01 12:01:01.123456789", periods=2, freq="ns") - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format(date_format="%y %I:%M:%S (ms=%l us=%u ns=%n)") - assert formatted[0] == "03 12:01:01 (ms=123 us=123456 ns=123456789)" - assert formatted[1] == "03 12:01:01 (ms=123 us=123456 ns=123456790)" - - def test_period_tz(self): - # Formatting periods created from a datetime with timezone. - msg = r"PeriodIndex\.format is deprecated" - # This timestamp is in 2013 in Europe/Paris but is 2012 in UTC - dt = pd.to_datetime(["2013-01-01 00:00:00+01:00"], utc=True) - - # Converting to a period looses the timezone information - # Since tz is currently set as utc, we'll see 2012 - with tm.assert_produces_warning(UserWarning, match="will drop timezone"): - per = dt.to_period(freq="h") - with tm.assert_produces_warning(FutureWarning, match=msg): - assert per.format()[0] == "2012-12-31 23:00" - - # If tz is currently set as paris before conversion, we'll see 2013 - dt = dt.tz_convert("Europe/Paris") - with tm.assert_produces_warning(UserWarning, match="will drop timezone"): - per = dt.to_period(freq="h") - with tm.assert_produces_warning(FutureWarning, match=msg): - assert per.format()[0] == "2013-01-01 00:00" - - @pytest.mark.parametrize( - "locale_str", - [ - pytest.param(None, id=str(locale.getlocale())), - "it_IT.utf8", - "it_IT", # Note: encoding will be 'ISO8859-1' - "zh_CN.utf8", - "zh_CN", # Note: encoding will be 'gb2312' - ], - ) - def test_period_non_ascii_fmt(self, locale_str): - # GH#46468 non-ascii char in input format string leads to wrong output - - # Skip if locale cannot be set - if locale_str is not None and not tm.can_set_locale(locale_str, locale.LC_ALL): - pytest.skip(f"Skipping as locale '{locale_str}' cannot be set on host.") - - # Change locale temporarily for this test. - with tm.set_locale(locale_str, locale.LC_ALL) if locale_str else nullcontext(): - # Scalar - per = pd.Period("2018-03-11 13:00", freq="h") - assert per.strftime("%y é") == "18 é" - - # Index - per = pd.period_range("2003-01-01 01:00:00", periods=2, freq="12h") - msg = "PeriodIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format(date_format="%y é") - assert formatted[0] == "03 é" - assert formatted[1] == "03 é" - - @pytest.mark.parametrize( - "locale_str", - [ - pytest.param(None, id=str(locale.getlocale())), - "it_IT.utf8", - "it_IT", # Note: encoding will be 'ISO8859-1' - "zh_CN.utf8", - "zh_CN", # Note: encoding will be 'gb2312' - ], - ) - def test_period_custom_locale_directive(self, locale_str): - # GH#46319 locale-specific directive leads to non-utf8 c strftime char* result - - # Skip if locale cannot be set - if locale_str is not None and not tm.can_set_locale(locale_str, locale.LC_ALL): - pytest.skip(f"Skipping as locale '{locale_str}' cannot be set on host.") - - # Change locale temporarily for this test. - with tm.set_locale(locale_str, locale.LC_ALL) if locale_str else nullcontext(): - # Get locale-specific reference - am_local, pm_local = get_local_am_pm() - - # Scalar - per = pd.Period("2018-03-11 13:00", freq="h") - assert per.strftime("%p") == pm_local - - # Index - per = pd.period_range("2003-01-01 01:00:00", periods=2, freq="12h") - msg = "PeriodIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = per.format(date_format="%y %I:%M:%S%p") - assert formatted[0] == f"03 01:00:00{am_local}" - assert formatted[1] == f"03 01:00:00{pm_local}" diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 06e19eeca6766..29d6916cc7f08 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -242,11 +242,6 @@ def test_cache(self): pass assert idx._cache == {} - msg = "RangeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - idx.format() - assert idx._cache == {} - df = pd.DataFrame({"a": range(10)}, index=idx) # df.__repr__ should not populate index cache @@ -570,15 +565,6 @@ def test_engineless_lookup(self): assert "_engine" not in idx._cache - def test_format_empty(self): - # GH35712 - empty_idx = RangeIndex(0) - msg = r"RangeIndex\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert empty_idx.format() == [] - with tm.assert_produces_warning(FutureWarning, match=msg): - assert empty_idx.format(name=True) == [""] - @pytest.mark.parametrize( "ri", [ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 5f08443b4b5b5..948f369edf072 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -686,41 +686,6 @@ def test_is_object(self, index, expected, using_infer_string): def test_summary(self, index): index._summary() - def test_format_bug(self): - # GH 14626 - # windows has different precision on datetime.datetime.now (it doesn't - # include us since the default for Timestamp shows these but Index - # formatting does not we are skipping) - now = datetime.now() - msg = r"Index\.format is deprecated" - - if not str(now).endswith("000"): - index = Index([now]) - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = index.format() - expected = [str(index[0])] - assert formatted == expected - - with tm.assert_produces_warning(FutureWarning, match=msg): - Index([]).format() - - @pytest.mark.parametrize("vals", [[1, 2.0 + 3.0j, 4.0], ["a", "b", "c"]]) - def test_format_missing(self, vals, nulls_fixture): - # 2845 - vals = list(vals) # Copy for each iteration - vals.append(nulls_fixture) - index = Index(vals, dtype=object) - # TODO: case with complex dtype? - - msg = r"Index\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - formatted = index.format() - null_repr = "NaN" if isinstance(nulls_fixture, float) else str(nulls_fixture) - expected = [str(index[0]), str(index[1]), str(index[2]), null_repr] - - assert formatted == expected - assert index[3] is nulls_fixture - def test_logical_compat(self, all_boolean_reductions, simple_index): index = simple_index left = getattr(index, all_boolean_reductions)() diff --git a/pandas/tests/indexes/test_old_base.py b/pandas/tests/indexes/test_old_base.py index d944c204f33ec..cc496dbee86d3 100644 --- a/pandas/tests/indexes/test_old_base.py +++ b/pandas/tests/indexes/test_old_base.py @@ -567,29 +567,6 @@ def test_equals_op(self, simple_index): tm.assert_numpy_array_equal(index_a == item, expected3) tm.assert_series_equal(series_a == item, Series(expected3)) - def test_format(self, simple_index): - # GH35439 - if is_numeric_dtype(simple_index.dtype) or isinstance( - simple_index, DatetimeIndex - ): - pytest.skip("Tested elsewhere.") - idx = simple_index - expected = [str(x) for x in idx] - msg = r"Index\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert idx.format() == expected - - def test_format_empty(self, simple_index): - # GH35712 - if isinstance(simple_index, (PeriodIndex, RangeIndex)): - pytest.skip("Tested elsewhere") - empty_idx = type(simple_index)([]) - msg = r"Index\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert empty_idx.format() == [] - with tm.assert_produces_warning(FutureWarning, match=msg): - assert empty_idx.format(name=True) == [""] - def test_fillna(self, index): # GH 11343 if len(index) == 0: @@ -927,17 +904,6 @@ def test_view(self, simple_index): idx_view = idx.view(index_cls) tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True) - def test_format(self, simple_index): - # GH35439 - if isinstance(simple_index, DatetimeIndex): - pytest.skip("Tested elsewhere") - idx = simple_index - max_width = max(len(str(x)) for x in idx) - expected = [str(x).ljust(max_width) for x in idx] - msg = r"Index\.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - assert idx.format() == expected - def test_insert_non_na(self, simple_index): # GH#43921 inserting an element that we know we can hold should # not change dtype or type (except for RangeIndex) diff --git a/pandas/tests/series/test_formats.py b/pandas/tests/series/test_formats.py index a1c5018ea7961..1a3b46ec8196a 100644 --- a/pandas/tests/series/test_formats.py +++ b/pandas/tests/series/test_formats.py @@ -19,7 +19,6 @@ period_range, timedelta_range, ) -import pandas._testing as tm class TestSeriesRepr: @@ -254,14 +253,6 @@ def test_index_repr_in_frame_with_nan(self): assert repr(s) == exp - def test_format_pre_1900_dates(self): - rng = date_range("1/1/1850", "1/1/1950", freq="YE-DEC") - msg = "DatetimeIndex.format is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - rng.format() - ts = Series(1, index=rng) - repr(ts) - def test_series_repr_nat(self): series = Series([0, 1000, 2000, pd.NaT._value], dtype="M8[ns]") diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 3fd771c7fe31a..057a5a627370e 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1212,9 +1212,7 @@ def test_value_counts(self): factor = cut(arr, 4) # assert isinstance(factor, n) - msg = "pandas.value_counts is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = algos.value_counts(factor) + result = algos.value_counts_internal(factor) breaks = [-1.606, -1.018, -0.431, 0.155, 0.741] index = IntervalIndex.from_breaks(breaks).astype(CategoricalDtype(ordered=True)) expected = Series([1, 0, 2, 1], index=index, name="count") @@ -1222,16 +1220,13 @@ def test_value_counts(self): def test_value_counts_bins(self): s = [1, 2, 3, 4] - msg = "pandas.value_counts is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = algos.value_counts(s, bins=1) + result = algos.value_counts_internal(s, bins=1) expected = Series( [4], index=IntervalIndex.from_tuples([(0.996, 4.0)]), name="count" ) tm.assert_series_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = algos.value_counts(s, bins=2, sort=False) + result = algos.value_counts_internal(s, bins=2, sort=False) expected = Series( [2, 2], index=IntervalIndex.from_tuples([(0.996, 2.5), (2.5, 4.0)]), @@ -1240,45 +1235,35 @@ def test_value_counts_bins(self): tm.assert_series_equal(result, expected) def test_value_counts_dtypes(self): - msg2 = "pandas.value_counts is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg2): - result = algos.value_counts(np.array([1, 1.0])) + result = algos.value_counts_internal(np.array([1, 1.0])) assert len(result) == 1 - with tm.assert_produces_warning(FutureWarning, match=msg2): - result = algos.value_counts(np.array([1, 1.0]), bins=1) + result = algos.value_counts_internal(np.array([1, 1.0]), bins=1) assert len(result) == 1 - with tm.assert_produces_warning(FutureWarning, match=msg2): - result = algos.value_counts(Series([1, 1.0, "1"])) # object + result = algos.value_counts_internal(Series([1, 1.0, "1"])) # object assert len(result) == 2 msg = "bins argument only works with numeric data" with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=msg2): - algos.value_counts(np.array(["1", 1], dtype=object), bins=1) + algos.value_counts_internal(np.array(["1", 1], dtype=object), bins=1) def test_value_counts_nat(self): td = Series([np.timedelta64(10000), NaT], dtype="timedelta64[ns]") dt = to_datetime(["NaT", "2014-01-01"]) - msg = "pandas.value_counts is deprecated" - for ser in [td, dt]: - with tm.assert_produces_warning(FutureWarning, match=msg): - vc = algos.value_counts(ser) - vc_with_na = algos.value_counts(ser, dropna=False) + vc = algos.value_counts_internal(ser) + vc_with_na = algos.value_counts_internal(ser, dropna=False) assert len(vc) == 1 assert len(vc_with_na) == 2 exp_dt = Series({Timestamp("2014-01-01 00:00:00"): 1}, name="count") - with tm.assert_produces_warning(FutureWarning, match=msg): - result_dt = algos.value_counts(dt) + result_dt = algos.value_counts_internal(dt) tm.assert_series_equal(result_dt, exp_dt) exp_td = Series({np.timedelta64(10000): 1}, name="count") - with tm.assert_produces_warning(FutureWarning, match=msg): - result_td = algos.value_counts(td) + result_td = algos.value_counts_internal(td) tm.assert_series_equal(result_td, exp_td) @pytest.mark.parametrize("dtype", [object, "M8[us]"]) @@ -1435,16 +1420,13 @@ def test_value_counts_normalized(self, dtype): def test_value_counts_uint64(self): arr = np.array([2**63], dtype=np.uint64) expected = Series([1], index=[2**63], name="count") - msg = "pandas.value_counts is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = algos.value_counts(arr) + result = algos.value_counts_internal(arr) tm.assert_series_equal(result, expected) arr = np.array([-1, 2**63], dtype=object) expected = Series([1, 1], index=[-1, 2**63], name="count") - with tm.assert_produces_warning(FutureWarning, match=msg): - result = algos.value_counts(arr) + result = algos.value_counts_internal(arr) tm.assert_series_equal(result, expected)