From da3952702222e59020f4b68c567a0bc063f8a6d8 Mon Sep 17 00:00:00 2001 From: Brock Date: Wed, 2 Nov 2022 16:29:30 -0700 Subject: [PATCH] CLN: assorted follow-ups --- doc/source/getting_started/install.rst | 2 +- pandas/core/dtypes/astype.py | 1 + pandas/core/dtypes/cast.py | 2 +- pandas/core/dtypes/concat.py | 48 +++---------------- pandas/core/frame.py | 1 - pandas/core/indexes/multi.py | 22 +-------- pandas/core/internals/concat.py | 8 ++-- pandas/core/series.py | 1 - pandas/core/sorting.py | 10 +--- pandas/io/formats/style.py | 14 ++---- pandas/plotting/_matplotlib/compat.py | 7 --- pandas/plotting/_matplotlib/core.py | 16 ++----- pandas/plotting/_matplotlib/style.py | 8 +--- pandas/plotting/_matplotlib/tools.py | 12 +---- pandas/tests/arithmetic/test_numeric.py | 23 ++------- pandas/tests/frame/methods/test_astype.py | 12 ++--- pandas/tests/groupby/test_allowlist.py | 2 + .../tests/indexes/datetimes/test_indexing.py | 1 - .../tests/indexes/timedeltas/test_indexing.py | 9 +--- .../tests/io/formats/style/test_matplotlib.py | 3 +- pandas/tests/plotting/common.py | 12 +---- pandas/tests/plotting/frame/test_frame.py | 13 +---- .../tests/plotting/frame/test_frame_color.py | 3 +- pandas/tests/plotting/test_datetimelike.py | 9 +--- pandas/tests/plotting/test_hist_method.py | 7 +-- pandas/tests/plotting/test_series.py | 7 +-- 26 files changed, 45 insertions(+), 208 deletions(-) diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index e9bf341eae73f..ca30f345ac1c4 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -417,7 +417,7 @@ Dependency Minimum Version optional_extra Notes PyTables 3.6.1 hdf5 HDF5-based reading / writing blosc 1.21.0 hdf5 Compression for HDF5 zlib hdf5 Compression for HDF5 -fastparquet 0.4.0 - Parquet reading / writing (pyarrow is default) +fastparquet 0.6.3 - Parquet reading / writing (pyarrow is default) pyarrow 6.0.0 parquet, feather Parquet, ORC, and feather reading / writing pyreadstat 1.1.2 spss SPSS files (.sav) reading odfpy 1.4.1 excel Open document format (.odf, .ods, .odt) reading / writing diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index ebd45da044ad9..2885989aa1867 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -222,6 +222,7 @@ def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> Arra # Series.astype behavior pre-2.0 did # values.tz_localize("UTC").tz_convert(dtype.tz) # which did not match the DTA/DTI behavior. + # We special-case here to give a Series-specific exception message. raise TypeError( "Cannot use .astype to convert from timezone-naive dtype to " "timezone-aware dtype. Use ser.dt.tz_localize instead." diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index a75448347233c..13802581c92ad 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1414,7 +1414,7 @@ def _ensure_nanosecond_dtype(dtype: DtypeObj) -> DtypeObj: # TODO: other value-dependent functions to standardize here include -# dtypes.concat.cast_to_common_type and Index._find_common_type_compat +# Index._find_common_type_compat def find_result_type(left: ArrayLike, right: Any) -> DtypeObj: """ Find the type/dtype for a the result of an operation between these objects. diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 5b11945a8589e..91d5ac865b6b6 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -3,19 +3,12 @@ """ from __future__ import annotations -from typing import ( - TYPE_CHECKING, - cast, -) +from typing import TYPE_CHECKING import warnings import numpy as np -from pandas._typing import ( - ArrayLike, - AxisInt, - DtypeObj, -) +from pandas._typing import AxisInt from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.astype import astype_array @@ -23,10 +16,7 @@ common_dtype_categorical_compat, find_common_type, ) -from pandas.core.dtypes.common import ( - is_dtype_equal, - is_sparse, -) +from pandas.core.dtypes.common import is_dtype_equal from pandas.core.dtypes.dtypes import ( DatetimeTZDtype, ExtensionDtype, @@ -39,34 +29,6 @@ if TYPE_CHECKING: from pandas.core.arrays import Categorical - from pandas.core.arrays.sparse import SparseArray - - -def cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike: - """ - Helper function for `arr.astype(common_dtype)` but handling all special - cases. - """ - if is_dtype_equal(arr.dtype, dtype): - return arr - - if is_sparse(arr) and not is_sparse(dtype): - # TODO(2.0): remove special case once SparseArray.astype deprecation - # is enforced. - # problem case: SparseArray.astype(dtype) doesn't follow the specified - # dtype exactly, but converts this to Sparse[dtype] -> first manually - # convert to dense array - - # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type - # "Union[dtype[Any], ExtensionDtype]"; expected "Union[dtype[Any], None, type, _ - # SupportsDType[dtype[Any]], str, Union[Tuple[Any, int], Tuple[Any, - # Union[SupportsIndex, Sequence[SupportsIndex]]], List[Any], _DTypeDict, - # Tuple[Any, Any]]]" [arg-type] - arr = cast("SparseArray", arr) - return arr.to_dense().astype(dtype, copy=False) # type: ignore[arg-type] - - # astype_array includes ensure_wrapped_if_datetimelike - return astype_array(arr, dtype=dtype, copy=False) def concat_compat(to_concat, axis: AxisInt = 0, ea_compat_axis: bool = False): @@ -126,7 +88,9 @@ def is_nonempty(x) -> bool: if not single_dtype: target_dtype = find_common_type([x.dtype for x in to_concat]) target_dtype = common_dtype_categorical_compat(to_concat, target_dtype) - to_concat = [cast_to_common_type(arr, target_dtype) for arr in to_concat] + to_concat = [ + astype_array(arr, target_dtype, copy=False) for arr in to_concat + ] if isinstance(to_concat[0], ABCExtensionArray): # TODO: what about EA-backed Index? diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 58859054943b3..2965baf837419 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5046,7 +5046,6 @@ def align( broadcast_axis=broadcast_axis, ) - # error: Signature of "set_axis" incompatible with supertype "NDFrame" @Appender( """ Examples diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index c7e47d1c21329..9e3fc7692fa66 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -14,7 +14,6 @@ Sequence, Tuple, cast, - overload, ) import warnings @@ -3750,28 +3749,9 @@ def isin(self, values, level=None) -> npt.NDArray[np.bool_]: return np.zeros(len(levs), dtype=np.bool_) return levs.isin(values) - @overload - def set_names( - self, names, *, level=..., inplace: Literal[False] = ... - ) -> MultiIndex: - ... - - @overload - def set_names(self, names, *, level=..., inplace: Literal[True]) -> None: - ... - - @overload - def set_names(self, names, *, level=..., inplace: bool = ...) -> MultiIndex | None: - ... - - def set_names( - self, names, *, level=None, inplace: bool = False - ) -> MultiIndex | None: - return super().set_names(names=names, level=level, inplace=inplace) - # error: Incompatible types in assignment (expression has type overloaded function, # base class "Index" defined the type as "Callable[[Index, Any, bool], Any]") - rename = set_names # type: ignore[assignment] + rename = Index.set_names # type: ignore[assignment] # --------------------------------------------------------------- # Arithmetic/Numeric Methods - Disabled diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index c8ad7dd328edf..0592db8ad608d 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -24,6 +24,7 @@ ) from pandas.util._decorators import cache_readonly +from pandas.core.dtypes.astype import astype_array from pandas.core.dtypes.cast import ( ensure_dtype_can_hold_na, find_common_type, @@ -34,10 +35,7 @@ is_scalar, needs_i8_conversion, ) -from pandas.core.dtypes.concat import ( - cast_to_common_type, - concat_compat, -) +from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.dtypes import ( DatetimeTZDtype, ExtensionDtype, @@ -153,7 +151,7 @@ def concat_arrays(to_concat: list) -> ArrayLike: to_concat = [ arr.to_array(target_dtype) if isinstance(arr, NullArrayProxy) - else cast_to_common_type(arr, target_dtype) + else astype_array(arr, target_dtype, copy=False) for arr in to_concat ] diff --git a/pandas/core/series.py b/pandas/core/series.py index 9f05eba00b05c..bba225bb91caf 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4925,7 +4925,6 @@ def rename( else: return self._set_name(index, inplace=inplace) - # error: Signature of "set_axis" incompatible with supertype "NDFrame" @Appender( """ Examples diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 58eef2a39b37a..b28a9def8a7ea 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -11,7 +11,6 @@ Sequence, cast, ) -import warnings import numpy as np @@ -341,14 +340,7 @@ def lexsort_indexer( keys = [ensure_key_mapped(k, key) for k in keys] for k, order in zip(keys, orders): - with warnings.catch_warnings(): - # TODO(2.0): unnecessary once deprecation is enforced - # GH#45618 don't issue warning user can't do anything about - warnings.filterwarnings( - "ignore", ".*(SparseArray|SparseDtype).*", category=FutureWarning - ) - - cat = Categorical(k, ordered=True) + cat = Categorical(k, ordered=True) if na_position not in ["last", "first"]: raise ValueError(f"invalid na_position: {na_position}") diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 8f21823ddcd02..5c359be6aacc6 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -3604,15 +3604,11 @@ def _background_gradient( rng = smax - smin # extend lower / upper bounds, compresses color range norm = mpl.colors.Normalize(smin - (rng * low), smax + (rng * high)) - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 - if mpl_ge_3_6_0(): - if cmap is None: - rgbas = mpl.colormaps[mpl.rcParams["image.cmap"]](norm(gmap)) - else: - rgbas = mpl.colormaps.get_cmap(cmap)(norm(gmap)) + if cmap is None: + rgbas = mpl.colormaps[mpl.rcParams["image.cmap"]](norm(gmap)) else: - rgbas = plt.cm.get_cmap(cmap)(norm(gmap)) + rgbas = mpl.colormaps.get_cmap(cmap)(norm(gmap)) def relative_luminance(rgba) -> float: """ @@ -3891,10 +3887,8 @@ def css_calc(x, left: float, right: float, align: str, color: str | list | tuple if cmap is not None: # use the matplotlib colormap input with _mpl(Styler.bar) as (plt, mpl): - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 - cmap = ( - (mpl.colormaps[cmap] if mpl_ge_3_6_0() else mpl.cm.get_cmap(cmap)) + mpl.colormaps[cmap] if isinstance(cmap, str) else cmap # assumed to be a Colormap instance as documented ) diff --git a/pandas/plotting/_matplotlib/compat.py b/pandas/plotting/_matplotlib/compat.py index 86b218db4ebe6..7314f05e9f19c 100644 --- a/pandas/plotting/_matplotlib/compat.py +++ b/pandas/plotting/_matplotlib/compat.py @@ -1,8 +1,6 @@ # being a bit too dynamic from __future__ import annotations -import operator - from pandas.util.version import Version @@ -15,8 +13,3 @@ def inner(): return op(Version(mpl.__version__), Version(version)) return inner - - -mpl_ge_3_4_0 = _mpl_version("3.4.0", operator.ge) -mpl_ge_3_5_0 = _mpl_version("3.5.0", operator.ge) -mpl_ge_3_6_0 = _mpl_version("3.6.0", operator.ge) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 605cc1d94e0af..73388ee9755c5 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -55,7 +55,6 @@ from pandas.core.frame import DataFrame from pandas.io.formats.printing import pprint_thing -from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters from pandas.plotting._matplotlib.groupby import reconstruct_data_with_by from pandas.plotting._matplotlib.misc import unpack_single_str_list @@ -1229,19 +1228,13 @@ def _make_plot(self): c_values = c if self.colormap is not None: - if mpl_ge_3_6_0(): - cmap = mpl.colormaps.get_cmap(self.colormap) - else: - cmap = self.plt.cm.get_cmap(self.colormap) + cmap = mpl.colormaps.get_cmap(self.colormap) else: # cmap is only used if c_values are integers, otherwise UserWarning if is_integer_dtype(c_values): # pandas uses colormap, matplotlib uses cmap. cmap = "Greys" - if mpl_ge_3_6_0(): - cmap = mpl.colormaps[cmap] - else: - cmap = self.plt.cm.get_cmap(cmap) + cmap = mpl.colormaps[cmap] else: cmap = None @@ -1309,10 +1302,7 @@ def _make_plot(self) -> None: ax = self.axes[0] # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or "BuGn" - if mpl_ge_3_6_0(): - cmap = mpl.colormaps.get_cmap(cmap) - else: - cmap = self.plt.cm.get_cmap(cmap) + cmap = mpl.colormaps.get_cmap(cmap) cb = self.kwds.pop("colorbar", True) if C is None: diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index f060255c4e9c5..839da35a8ae83 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -10,7 +10,6 @@ import warnings import matplotlib as mpl -from matplotlib import cm import matplotlib.colors import numpy as np @@ -21,8 +20,6 @@ import pandas.core.common as com -from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 - if TYPE_CHECKING: from matplotlib.colors import Colormap @@ -153,10 +150,7 @@ def _get_cmap_instance(colormap: str | Colormap) -> Colormap: """Get instance of matplotlib colormap.""" if isinstance(colormap, str): cmap = colormap - if mpl_ge_3_6_0(): - colormap = mpl.colormaps[colormap] - else: - colormap = cm.get_cmap(colormap) + colormap = mpl.colormaps[colormap] if colormap is None: raise ValueError(f"Colormap {cmap} is not recognized") return colormap diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 1749c05a555a1..eecfcbc72f489 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -22,8 +22,6 @@ ABCSeries, ) -from pandas.plotting._matplotlib import compat - if TYPE_CHECKING: from matplotlib.axes import Axes from matplotlib.axis import Axis @@ -396,10 +394,7 @@ def handle_shared_axes( row_num = lambda x: x.get_subplotspec().rowspan.start col_num = lambda x: x.get_subplotspec().colspan.start - if compat.mpl_ge_3_4_0(): - is_first_col = lambda x: x.get_subplotspec().is_first_col() - else: - is_first_col = lambda x: x.is_first_col() + is_first_col = lambda x: x.get_subplotspec().is_first_col() if nrows > 1: try: @@ -421,10 +416,7 @@ def handle_shared_axes( except IndexError: # if gridspec is used, ax.rowNum and ax.colNum may different # from layout shape. in this case, use last_row logic - if compat.mpl_ge_3_4_0(): - is_last_row = lambda x: x.get_subplotspec().is_last_row() - else: - is_last_row = lambda x: x.is_last_row() + is_last_row = lambda x: x.get_subplotspec().is_last_row() for ax in axarr: if is_last_row(ax): continue diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 95d4d6629f608..529dd6baa70c0 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -28,7 +28,6 @@ Int64Index, UInt64Index, ) -from pandas.core.arrays import TimedeltaArray from pandas.core.computation import expressions as expr from pandas.tests.arithmetic.common import ( assert_invalid_addsub_type, @@ -210,15 +209,10 @@ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box_with_array): index = numeric_idx expected = TimedeltaIndex([Timedelta(days=n) for n in range(len(index))]) if isinstance(scalar_td, np.timedelta64): - # TODO(2.0): once TDA.astype converts to m8, just do expected.astype - tda = expected._data dtype = scalar_td.dtype - expected = type(tda)._simple_new(tda._ndarray.astype(dtype), dtype=dtype) + expected = expected.astype(dtype) elif type(scalar_td) is timedelta: - # TODO(2.0): once TDA.astype converts to m8, just do expected.astype - tda = expected._data - dtype = np.dtype("m8[us]") - expected = type(tda)._simple_new(tda._ndarray.astype(dtype), dtype=dtype) + expected = expected.astype("m8[us]") index = tm.box_expected(index, box) expected = tm.box_expected(expected, box) @@ -251,11 +245,7 @@ def test_numeric_arr_mul_tdscalar_numexpr_path( expected = arr_i8.view("timedelta64[D]").astype("timedelta64[ns]") if type(scalar_td) is timedelta: - # TODO(2.0): this shouldn't depend on 'box' expected = expected.astype("timedelta64[us]") - # TODO(2.0): won't be necessary to construct TimedeltaArray - # explicitly. - expected = TimedeltaArray._simple_new(expected, dtype=expected.dtype) expected = tm.box_expected(expected, box, transpose=False) @@ -272,18 +262,13 @@ def test_numeric_arr_rdiv_tdscalar(self, three_days, numeric_idx, box_with_array expected = TimedeltaIndex(["3 Days", "36 Hours"]) if isinstance(three_days, np.timedelta64): - # TODO(2.0): just use expected.astype - tda = expected._data dtype = three_days.dtype if dtype < np.dtype("m8[s]"): # i.e. resolution is lower -> use lowest supported resolution dtype = np.dtype("m8[s]") - expected = type(tda)._simple_new(tda._ndarray.astype(dtype), dtype=dtype) + expected = expected.astype(dtype) elif type(three_days) is timedelta: - # TODO(2.0): just use expected.astype - tda = expected._data - dtype = np.dtype("m8[us]") - expected = type(tda)._simple_new(tda._ndarray.astype(dtype), dtype=dtype) + expected = expected.astype("m8[us]") index = tm.box_expected(index, box) expected = tm.box_expected(expected, box) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 8e6aa43ff434c..9d79d0259ae16 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -426,13 +426,8 @@ def test_astype_to_datetime_unit(self, unit): else: # we use the nearest supported dtype (i.e. M8[s]) exp_dtype = "M8[s]" - # TODO(2.0): once DataFrame constructor doesn't cast ndarray inputs. - # can simplify this - exp_values = arr.astype(exp_dtype) - exp_dta = pd.core.arrays.DatetimeArray._simple_new( - exp_values, dtype=exp_values.dtype - ) - exp_df = DataFrame(exp_dta) + + exp_df = DataFrame(arr.astype(exp_dtype)) assert (exp_df.dtypes == exp_dtype).all() tm.assert_frame_equal(result, exp_df) @@ -447,8 +442,7 @@ def test_astype_to_datetime_unit(self, unit): exp_dta = exp_ser._values res_index = idx.astype(dtype) - # TODO(2.0): should be able to just call pd.Index(exp_ser) - exp_index = pd.DatetimeIndex._simple_new(exp_dta, name=idx.name) + exp_index = pd.Index(exp_ser) assert exp_index.dtype == exp_dtype tm.assert_index_equal(res_index, exp_index) diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index 38de589d0c60c..034514cb0bcfb 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -74,6 +74,8 @@ def raw_frame(multiindex_dataframe_random_data): @pytest.mark.parametrize("axis", [0, 1]) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize("sort", [True, False]) +@pytest.mark.filterwarnings("ignore:Using the level keyword:FutureWarning") +@pytest.mark.filterwarnings("ignore:The default value of numeric_only:FutureWarning") def test_regression_allowlist_methods(raw_frame, op, level, axis, skipna, sort): # GH6944 # GH 17537 diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 7e4df5ae8699c..c5b135880ee8c 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -668,7 +668,6 @@ def test_get_indexer_mixed_dtypes(self, target): ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]), ], ) - @pytest.mark.filterwarnings("ignore:Comparison of Timestamp.*:FutureWarning") def test_get_indexer_out_of_bounds_date(self, target, positions): values = DatetimeIndex([Timestamp("2020-01-01"), Timestamp("2020-01-02")]) diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index ff4b8564f86ca..4b7140b112bd9 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -82,14 +82,9 @@ def test_get_loc_key_unit_mismatch(self): assert loc == 1 def test_get_loc_key_unit_mismatch_not_castable(self): - # TODO(2.0): once TDA.astype supports m8[s] directly, tdi - # can be constructed directly - tda = to_timedelta(["0 days", "1 days", "2 days"])._data - arr = np.array(tda).astype("m8[s]") - tda2 = type(tda)._simple_new(arr, dtype=arr.dtype) - tdi = TimedeltaIndex(tda2) + tdi = to_timedelta(["0 days", "1 days", "2 days"]).astype("m8[s]") assert tdi.dtype == "m8[s]" - key = tda[0]._as_unit("ns") + Timedelta(1) + key = tdi[0]._as_unit("ns") + Timedelta(1) with pytest.raises(KeyError, match=r"Timedelta\('0 days 00:00:00.000000001'\)"): tdi.get_loc(key) diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py index f0c4152e3339b..c19f27dc064d1 100644 --- a/pandas/tests/io/formats/style/test_matplotlib.py +++ b/pandas/tests/io/formats/style/test_matplotlib.py @@ -13,7 +13,6 @@ import matplotlib as mpl from pandas.io.formats.style import Styler -from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 @pytest.fixture @@ -263,7 +262,7 @@ def test_background_gradient_gmap_wrong_series(styler_blank): @pytest.mark.parametrize( "cmap", - ["PuBu", mpl.colormaps["PuBu"] if mpl_ge_3_6_0() else mpl.cm.get_cmap("PuBu")], + ["PuBu", mpl.colormaps["PuBu"]], ) def test_bar_colormap(cmap): data = DataFrame([[1, 2], [3, 4]]) diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 6567504894236..20de38ebf6665 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -510,18 +510,10 @@ def _unpack_cycler(self, rcParams, field="color"): return [v[field] for v in rcParams["axes.prop_cycle"]] def get_x_axis(self, ax): - from pandas.plotting._matplotlib.compat import mpl_ge_3_5_0 - - if mpl_ge_3_5_0(): - return ax._shared_axes["x"] - return ax._shared_x_axes + return ax._shared_axes["x"] def get_y_axis(self, ax): - from pandas.plotting._matplotlib.compat import mpl_ge_3_5_0 - - if mpl_ge_3_5_0(): - return ax._shared_axes["y"] - return ax._shared_y_axes + return ax._shared_axes["y"] def _check_plot_works(f, filterwarnings="always", default_axes=False, **kwargs): diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 476f0a89980ea..73b723ba7f597 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -32,15 +32,10 @@ from pandas.io.formats.printing import pprint_thing -try: - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 -except ImportError: - mpl_ge_3_6_0 = lambda: True - @td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): - @pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed") + @pytest.mark.xfail(reason="Api changed in 3.6.0") @pytest.mark.slow def test_plot(self): df = tm.makeTimeDataFrame() @@ -735,7 +730,6 @@ def test_plot_scatter_with_categorical_data(self, x, y): _check_plot_works(df.plot.scatter, x=x, y=y) def test_plot_scatter_with_c(self): - from pandas.plotting._matplotlib.compat import mpl_ge_3_4_0 df = DataFrame( np.random.randint(low=0, high=100, size=(6, 4)), @@ -748,10 +742,7 @@ def test_plot_scatter_with_c(self): # default to Greys assert ax.collections[0].cmap.name == "Greys" - if mpl_ge_3_4_0(): - assert ax.collections[0].colorbar.ax.get_ylabel() == "z" - else: - assert ax.collections[0].colorbar._label == "z" + assert ax.collections[0].colorbar.ax.get_ylabel() == "z" cm = "cubehelix" ax = df.plot.scatter(x="x", y="y", c="z", colormap=cm) diff --git a/pandas/tests/plotting/frame/test_frame_color.py b/pandas/tests/plotting/frame/test_frame_color.py index 2e860c2615322..ed129d315a0c6 100644 --- a/pandas/tests/plotting/frame/test_frame_color.py +++ b/pandas/tests/plotting/frame/test_frame_color.py @@ -199,14 +199,13 @@ def test_if_scatterplot_colorbars_are_next_to_parent_axes(self): @pytest.mark.parametrize("kw", ["c", "color"]) def test_scatter_with_c_column_name_with_colors(self, cmap, kw): # https://github.com/pandas-dev/pandas/issues/34316 - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 df = DataFrame( [[5.1, 3.5], [4.9, 3.0], [7.0, 3.2], [6.4, 3.2], [5.9, 3.0]], columns=["length", "width"], ) df["species"] = ["r", "r", "g", "g", "b"] - if mpl_ge_3_6_0() and cmap is not None: + if cmap is not None: with tm.assert_produces_warning(UserWarning, check_stacklevel=False): ax = df.plot.scatter(x=0, y=1, cmap=cmap, **{kw: "species"}) else: diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index f75e5cd3491a4..3149fa9cb2095 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -39,11 +39,6 @@ from pandas.core.indexes.timedeltas import timedelta_range from pandas.tests.plotting.common import TestPlotBase -try: - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 -except ImportError: - mpl_ge_3_6_0 = lambda: True - from pandas.tseries.offsets import WeekOfMonth @@ -265,7 +260,7 @@ def test_plot_multiple_inferred_freq(self): ser = Series(np.random.randn(len(dr)), index=dr) _check_plot_works(ser.plot) - @pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed") + @pytest.mark.xfail(reason="Api changed in 3.6.0") def test_uhf(self): import pandas.plotting._matplotlib.converter as conv @@ -1215,7 +1210,7 @@ def test_secondary_legend(self): # TODO: color cycle problems assert len(colors) == 4 - @pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed") + @pytest.mark.xfail(reason="Api changed in 3.6.0") def test_format_date_axis(self): rng = date_range("1/1/2012", periods=12, freq="M") df = DataFrame(np.random.randn(len(rng), 3), rng) diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index dc586d15ba115..9d90f2e405803 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -18,11 +18,6 @@ _check_plot_works, ) -try: - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 -except ImportError: - mpl_ge_3_6_0 = lambda: True - @pytest.fixture def ts(): @@ -196,7 +191,7 @@ def test_hist_kwargs(self, ts): ax = ts.plot.hist(align="left", stacked=True, ax=ax) tm.close() - @pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed") + @pytest.mark.xfail(reason="Api changed in 3.6.0") @td.skip_if_no_scipy def test_hist_kde(self, ts): diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index d8004ad563196..d9505b4d593e6 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -20,11 +20,6 @@ _check_plot_works, ) -try: - from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 -except ImportError: - mpl_ge_3_6_0 = lambda: True - @pytest.fixture def ts(): @@ -497,7 +492,7 @@ def test_kde_missing_vals(self): # gh-14821: check if the values have any missing values assert any(~np.isnan(axes.lines[0].get_xdata())) - @pytest.mark.xfail(mpl_ge_3_6_0(), reason="Api changed") + @pytest.mark.xfail(reason="Api changed in 3.6.0") def test_boxplot_series(self, ts): _, ax = self.plt.subplots() ax = ts.plot.box(logy=True, ax=ax)