From 96d9d295181d8d465cd4ee3ae7c580f8c05ad641 Mon Sep 17 00:00:00 2001 From: Richard Shadrach Date: Mon, 8 Nov 2021 17:34:53 -0500 Subject: [PATCH 1/2] ENH: Use find_stack_level in pandas.core --- pandas/core/accessor.py | 3 +- pandas/core/arraylike.py | 3 +- pandas/core/arrays/categorical.py | 20 ++++++------- pandas/core/arrays/datetimes.py | 4 +-- pandas/core/arrays/sparse/array.py | 4 +-- pandas/core/arrays/sparse/dtype.py | 3 +- pandas/core/common.py | 3 +- pandas/core/computation/align.py | 5 +++- pandas/core/computation/eval.py | 3 +- pandas/core/config_init.py | 4 ++- pandas/core/construction.py | 5 ++-- pandas/core/describe.py | 3 +- pandas/core/dtypes/cast.py | 18 ++++++------ pandas/core/dtypes/common.py | 5 ++-- pandas/core/frame.py | 25 ++++++++-------- pandas/core/generic.py | 28 +++++++++--------- pandas/core/groupby/generic.py | 3 +- pandas/core/index.py | 4 ++- pandas/core/indexers/utils.py | 2 +- pandas/core/indexes/accessors.py | 4 ++- pandas/core/indexes/base.py | 40 +++++++++++++------------- pandas/core/indexes/category.py | 7 +++-- pandas/core/indexes/datetimelike.py | 3 +- pandas/core/indexes/datetimes.py | 8 +++--- pandas/core/indexes/multi.py | 21 +++++++------- pandas/core/indexes/numeric.py | 3 +- pandas/core/indexes/period.py | 3 +- pandas/core/indexes/range.py | 9 +++--- pandas/core/indexing.py | 5 ++-- pandas/core/internals/__init__.py | 4 ++- pandas/core/internals/array_manager.py | 2 +- pandas/core/internals/blocks.py | 4 +-- pandas/core/internals/construction.py | 3 +- pandas/core/internals/managers.py | 4 +-- pandas/core/ops/__init__.py | 3 +- pandas/core/reshape/melt.py | 3 +- pandas/core/reshape/merge.py | 7 +++-- pandas/core/series.py | 13 +++++---- pandas/core/strings/accessor.py | 5 ++-- pandas/core/tools/datetimes.py | 3 +- pandas/core/window/ewm.py | 2 +- pandas/core/window/rolling.py | 7 +++-- 42 files changed, 171 insertions(+), 137 deletions(-) diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index c31368f179ef0..07fa5799fe371 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -9,6 +9,7 @@ import warnings from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level class DirNamesMixin: @@ -267,7 +268,7 @@ def decorator(accessor): f"{repr(name)} for type {repr(cls)} is overriding a preexisting " f"attribute with the same name.", UserWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) setattr(cls, name, CachedAccessor(name, accessor)) cls._accessors.add(name) diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index fe09a044566f8..11d32e8a159f3 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -11,6 +11,7 @@ import numpy as np from pandas._libs import lib +from pandas.util._exceptions import find_stack_level from pandas.core.construction import extract_array from pandas.core.ops import ( @@ -210,7 +211,7 @@ def _maybe_fallback(ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any): "or align manually (eg 'df1, df2 = df1.align(df2)') before passing to " "the ufunc to obtain the future behaviour and silence this warning.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) # keep the first dataframe of the inputs, other DataFrame/Series is diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c7f587b35f557..fd84d2dea0b18 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -393,7 +393,7 @@ def __init__( "Allowing scalars in the Categorical constructor is deprecated " "and will raise in a future version. Use `[value]` instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) values = [values] @@ -948,7 +948,7 @@ def set_categories( "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1048,7 +1048,7 @@ def rename_categories(self, new_categories, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1180,7 +1180,7 @@ def add_categories(self, new_categories, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1255,7 +1255,7 @@ def remove_categories(self, removals, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1330,7 +1330,7 @@ def remove_unused_categories(self, inplace=no_default): "remove_unused_categories is deprecated and " "will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1886,7 +1886,7 @@ def to_dense(self) -> np.ndarray: "Categorical.to_dense is deprecated and will be removed in " "a future version. Use np.asarray(cat) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return np.asarray(self) @@ -1903,7 +1903,7 @@ def _codes(self, value: np.ndarray): "Setting the codes on a Categorical is deprecated and will raise in " "a future version. Create a new Categorical object instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # GH#40606 NDArrayBacked.__init__(self, value, self.dtype) @@ -1926,7 +1926,7 @@ def take_nd(self, indexer, allow_fill: bool = False, fill_value=None): warn( "Categorical.take_nd is deprecated, use Categorical.take instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.take(indexer, allow_fill=allow_fill, fill_value=fill_value) @@ -2352,7 +2352,7 @@ def is_dtype_equal(self, other) -> bool: "Categorical.is_dtype_equal is deprecated and will be removed " "in a future version", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) try: return self._categories_match_up_to_permutation(other) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 4fecbe4be9681..a0a7ef3501d7f 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1206,7 +1206,7 @@ def to_perioddelta(self, freq) -> TimedeltaArray: "Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead.", FutureWarning, # stacklevel chosen to be correct for when called from DatetimeIndex - stacklevel=3, + stacklevel=find_stack_level(), ) from pandas.core.arrays.timedeltas import TimedeltaArray @@ -1373,7 +1373,7 @@ def weekofyear(self): "weekofyear and return an Index, you may call " "pd.Int64Index(idx.isocalendar().week)", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) week_series = self.isocalendar().week if week_series.hasnans: diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 960544a2f89ea..c054710a01f75 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -467,7 +467,7 @@ def __init__( "loses timezone information. Cast to object before " "sparse to retain timezone information.", UserWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) data = np.asarray(data, dtype="datetime64[ns]") if fill_value is NaT: @@ -1089,7 +1089,7 @@ def searchsorted( ) -> npt.NDArray[np.intp] | np.intp: msg = "searchsorted requires high memory usage." - warnings.warn(msg, PerformanceWarning, stacklevel=2) + warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level()) if not is_scalar(v): v = np.asarray(v) v = np.asarray(v) diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 915e13bc3bbb2..d23e217e605c7 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -16,6 +16,7 @@ type_t, ) from pandas.errors import PerformanceWarning +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import ( ExtensionDtype, @@ -389,7 +390,7 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: f"values: '{fill_values}'. Picking the first and " "converting the rest.", PerformanceWarning, - stacklevel=6, + stacklevel=find_stack_level(), ) np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes] diff --git a/pandas/core/common.py b/pandas/core/common.py index 2bf925466e176..590296c4b12f5 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -36,6 +36,7 @@ Scalar, T, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.common import ( @@ -175,7 +176,7 @@ def cast_scalar_indexer(val, warn_float: bool = False): "Indexing with a float is deprecated, and will raise an IndexError " "in pandas 2.0. You can manually convert to an integer key instead.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return int(val) return val diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index a4bd0270f9451..f14882227ddd9 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -16,6 +16,7 @@ import numpy as np from pandas.errors import PerformanceWarning +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.generic import ( ABCDataFrame, @@ -126,7 +127,9 @@ def _align_core(terms): f"than an order of magnitude on term {repr(terms[i].name)}, " f"by more than {ordm:.4g}; performance may suffer." ) - warnings.warn(w, category=PerformanceWarning, stacklevel=6) + warnings.warn( + w, category=PerformanceWarning, stacklevel=find_stack_level() + ) f = partial(ti.reindex, reindexer, axis=axis, copy=False) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 26748eadb4c85..d82cc37b90ad4 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -7,6 +7,7 @@ import warnings from pandas._libs.lib import no_default +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg from pandas.core.computation.engines import ENGINES @@ -308,7 +309,7 @@ def eval( "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) exprs: list[str | BinOp] diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 0081f8cd074b6..31c2ec8f0cbf9 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -25,6 +25,8 @@ is_text, ) +from pandas.util._exceptions import find_stack_level + # compute use_bottleneck_doc = """ @@ -373,7 +375,7 @@ def _deprecate_negative_int_max_colwidth(key): "will not be supported in future version. Instead, use None " "to not limit the column width.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) cf.register_option( diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c6f131a9daba6..e3b41f2c7b8c2 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -25,6 +25,7 @@ DtypeObj, ) from pandas.errors import IntCastingNaNError +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import ( ExtensionDtype, @@ -538,7 +539,7 @@ def sanitize_array( "if they cannot be cast losslessly (matching Series behavior). " "To retain the old behavior, use DataFrame(data).astype(dtype)", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) # GH#40110 until the deprecation is enforced, we _dont_ # ignore the dtype for DataFrame, and _do_ cast even though @@ -777,7 +778,7 @@ def _try_cast( "passed to 'DataFrame', either all columns will be cast to that " "dtype, or a TypeError will be raised.", FutureWarning, - stacklevel=7, + stacklevel=find_stack_level(), ) subarr = np.array(arr, dtype=object, copy=copy) return subarr diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 2c4a340e8c8ea..8d88ce280d5c8 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -23,6 +23,7 @@ from pandas._libs.tslibs import Timestamp from pandas._typing import NDFrameT +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_percentile from pandas.core.dtypes.common import ( @@ -377,7 +378,7 @@ def select_describe_func( "version of pandas. Specify `datetime_is_numeric=True` to " "silence this warning and adopt the future behavior now.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) return describe_timestamp_as_categorical_1d elif is_timedelta64_dtype(data.dtype): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 432074a8dd699..2c26d6f838315 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -563,7 +563,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan): "dtype is deprecated. In a future version, this will be cast " "to object dtype. Pass `fill_value=Timestamp(date_obj)` instead.", FutureWarning, - stacklevel=8, + stacklevel=find_stack_level(), ) return dtype, fv elif isinstance(fill_value, str): @@ -1133,7 +1133,7 @@ def astype_nansafe( "Use .view(...) instead.", FutureWarning, # stacklevel chosen to be correct when reached via Series.astype - stacklevel=7, + stacklevel=find_stack_level(), ) if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") @@ -1155,7 +1155,7 @@ def astype_nansafe( "Use .view(...) instead.", FutureWarning, # stacklevel chosen to be correct when reached via Series.astype - stacklevel=7, + stacklevel=find_stack_level(), ) if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") @@ -1651,7 +1651,7 @@ def maybe_cast_to_datetime( "`pd.Series(values).dt.tz_localize(None)` " "instead.", FutureWarning, - stacklevel=8, + stacklevel=find_stack_level(), ) # equiv: dta.view(dtype) # Note: NOT equivalent to dta.astype(dtype) @@ -1691,7 +1691,7 @@ def maybe_cast_to_datetime( ".tz_localize('UTC').tz_convert(dtype.tz) " "or pd.Series(data.view('int64'), dtype=dtype)", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) value = dta.tz_localize("UTC").tz_convert(dtype.tz) @@ -1859,7 +1859,7 @@ def construct_2d_arraylike_from_scalar( shape = (length, width) if dtype.kind in ["m", "M"]: - value = maybe_unbox_datetimelike_tz_deprecation(value, dtype, stacklevel=4) + value = maybe_unbox_datetimelike_tz_deprecation(value, dtype) # error: Non-overlapping equality check (left operand type: "dtype[Any]", right # operand type: "Type[object]") elif dtype == object: # type: ignore[comparison-overlap] @@ -1932,9 +1932,7 @@ def construct_1d_arraylike_from_scalar( return subarr -def maybe_unbox_datetimelike_tz_deprecation( - value: Scalar, dtype: DtypeObj, stacklevel: int = 5 -): +def maybe_unbox_datetimelike_tz_deprecation(value: Scalar, dtype: DtypeObj): """ Wrap maybe_unbox_datetimelike with a check for a timezone-aware Timestamp along with a timezone-naive datetime64 dtype, which is deprecated. @@ -1963,7 +1961,7 @@ def maybe_unbox_datetimelike_tz_deprecation( "`pd.Series(values).dt.tz_localize(None)` " "instead.", FutureWarning, - stacklevel=stacklevel, + stacklevel=find_stack_level(), ) new_value = value.tz_localize(None) return maybe_unbox_datetimelike(new_value, dtype) diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 815a0a2040ddb..7ac8e6c47158c 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -22,6 +22,7 @@ ArrayLike, DtypeObj, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import _registry as registry from pandas.core.dtypes.dtypes import ( @@ -304,7 +305,7 @@ def is_categorical(arr) -> bool: "is_categorical is deprecated and will be removed in a future version. " "Use is_categorical_dtype instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr) @@ -1378,7 +1379,7 @@ def is_extension_type(arr) -> bool: "'is_extension_type' is deprecated and will be removed in a future " "version. Use 'is_extension_array_dtype' instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if is_categorical_dtype(arr): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ebf3428020652..81574102ec241 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -83,6 +83,7 @@ doc, rewrite_axis_style_signature, ) +from pandas.util._exceptions import find_stack_level from pandas.util._validators import ( validate_ascending, validate_axis_style_args, @@ -643,7 +644,7 @@ def __init__( "removed in a future version. Pass " "{name: data[name] for name in data.dtype.names} instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # a masked array @@ -1793,7 +1794,7 @@ def to_dict(self, orient: str = "dict", into=dict): warnings.warn( "DataFrame columns are not unique, some columns will be omitted.", UserWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # GH16122 into_c = com.standardize_mapping(into) @@ -1814,7 +1815,7 @@ def to_dict(self, orient: str = "dict", into=dict): "will be used in a future version. Use one of the above " "to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if orient.startswith("d"): @@ -2659,7 +2660,7 @@ def to_markdown( "'showindex' is deprecated. Only 'index' will be used " "in a future version. Use 'index' to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) kwargs.setdefault("headers", "keys") @@ -3218,7 +3219,7 @@ def info( warnings.warn( "null_counts is deprecated. Use show_counts instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) show_counts = null_counts info = DataFrameInfo( @@ -3591,7 +3592,7 @@ def _getitem_bool_array(self, key): warnings.warn( "Boolean Series key will be reindexed to match DataFrame index.", UserWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) elif len(key) != len(self.index): raise ValueError( @@ -4634,7 +4635,7 @@ def lookup( "You can use DataFrame.melt and DataFrame.loc " "as a substitute." ) - warnings.warn(msg, FutureWarning, stacklevel=2) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) n = len(row_labels) if n != len(col_labels): @@ -7751,7 +7752,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: squeeze = False @@ -9841,7 +9842,7 @@ def count( "deprecated and will be removed in a future version. Use groupby " "instead. df.count(level=1) should use df.groupby(level=1).count().", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._count_level(level, axis=axis, numeric_only=numeric_only) @@ -9941,7 +9942,7 @@ def _reduce( "will include datetime64 and datetime64tz columns in a " "future version.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) # Non-copy equivalent to # dt64_cols = self.dtypes.apply(is_datetime64_any_dtype) @@ -10016,7 +10017,7 @@ def _get_data() -> DataFrame: "version this will raise TypeError. Select only valid " "columns before calling the reduction.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) return out @@ -10049,7 +10050,7 @@ def _get_data() -> DataFrame: "version this will raise TypeError. Select only valid " "columns before calling the reduction.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) if hasattr(result, "dtype"): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 93bf70c27f8ff..23608cf0192df 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3647,7 +3647,7 @@ class max_speed "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) nv.validate_take((), kwargs) @@ -3781,7 +3781,7 @@ class animal locomotion "Passing lists as key for xs is deprecated and will be removed in a " "future version. Pass key as a tuple instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if level is not None: @@ -5556,7 +5556,7 @@ def __setattr__(self, name: str, value) -> None: "created via a new attribute name - see " "https://pandas.pydata.org/pandas-docs/" "stable/indexing.html#attribute-access", - stacklevel=2, + stacklevel=find_stack_level(), ) object.__setattr__(self, name, value) @@ -7774,7 +7774,7 @@ def between_time( "`include_start` and `include_end` are deprecated in " "favour of `inclusive`.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) left = True if isinstance(include_start, lib.NoDefault) else include_start right = True if isinstance(include_end, lib.NoDefault) else include_end @@ -9190,7 +9190,7 @@ def where( "try_cast keyword is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._where(cond, other, inplace, axis, level, errors=errors) @@ -9222,7 +9222,7 @@ def mask( "try_cast keyword is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) # see gh-21891 @@ -9415,7 +9415,7 @@ def slice_shift(self: NDFrameT, periods: int = 1, axis=0) -> NDFrameT: "and will be removed in a future version. " "You can use DataFrame/Series.shift instead." ) - warnings.warn(msg, FutureWarning, stacklevel=2) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) if periods == 0: return self @@ -9467,7 +9467,7 @@ def tshift(self: NDFrameT, periods: int = 1, freq=None, axis: Axis = 0) -> NDFra "Please use shift instead." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if freq is None: @@ -10282,7 +10282,7 @@ def _logical_func( "deprecated and will be removed in a future version. Use groupby " "instead. df.any(level=1) should use df.groupby(level=1).any()", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) if bool_only is not None: raise NotImplementedError( @@ -10378,7 +10378,7 @@ def _stat_function_ddof( "deprecated and will be removed in a future version. Use groupby " "instead. df.var(level=1) should use df.groupby(level=1).var().", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, ddof=ddof @@ -10431,7 +10431,7 @@ def _stat_function( "deprecated and will be removed in a future version. Use groupby " "instead. df.median(level=1) should use df.groupby(level=1).median().", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, numeric_only=numeric_only @@ -10498,7 +10498,7 @@ def _min_count_stat_function( "deprecated and will be removed in a future version. Use groupby " "instead. df.sum(level=1) should use df.groupby(level=1).sum().", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._agg_by_level( name, @@ -10582,7 +10582,7 @@ def mad(self, axis=None, skipna=None, level=None): "deprecated and will be removed in a future version. Use groupby " "instead. df.mad(level=1) should use df.groupby(level=1).mad()", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return self._agg_by_level("mad", axis=axis, level=level, skipna=skipna) @@ -10980,7 +10980,7 @@ def expanding( warnings.warn( "The `center` argument on `expanding` will be removed in the future.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: center = False diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 8a330d08bef78..3c45f7263265c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -37,6 +37,7 @@ Substitution, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_int64, @@ -1330,7 +1331,7 @@ def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return super().__getitem__(key) diff --git a/pandas/core/index.py b/pandas/core/index.py index 13a687b1c27e3..00ca6f9048a40 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1,5 +1,7 @@ import warnings +from pandas.util._exceptions import find_stack_level + from pandas.core.indexes.api import ( # noqa:F401 CategoricalIndex, DatetimeIndex, @@ -26,5 +28,5 @@ "pandas.core.index is deprecated and will be removed in a future version. " "The public classes are available in the top-level namespace.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index b1824413512c5..41920727c50fd 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -399,7 +399,7 @@ def unpack_1tuple(tup): "slice is deprecated and will raise in a future " "version. Pass a tuple instead.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return tup[0] diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index b8f4b5f9d3423..3aad1140294e5 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -8,6 +8,8 @@ import numpy as np +from pandas.util._exceptions import find_stack_level + from pandas.core.dtypes.common import ( is_categorical_dtype, is_datetime64_dtype, @@ -286,7 +288,7 @@ def weekofyear(self): "Series.dt.weekofyear and Series.dt.week have been deprecated. " "Please use Series.dt.isocalendar().week instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) week_series = self.isocalendar().week week_series.name = self.name diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index ba7dde7d2a4d8..91fe0ae877e13 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -399,7 +399,7 @@ def __new__( "'tupleize_cols' is deprecated and will raise TypeError in a " "future version. Use the specific Index subclass directly instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) from pandas.core.arrays import PandasArray @@ -632,7 +632,7 @@ def asi8(self): warnings.warn( "Index.asi8 is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return None @@ -746,7 +746,7 @@ def _get_attributes_dict(self) -> dict[str_t, Any]: "The Index._get_attributes_dict method is deprecated, and will be " "removed in a future version", DeprecationWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return {k: getattr(self, k, None) for k in self._attributes} @@ -919,7 +919,7 @@ def ravel(self, order="C"): "Index.ravel returning ndarray is deprecated; in a future version " "this will return a view on self.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if needs_i8_conversion(self.dtype): # Item "ndarray[Any, Any]" of "Union[ExtensionArray, ndarray[Any, Any]]" @@ -1191,7 +1191,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index @@ -1371,7 +1371,7 @@ def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: "The 'to_native_types' method is deprecated and will be removed in " "a future version. Use 'astype(str)' instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) values = self if slicer is not None: @@ -2503,7 +2503,7 @@ def is_mixed(self) -> bool: "Index.is_mixed is deprecated and will be removed in a future version. " "Check index.inferred_type directly instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.inferred_type in ["mixed"] @@ -2538,7 +2538,7 @@ def is_all_dates(self) -> bool: "Index.is_all_dates is deprecated, will be removed in a future version. " "check index.inferred_type instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._is_all_dates @@ -2905,7 +2905,7 @@ def __and__(self, other): "in the future this will be a logical operation matching " "Series.__and__. Use index.intersection(other) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.intersection(other) @@ -2916,7 +2916,7 @@ def __or__(self, other): "in the future this will be a logical operation matching " "Series.__or__. Use index.union(other) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.union(other) @@ -2927,7 +2927,7 @@ def __xor__(self, other): "in the future this will be a logical operation matching " "Series.__xor__. Use index.symmetric_difference(other) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.symmetric_difference(other) @@ -3073,7 +3073,7 @@ def union(self, other, sort=None): "object dtype. To retain the old behavior, " "use `index.astype(object).union(other)`", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) dtype = self._find_common_type_compat(other) @@ -3524,7 +3524,7 @@ def get_loc(self, key, method=None, tolerance=None): "and will raise in a future version. Use " "index.get_indexer([item], method=...) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if is_scalar(key) and isna(key) and not self.hasnans: @@ -3958,7 +3958,7 @@ def is_int(v): "and will raise TypeError in a future version. " "Use .loc with labels or .iloc with positions instead.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) indexer = key else: @@ -4107,7 +4107,7 @@ def reindex( "reindexing with a non-unique Index is deprecated and " "will raise in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) target = self._wrap_reindex_result(target, indexer, preserve_names) @@ -4849,7 +4849,7 @@ def is_type_compatible(self, kind: str_t) -> bool: "Index.is_type_compatible is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return kind == self.inferred_type @@ -5487,7 +5487,7 @@ def get_value(self, series: Series, key): "get_value is deprecated and will be removed in a future version. " "Use Series[key] instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) self._check_indexing_error(key) @@ -5555,7 +5555,7 @@ def set_value(self, arr, key, value): "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) loc = self._engine.get_loc(key) validate_numeric_casting(arr.dtype, value) @@ -7025,7 +7025,7 @@ def _maybe_cast_data_without_dtype( "In a future version, the Index constructor will not infer numeric " "dtypes when passed object-dtype sequences (matching Series behavior)", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) if result.dtype.kind in ["b", "c"]: return subarr @@ -7083,6 +7083,6 @@ def _maybe_try_sort(result, sort): warnings.warn( f"{err}, sort order is undefined for incomparable objects.", RuntimeWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return result diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e2dd5ecfde5a8..f26a24c38b19f 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -17,6 +17,7 @@ npt, ) from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -218,7 +219,7 @@ def __new__( "deprecated and will raise in a future version. " "Use CategoricalIndex([], ...) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) data = [] @@ -431,7 +432,7 @@ def reindex( "reindexing with a non-unique Index is deprecated and will " "raise in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if len(self) and indexer is not None: @@ -506,7 +507,7 @@ def take_nd(self, *args, **kwargs): "CategoricalIndex.take_nd is deprecated, use CategoricalIndex.take " "instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.take(*args, **kwargs) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index a0902a5fb32fe..104bce0369d37 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -36,6 +36,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -403,7 +404,7 @@ def is_type_compatible(self, kind: str) -> bool: f"{type(self).__name__}.is_type_compatible is deprecated and will be " "removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return kind in self._data._infer_matches diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 6078da3bedd8c..e283509206344 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -495,7 +495,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): "is deprecated and will be removed in a future version. " "You can stop passing 'keep_tz' to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: warnings.warn( @@ -505,7 +505,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): "can do 'idx.tz_convert(None)' before calling " "'to_series'.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: keep_tz = True @@ -752,7 +752,7 @@ def check_str_or_none(point): "with non-existing keys is deprecated and will raise a " "KeyError in a future Version.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) indexer = mask.nonzero()[0][::step] if len(indexer) == len(self): @@ -1042,7 +1042,7 @@ def date_range( warnings.warn( "Argument `closed` is deprecated in favor of `inclusive`.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if closed is None: inclusive = "both" diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index fe97d61be7548..128aa8e282a0d 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -46,6 +46,7 @@ deprecate_nonkeyword_arguments, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import coerce_indexer_dtype from pandas.core.dtypes.common import ( @@ -893,7 +894,7 @@ def set_levels( warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1054,7 +1055,7 @@ def set_codes(self, codes, level=None, inplace=None, verify_integrity: bool = Tr warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1166,14 +1167,14 @@ def copy( "parameter levels is deprecated and will be removed in a future " "version. Use the set_levels method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if codes is not None: warnings.warn( "parameter codes is deprecated and will be removed in a future " "version. Use the set_codes method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if deep: @@ -1202,7 +1203,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index @@ -1802,7 +1803,7 @@ def is_lexsorted(self) -> bool: "MultiIndex.is_lexsorted is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._is_lexsorted() @@ -1846,7 +1847,7 @@ def lexsort_depth(self) -> int: "MultiIndex.is_lexsorted is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._lexsort_depth @@ -2212,7 +2213,7 @@ def drop(self, codes, level=None, errors="raise"): "dropping on a non-lexsorted multi-index " "without a level parameter may impact performance.", PerformanceWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) loc = loc.nonzero()[0] inds.extend(loc) @@ -2877,7 +2878,7 @@ def _maybe_to_slice(loc): warnings.warn( "indexing past lexsort depth may impact performance.", PerformanceWarning, - stacklevel=10, + stacklevel=find_stack_level(), ) loc = np.arange(start, stop, dtype=np.intp) @@ -3335,7 +3336,7 @@ def _update_indexer(idxr: Index, indexer: Index) -> Index: # TODO: how to handle IntervalIndex level? # (no test cases) FutureWarning, - stacklevel=7, + stacklevel=find_stack_level(), ) continue else: diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 4d8c411478993..25b43c556b812 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -21,6 +21,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import astype_nansafe from pandas.core.dtypes.common import ( @@ -421,7 +422,7 @@ def asi8(self) -> npt.NDArray[np.int64]: warnings.warn( "Index.asi8 is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._values.view(self._default_dtype) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index fd5b5bb7396af..23851eff252b4 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -25,6 +25,7 @@ DtypeObj, ) from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_datetime64_any_dtype, @@ -346,7 +347,7 @@ def astype(self, dtype, copy: bool = True, how=lib.no_default): "will be removed in a future version. " "Use index.to_timestamp(how=how) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: how = "start" diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index aed7a7a467db3..fdb1ee754a7e6 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -29,6 +29,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_platform_int, @@ -256,7 +257,7 @@ def _start(self) -> int: warnings.warn( self._deprecation_message.format("_start", "start"), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.start @@ -279,7 +280,7 @@ def _stop(self) -> int: warnings.warn( self._deprecation_message.format("_stop", "stop"), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.stop @@ -303,7 +304,7 @@ def _step(self) -> int: warnings.warn( self._deprecation_message.format("_step", "step"), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.step @@ -456,7 +457,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 669274e034905..e773bf5ffb7f4 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -16,6 +16,7 @@ InvalidIndexError, ) from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_array_like, @@ -1381,7 +1382,7 @@ def _has_valid_setitem_indexer(self, indexer) -> bool: "a future version.\n" "consider using .loc with a DataFrame indexer for automatic alignment.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) if not isinstance(indexer, tuple): @@ -2298,7 +2299,7 @@ def convert_to_index_sliceable(obj: DataFrame, key): "and will be removed in a future version. Use `frame.loc[string]` " "instead.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return res except (KeyError, ValueError, NotImplementedError): diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index 6cbaae3fe12e0..75715bdc90003 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -44,12 +44,14 @@ def __getattr__(name: str): import warnings + from pandas.util._exceptions import find_stack_level + if name == "CategoricalBlock": warnings.warn( "CategoricalBlock is deprecated and will be removed in a future version. " "Use ExtensionBlock instead.", DeprecationWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) from pandas.core.internals.blocks import CategoricalBlock diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 543b2ea26f750..1cd9fe65407ba 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -365,7 +365,7 @@ def diff(self: T, n: int, axis: int) -> T: # with axis=0 is equivalent assert n == 0 axis = 0 - return self.apply(algos.diff, n=n, axis=axis, stacklevel=5) + return self.apply(algos.diff, n=n, axis=axis) def interpolate(self: T, **kwargs) -> T: return self.apply_with_block("interpolate", swap_axis=False, **kwargs) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2589015e0f0b1..aebabd7baaa68 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -190,7 +190,7 @@ def is_categorical(self) -> bool: "future version. Use isinstance(block.values, Categorical) " "instead. See https://github.com/pandas-dev/pandas/issues/40226", DeprecationWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return isinstance(self.values, Categorical) @@ -1122,7 +1122,7 @@ def take_nd( def diff(self, n: int, axis: int = 1) -> list[Block]: """return block for the diff of the values""" - new_values = algos.diff(self.values, n, axis=axis, stacklevel=7) + new_values = algos.diff(self.values, n, axis=axis) return [self.make_block(values=new_values)] def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Block]: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 159c20382dcfb..e6d6b561803d6 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -23,6 +23,7 @@ DtypeObj, Manager, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -830,7 +831,7 @@ def to_arrays( "To retain the old behavior, pass as a dictionary " "DataFrame({col: categorical, ..})", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) if columns is None: columns = default_index(len(data)) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 05a9aab4a5554..1a9989f312f3f 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1193,7 +1193,7 @@ def insert(self, loc: int, item: Hashable, value: ArrayLike) -> None: "Consider joining all columns at once using pd.concat(axis=1) " "instead. To get a de-fragmented frame, use `newframe = frame.copy()`", PerformanceWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) def _insert_update_mgr_locs(self, loc) -> None: @@ -1638,7 +1638,7 @@ def __init__( "The `fastpath` keyword is deprecated and will be removed " "in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) self.axes = [axis] diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index ece5b21fa2f8e..540a557f7c7cc 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -14,6 +14,7 @@ from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401 from pandas._typing import Level from pandas.util._decorators import Appender +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_array_like, @@ -300,7 +301,7 @@ def to_series(right): "Do `left, right = left.align(right, axis=1, copy=False)` " "before e.g. `left == right`", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) left, right = left.align( diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 1b217a592987f..7026e470df1c0 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -10,6 +10,7 @@ Appender, deprecate_kwarg, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_extension_array_dtype, @@ -58,7 +59,7 @@ def melt( "In the future this will raise an error, please set the 'value_name' " "parameter of DataFrame.melt to a unique name.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) if id_vars is not None: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index a88d1dce693f6..4dd15dd367581 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -35,6 +35,7 @@ Appender, Substitution, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import find_common_type from pandas.core.dtypes.common import ( @@ -676,7 +677,7 @@ def __init__( ) # stacklevel chosen to be correct when this is reached via pd.merge # (and not DataFrame.join) - warnings.warn(msg, FutureWarning, stacklevel=3) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) self._validate_specification() @@ -2297,7 +2298,7 @@ def _items_overlap_with_suffix( "unexpected results. Provide 'suffixes' as a tuple instead. In the " "future a 'TypeError' will be raised.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) to_rename = left.intersection(right) @@ -2347,7 +2348,7 @@ def renamer(x, suffix): f"Passing 'suffixes' which cause duplicate columns {set(dups)} in the " f"result is deprecated and will raise a MergeError in a future version.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return llabels, rlabels diff --git a/pandas/core/series.py b/pandas/core/series.py index 7ee9a0bcdd9e1..413c39817c50b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -54,6 +54,7 @@ deprecate_nonkeyword_arguments, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.util._validators import ( validate_ascending, validate_bool_kwarg, @@ -360,7 +361,7 @@ def __init__( "of 'float64' in a future version. Specify a dtype explicitly " "to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # uncomment the line below when removing the FutureWarning # dtype = np.dtype(object) @@ -886,7 +887,7 @@ def take(self, indices, axis=0, is_copy=None, **kwargs) -> Series: "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) nv.validate_take((), kwargs) @@ -1078,7 +1079,7 @@ def __setitem__(self, key, value) -> None: "Series. Use `series.iloc[an_int] = val` to treat the " "key as positional.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # this is equivalent to self._values[key] = value self._mgr.setitem_inplace(key, value) @@ -1887,7 +1888,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: squeeze = False @@ -1949,7 +1950,7 @@ def count(self, level=None): "deprecated and will be removed in a future version. Use groupby " "instead. ser.count(level=1) should use ser.groupby(level=1).count().", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if not isinstance(self.index, MultiIndex): raise ValueError("Series.count level is only valid with a MultiIndex") @@ -5134,7 +5135,7 @@ def between(self, left, right, inclusive="both") -> Series: "Boolean inputs to the `inclusive` argument are deprecated in " "favour of `both` or `neither`.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if inclusive: inclusive = "both" diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 1e27febab2af9..f82e1aa5d188c 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -19,6 +19,7 @@ F, ) from pandas.util._decorators import Appender +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_object, @@ -238,7 +239,7 @@ def __iter__(self): warnings.warn( "Columnar iteration over characters will be deprecated in future releases.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) i = 0 g = self.get(i) @@ -1214,7 +1215,7 @@ def contains(self, pat, case=True, flags=0, na=None, regex=True): "This pattern has match groups. To actually get the " "groups, use str.extract.", UserWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) result = self._data.array._str_contains(pat, case, flags, na, regex) diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 669a39fcb3a74..67a6975c21fdd 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -39,6 +39,7 @@ ArrayLike, Timezone, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_object, @@ -1109,7 +1110,7 @@ def to_time(arg, format=None, infer_time_format=False, errors="raise"): "`to_time` has been moved, should be imported from pandas.core.tools.times. " "This alias will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) from pandas.core.tools.times import to_time diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index c17af442fe2cc..f5f681d9de797 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -640,7 +640,7 @@ def vol(self, bias: bool = False, *args, **kwargs): "Use std instead." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.std(bias, *args, **kwargs) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b04aab3755b91..f7799912937b7 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -167,7 +167,7 @@ def win_type(self): "win_type will no longer return 'freq' in a future version. " "Check the type of self.window instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return "freq" return self._win_type @@ -177,7 +177,7 @@ def is_datetimelike(self) -> bool: warnings.warn( "is_datetimelike is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._win_freq_i8 is not None @@ -185,7 +185,7 @@ def validate(self) -> None: warnings.warn( "validate is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._validate() @@ -1763,6 +1763,7 @@ def count(self): "Specify min_periods=0 instead." ), FutureWarning, + stacklevel=find_stack_level(), ) self.min_periods = 0 result = super().count() From 51561df0112edde77e8918589735bd7da1403650 Mon Sep 17 00:00:00 2001 From: Richard Shadrach Date: Mon, 8 Nov 2021 17:45:19 -0500 Subject: [PATCH 2/2] Reverts --- pandas/core/internals/array_manager.py | 2 +- pandas/core/internals/blocks.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 1cd9fe65407ba..543b2ea26f750 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -365,7 +365,7 @@ def diff(self: T, n: int, axis: int) -> T: # with axis=0 is equivalent assert n == 0 axis = 0 - return self.apply(algos.diff, n=n, axis=axis) + return self.apply(algos.diff, n=n, axis=axis, stacklevel=5) def interpolate(self: T, **kwargs) -> T: return self.apply_with_block("interpolate", swap_axis=False, **kwargs) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index aebabd7baaa68..aaa16675115ae 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1122,7 +1122,7 @@ def take_nd( def diff(self, n: int, axis: int = 1) -> list[Block]: """return block for the diff of the values""" - new_values = algos.diff(self.values, n, axis=axis) + new_values = algos.diff(self.values, n, axis=axis, stacklevel=7) return [self.make_block(values=new_values)] def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Block]: