title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
REF: simplify maybe_cast_to_datetime
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 51b9ed5fd22c7..30b807001c33c 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -726,7 +726,9 @@ def _try_cast( except (ValueError, TypeError) as err: if dtype is not None and raise_cast_failure: raise - elif "Cannot cast" in str(err): + elif "Cannot cast" in str(err) or "cannot be converted to timedelta64" in str( + err + ): # via _disallow_mismatched_datetimelike raise else: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e3616bc857140..64152dde9ac25 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -68,7 +68,6 @@ is_numeric_dtype, is_object_dtype, is_scalar, - is_sparse, is_string_dtype, is_timedelta64_dtype, is_unsigned_integer_dtype, @@ -1583,83 +1582,84 @@ def maybe_cast_to_datetime( We allow a list *only* when dtype is not None. """ from pandas.core.arrays.datetimes import sequence_to_datetimes - from pandas.core.arrays.timedeltas import sequence_to_td64ns + from pandas.core.arrays.timedeltas import TimedeltaArray if not is_list_like(value): raise TypeError("value must be listlike") + if is_timedelta64_dtype(dtype): + # TODO: _from_sequence would raise ValueError in cases where + # ensure_nanosecond_dtype raises TypeError + dtype = cast(np.dtype, dtype) + dtype = ensure_nanosecond_dtype(dtype) + res = TimedeltaArray._from_sequence(value, dtype=dtype) + return res + if dtype is not None: is_datetime64 = is_datetime64_dtype(dtype) is_datetime64tz = is_datetime64tz_dtype(dtype) - is_timedelta64 = is_timedelta64_dtype(dtype) vdtype = getattr(value, "dtype", None) - if is_datetime64 or is_datetime64tz or is_timedelta64: + if is_datetime64 or is_datetime64tz: dtype = ensure_nanosecond_dtype(dtype) - if not is_sparse(value): - value = np.array(value, copy=False) - - # we have an array of datetime or timedeltas & nulls - if value.size or not is_dtype_equal(value.dtype, dtype): - _disallow_mismatched_datetimelike(value, dtype) - - try: - if is_datetime64: - dta = sequence_to_datetimes(value, allow_object=False) - # GH 25843: Remove tz information since the dtype - # didn't specify one - - if dta.tz is not None: - warnings.warn( - "Data is timezone-aware. Converting " - "timezone-aware data to timezone-naive by " - "passing dtype='datetime64[ns]' to " - "DataFrame or Series is deprecated and will " - "raise in a future version. Use " - "`pd.Series(values).dt.tz_localize(None)` " - "instead.", - FutureWarning, - stacklevel=8, - ) - # equiv: dta.view(dtype) - # Note: NOT equivalent to dta.astype(dtype) - dta = dta.tz_localize(None) - - value = dta - elif is_datetime64tz: - dtype = cast(DatetimeTZDtype, dtype) - # The string check can be removed once issue #13712 - # is solved. String data that is passed with a - # datetime64tz is assumed to be naive which should - # be localized to the timezone. - is_dt_string = is_string_dtype(value.dtype) - dta = sequence_to_datetimes(value, allow_object=False) - if dta.tz is not None: - value = dta.astype(dtype, copy=False) - elif is_dt_string: - # Strings here are naive, so directly localize - # equiv: dta.astype(dtype) # though deprecated - - value = dta.tz_localize(dtype.tz) - else: - # Numeric values are UTC at this point, - # so localize and convert - # equiv: Series(dta).astype(dtype) # though deprecated - - value = dta.tz_localize("UTC").tz_convert(dtype.tz) - elif is_timedelta64: - # if successful, we get a ndarray[td64ns] - value, _ = sequence_to_td64ns(value) - except OutOfBoundsDatetime: - raise - except ValueError: - # TODO(GH#40048): only catch dateutil's ParserError - # once we can reliably import it in all supported versions - if is_timedelta64: - raise - pass + value = np.array(value, copy=False) + + # we have an array of datetime or timedeltas & nulls + if value.size or not is_dtype_equal(value.dtype, dtype): + _disallow_mismatched_datetimelike(value, dtype) + + try: + if is_datetime64: + dta = sequence_to_datetimes(value, allow_object=False) + # GH 25843: Remove tz information since the dtype + # didn't specify one + + if dta.tz is not None: + warnings.warn( + "Data is timezone-aware. Converting " + "timezone-aware data to timezone-naive by " + "passing dtype='datetime64[ns]' to " + "DataFrame or Series is deprecated and will " + "raise in a future version. Use " + "`pd.Series(values).dt.tz_localize(None)` " + "instead.", + FutureWarning, + stacklevel=8, + ) + # equiv: dta.view(dtype) + # Note: NOT equivalent to dta.astype(dtype) + dta = dta.tz_localize(None) + + value = dta + elif is_datetime64tz: + dtype = cast(DatetimeTZDtype, dtype) + # The string check can be removed once issue #13712 + # is solved. String data that is passed with a + # datetime64tz is assumed to be naive which should + # be localized to the timezone. + is_dt_string = is_string_dtype(value.dtype) + dta = sequence_to_datetimes(value, allow_object=False) + if dta.tz is not None: + value = dta.astype(dtype, copy=False) + elif is_dt_string: + # Strings here are naive, so directly localize + # equiv: dta.astype(dtype) # though deprecated + + value = dta.tz_localize(dtype.tz) + else: + # Numeric values are UTC at this point, + # so localize and convert + # equiv: Series(dta).astype(dtype) # though deprecated + + value = dta.tz_localize("UTC").tz_convert(dtype.tz) + except OutOfBoundsDatetime: + raise + except ValueError: + # TODO(GH#40048): only catch dateutil's ParserError + # once we can reliably import it in all supported versions + pass elif getattr(vdtype, "kind", None) in ["m", "M"]: # we are already datetimelike and want to coerce to non-datetimelike; diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index d271cf99b165c..d118a376b56ec 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2763,11 +2763,20 @@ def test_from_scalar_datetimelike_mismatched(self, constructor, cls, request): scalar = cls("NaT", "ns") dtype = {np.datetime64: "m8[ns]", np.timedelta64: "M8[ns]"}[cls] - with pytest.raises(TypeError, match="Cannot cast"): + msg = "Cannot cast" + if cls is np.datetime64: + msg = "|".join( + [ + r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]", + "Cannot cast", + ] + ) + + with pytest.raises(TypeError, match=msg): constructor(scalar, dtype=dtype) scalar = cls(4, "ns") - with pytest.raises(TypeError, match="Cannot cast"): + with pytest.raises(TypeError, match=msg): constructor(scalar, dtype=dtype) @pytest.mark.parametrize("cls", [datetime, np.datetime64])
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41624
2021-05-22T20:35:07Z
2021-05-25T13:23:32Z
2021-05-25T13:23:32Z
2021-05-25T14:00:27Z
REF: convert_dtypes return dtype objects
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e3616bc857140..867f3b313da08 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1386,7 +1386,7 @@ def convert_dtypes( convert_integer: bool = True, convert_boolean: bool = True, convert_floating: bool = True, -) -> Dtype: +) -> DtypeObj: """ Convert objects to best possible type, and optionally, to types supporting ``pd.NA``. @@ -1407,23 +1407,28 @@ def convert_dtypes( Returns ------- - str, np.dtype, or ExtensionDtype - dtype - new dtype + np.dtype, or ExtensionDtype """ - inferred_dtype: str | np.dtype | ExtensionDtype - # TODO: rule out str + inferred_dtype: str | DtypeObj if ( convert_string or convert_integer or convert_boolean or convert_floating ) and isinstance(input_array, np.ndarray): - inferred_dtype = lib.infer_dtype(input_array) - if not convert_string and is_string_dtype(inferred_dtype): + if is_object_dtype(input_array.dtype): + inferred_dtype = lib.infer_dtype(input_array) + else: inferred_dtype = input_array.dtype + if is_string_dtype(inferred_dtype): + if not convert_string: + inferred_dtype = input_array.dtype + else: + inferred_dtype = pandas_dtype("string") + return inferred_dtype + if convert_integer: - target_int_dtype = "Int64" + target_int_dtype = pandas_dtype("Int64") if is_integer_dtype(input_array.dtype): from pandas.core.arrays.integer import INT_STR_TO_DTYPE @@ -1431,14 +1436,13 @@ def convert_dtypes( inferred_dtype = INT_STR_TO_DTYPE.get( input_array.dtype.name, target_int_dtype ) - if not is_integer_dtype(input_array.dtype) and is_numeric_dtype( - input_array.dtype - ): - inferred_dtype = target_int_dtype - - else: - if is_integer_dtype(inferred_dtype): - inferred_dtype = input_array.dtype + elif is_numeric_dtype(input_array.dtype): + # TODO: de-dup with maybe_cast_to_integer_array? + arr = input_array[notna(input_array)] + if (arr.astype(int) == arr).all(): + inferred_dtype = target_int_dtype + else: + inferred_dtype = input_array.dtype if convert_floating: if not is_integer_dtype(input_array.dtype) and is_numeric_dtype( @@ -1446,32 +1450,33 @@ def convert_dtypes( ): from pandas.core.arrays.floating import FLOAT_STR_TO_DTYPE - inferred_float_dtype = FLOAT_STR_TO_DTYPE.get( - input_array.dtype.name, "Float64" + inferred_float_dtype: DtypeObj = FLOAT_STR_TO_DTYPE.get( + input_array.dtype.name, pandas_dtype("Float64") ) # if we could also convert to integer, check if all floats # are actually integers if convert_integer: + # TODO: de-dup with maybe_cast_to_integer_array? arr = input_array[notna(input_array)] if (arr.astype(int) == arr).all(): - inferred_dtype = "Int64" + inferred_dtype = pandas_dtype("Int64") else: inferred_dtype = inferred_float_dtype else: inferred_dtype = inferred_float_dtype - else: - if is_float_dtype(inferred_dtype): - inferred_dtype = input_array.dtype if convert_boolean: if is_bool_dtype(input_array.dtype): - inferred_dtype = "boolean" - else: - if isinstance(inferred_dtype, str) and inferred_dtype == "boolean": - inferred_dtype = input_array.dtype + inferred_dtype = pandas_dtype("boolean") + elif isinstance(inferred_dtype, str) and inferred_dtype == "boolean": + inferred_dtype = pandas_dtype("boolean") + + if isinstance(inferred_dtype, str): + # If we couldn't do anything else, then we retain the dtype + inferred_dtype = input_array.dtype else: - inferred_dtype = input_array.dtype + return input_array.dtype return inferred_dtype diff --git a/pandas/core/series.py b/pandas/core/series.py index d8b7876028839..4eba0db7e98ec 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5065,10 +5065,7 @@ def _convert_dtypes( convert_boolean, convert_floating, ) - try: - result = input_series.astype(inferred_dtype) - except TypeError: - result = input_series.copy() + result = input_series.astype(inferred_dtype) else: result = input_series.copy() return result
This turns out to be a blocker for sharing arrays.integers.safe_cast with maybe_cast_to_integer_array, which in turn is a blocker for #34460
https://api.github.com/repos/pandas-dev/pandas/pulls/41622
2021-05-22T19:19:05Z
2021-05-24T18:18:31Z
2021-05-24T18:18:31Z
2021-05-24T18:30:47Z
TYP: NaTType comparisons
diff --git a/pandas/_libs/tslibs/nattype.pyi b/pandas/_libs/tslibs/nattype.pyi index 0f81dcb4b2df1..5a2985d0e815b 100644 --- a/pandas/_libs/tslibs/nattype.pyi +++ b/pandas/_libs/tslibs/nattype.pyi @@ -1,8 +1,14 @@ -from datetime import datetime +from datetime import ( + datetime, + timedelta, +) +from typing import Any import numpy as np +from pandas._libs.tslibs.period import Period + NaT: NaTType iNaT: int nat_strings: set[str] @@ -133,3 +139,31 @@ class NaTType(datetime): # inject Period properties @property def qyear(self) -> float: ... + + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + # https://github.com/python/mypy/issues/9015 + # error: Argument 1 of "__lt__" is incompatible with supertype "date"; + # supertype defines the argument type as "date" + def __lt__( # type: ignore[override] + self, + other: datetime | timedelta | Period | np.datetime64 | np.timedelta64 + ) -> bool: ... + # error: Argument 1 of "__le__" is incompatible with supertype "date"; + # supertype defines the argument type as "date" + def __le__( # type: ignore[override] + self, + other: datetime | timedelta | Period | np.datetime64 | np.timedelta64 + ) -> bool: ... + # error: Argument 1 of "__gt__" is incompatible with supertype "date"; + # supertype defines the argument type as "date" + def __gt__( # type: ignore[override] + self, + other: datetime | timedelta | Period | np.datetime64 | np.timedelta64 + ) -> bool: ... + # error: Argument 1 of "__ge__" is incompatible with supertype "date"; + # supertype defines the argument type as "date" + def __ge__( # type: ignore[override] + self, + other: datetime | timedelta | Period | np.datetime64 | np.timedelta64 + ) -> bool: ...
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41621
2021-05-22T18:26:48Z
2021-05-24T08:59:54Z
2021-05-24T08:59:54Z
2021-05-24T15:16:11Z
TYP: __future__ annotations in parsers
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index df2bfa7d2a870..02084f91d9966 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from collections import defaultdict import csv import datetime @@ -6,14 +8,8 @@ Any, Callable, DefaultDict, - Dict, Iterable, - List, - Optional, Sequence, - Set, - Tuple, - Union, cast, ) import warnings @@ -122,12 +118,12 @@ class ParserBase: def __init__(self, kwds): self.names = kwds.get("names") - self.orig_names: Optional[List] = None + self.orig_names: list | None = None self.prefix = kwds.pop("prefix", None) self.index_col = kwds.get("index_col", None) - self.unnamed_cols: Set = set() - self.index_names: Optional[List] = None + self.unnamed_cols: set = set() + self.index_names: list | None = None self.col_names = None self.parse_dates = _validate_parse_dates_arg(kwds.pop("parse_dates", False)) @@ -205,9 +201,9 @@ def __init__(self, kwds): self.usecols, self.usecols_dtype = self._validate_usecols_arg(kwds["usecols"]) - self.handles: Optional[IOHandles] = None + self.handles: IOHandles | None = None - def _open_handles(self, src: FilePathOrBuffer, kwds: Dict[str, Any]) -> None: + def _open_handles(self, src: FilePathOrBuffer, kwds: dict[str, Any]) -> None: """ Let the readers open IOHanldes after they are done with their potential raises. """ @@ -221,7 +217,7 @@ def _open_handles(self, src: FilePathOrBuffer, kwds: Dict[str, Any]) -> None: errors=kwds.get("encoding_errors", "strict"), ) - def _validate_parse_dates_presence(self, columns: List[str]) -> None: + def _validate_parse_dates_presence(self, columns: list[str]) -> None: """ Check if parse_dates are in columns. @@ -371,7 +367,7 @@ def _maybe_dedup_names(self, names): # would be nice! if self.mangle_dupe_cols: names = list(names) # so we can index - counts: DefaultDict[Union[int, str, Tuple], int] = defaultdict(int) + counts: DefaultDict[int | str | tuple, int] = defaultdict(int) is_potential_mi = _is_potential_multi_index(names, self.index_col) for i, col in enumerate(names): @@ -596,8 +592,8 @@ def _convert_to_ndarrays( @final def _set_noconvert_dtype_columns( - self, col_indices: List[int], names: List[Union[int, str, Tuple]] - ) -> Set[int]: + self, col_indices: list[int], names: list[int | str | tuple] + ) -> set[int]: """ Set the columns that should not undergo dtype conversions. @@ -615,7 +611,7 @@ def _set_noconvert_dtype_columns( ------- A set of integers containing the positions of the columns not to convert. """ - usecols: Optional[Union[List[int], List[str]]] + usecols: list[int] | list[str] | None noconvert_columns = set() if self.usecols_dtype == "integer": # A set of integers will be converted to a list in @@ -900,7 +896,7 @@ def _clean_index_names(self, columns, index_col, unnamed_cols): return [None] * len(index_col), columns, index_col cp_cols = list(columns) - index_names: List[Optional[Union[int, str]]] = [] + index_names: list[str | int | None] = [] # don't mutate index_col = list(index_col) @@ -926,7 +922,7 @@ def _clean_index_names(self, columns, index_col, unnamed_cols): return index_names, columns, index_col def _get_empty_meta( - self, columns, index_col, index_names, dtype: Optional[DtypeArg] = None + self, columns, index_col, index_names, dtype: DtypeArg | None = None ): columns = list(columns) @@ -1150,7 +1146,7 @@ def _get_na_values(col, na_values, na_fvalues, keep_default_na): def _is_potential_multi_index( - columns, index_col: Optional[Union[bool, Sequence[int]]] = None + columns, index_col: bool | Sequence[int] | None = None ) -> bool: """ Check whether or not the `columns` parameter diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 9082e41698913..8f6d95f001d91 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from collections import ( abc, defaultdict, @@ -9,10 +11,6 @@ from typing import ( DefaultDict, Iterator, - List, - Optional, - Set, - Tuple, cast, ) import warnings @@ -44,14 +42,14 @@ class PythonParser(ParserBase): - def __init__(self, f: Union[FilePathOrBuffer, List], **kwds): + def __init__(self, f: Union[FilePathOrBuffer, list], **kwds): """ Workhorse function for processing nested list into DataFrame """ ParserBase.__init__(self, kwds) - self.data: Optional[Iterator[str]] = None - self.buf: List = [] + self.data: Iterator[str] | None = None + self.buf: list = [] self.pos = 0 self.line_pos = 0 @@ -110,7 +108,7 @@ def __init__(self, f: Union[FilePathOrBuffer, List], **kwds): # Get columns in two steps: infer from data, then # infer column indices from self.usecols if it is specified. - self._col_indices: Optional[List[int]] = None + self._col_indices: list[int] | None = None try: ( self.columns, @@ -143,7 +141,7 @@ def __init__(self, f: Union[FilePathOrBuffer, List], **kwds): self.columns = self.columns[0] # get popped off for index - self.orig_names: List[Union[int, str, Tuple]] = list(self.columns) + self.orig_names: list[int | str | tuple] = list(self.columns) # needs to be cleaned/refactored # multiple date column thing turning into a real spaghetti factory @@ -160,7 +158,7 @@ def __init__(self, f: Union[FilePathOrBuffer, List], **kwds): self._col_indices = list(range(len(self.columns))) self._validate_parse_dates_presence(self.columns) - no_thousands_columns: Optional[Set[int]] = None + no_thousands_columns: set[int] | None = None if self.parse_dates: no_thousands_columns = self._set_noconvert_dtype_columns( self._col_indices, self.columns @@ -360,7 +358,7 @@ def _infer_columns(self): names = self.names num_original_columns = 0 clear_buffer = True - unnamed_cols: Set[Optional[Union[int, str]]] = set() + unnamed_cols: set[str | int | None] = set() if self.header is not None: header = self.header @@ -374,7 +372,7 @@ def _infer_columns(self): have_mi_columns = False header = [header] - columns: List[List[Optional[Union[int, str]]]] = [] + columns: list[list[int | str | None]] = [] for level, hr in enumerate(header): try: line = self._buffered_line() @@ -403,7 +401,7 @@ def _infer_columns(self): line = self.names[:] - this_columns: List[Optional[Union[int, str]]] = [] + this_columns: list[int | str | None] = [] this_unnamed_cols = [] for i, c in enumerate(line): @@ -531,8 +529,8 @@ def _infer_columns(self): def _handle_usecols( self, - columns: List[List[Union[Optional[str], Optional[int]]]], - usecols_key: List[Union[Optional[str], Optional[int]]], + columns: list[list[str | int | None]], + usecols_key: list[str | int | None], num_original_columns: int, ): """ @@ -1209,7 +1207,7 @@ def _make_reader(self, f): self.infer_nrows, ) - def _remove_empty_lines(self, lines) -> List: + def _remove_empty_lines(self, lines) -> list: """ Returns the list of lines without the empty ones. With fixed-width fields, empty lines become arrays of empty strings.
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41620
2021-05-22T18:24:03Z
2021-05-23T08:49:24Z
2021-05-23T08:49:24Z
2021-05-23T17:13:03Z
REF: type change `escape` in `Styler.format` to str to allow "html" and "latex"
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb index 219b74407fae4..7d8d8e90dfbda 100644 --- a/doc/source/user_guide/style.ipynb +++ b/doc/source/user_guide/style.ipynb @@ -1462,7 +1462,7 @@ "metadata": {}, "outputs": [], "source": [ - "df4.style.format(escape=True)" + "df4.style.format(escape=\"html\")" ] }, { @@ -1471,7 +1471,7 @@ "metadata": {}, "outputs": [], "source": [ - "df4.style.format('<a href=\"https://pandas.pydata.org\" target=\"_blank\">{}</a>', escape=True)" + "df4.style.format('<a href=\"https://pandas.pydata.org\" target=\"_blank\">{}</a>', escape=\"html\")" ] }, { diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 5a9b5e3c81e84..73924631aea5c 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -74,7 +74,7 @@ def _mpl(func: Callable): class Styler(StylerRenderer): - """ + r""" Helps style a DataFrame or Series according to the data with HTML and CSS. Parameters @@ -119,9 +119,12 @@ class Styler(StylerRenderer): .. versionadded:: 1.3.0 - escape : bool, default False - Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in cell display - strings with HTML-safe sequences. + escape : str, optional + Use 'html' to replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` + in cell display string with HTML-safe sequences. + Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, + ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with + LaTeX-safe sequences. ... versionadded:: 1.3.0 @@ -179,7 +182,7 @@ def __init__( uuid_len: int = 5, decimal: str = ".", thousands: str | None = None, - escape: bool = False, + escape: str | None = None, ): super().__init__( data=data, diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index ce328f00cf794..41733b77cbbd3 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -457,9 +457,9 @@ def format( precision: int | None = None, decimal: str = ".", thousands: str | None = None, - escape: bool = False, + escape: str | None = None, ) -> StylerRenderer: - """ + r""" Format the text display value of cells. Parameters @@ -492,9 +492,13 @@ def format( .. versionadded:: 1.3.0 - escape : bool, default False - Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in cell display - string with HTML-safe sequences. Escaping is done before ``formatter``. + escape : str, optional + Use 'html' to replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` + in cell display string with HTML-safe sequences. + Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, + ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with + LaTeX-safe sequences. + Escaping is done before ``formatter``. .. versionadded:: 1.3.0 @@ -571,13 +575,26 @@ def format( Using a ``formatter`` with HTML ``escape`` and ``na_rep``. >>> df = pd.DataFrame([['<div></div>', '"A&B"', None]]) - >>> s = df.style.format('<a href="a.com/{0}">{0}</a>', escape=True, na_rep="NA") + >>> s = df.style.format( + ... '<a href="a.com/{0}">{0}</a>', escape="html", na_rep="NA" + ... ) >>> s.render() ... <td .. ><a href="a.com/&lt;div&gt;&lt;/div&gt;">&lt;div&gt;&lt;/div&gt;</a></td> <td .. ><a href="a.com/&#34;A&amp;B&#34;">&#34;A&amp;B&#34;</a></td> <td .. >NA</td> ... + + Using a ``formatter`` with LaTeX ``escape``. + + >>> df = pd.DataFrame([["123"], ["~ ^"], ["$%#"]]) + >>> s = df.style.format("\\textbf{{{}}}", escape="latex").to_latex() + \begin{tabular}{ll} + {} & {0} \\ + 0 & \textbf{123} \\ + 1 & \textbf{\textasciitilde \space \textasciicircum } \\ + 2 & \textbf{\$\%\#} \\ + \end{tabular} """ if all( ( @@ -587,7 +604,7 @@ def format( decimal == ".", thousands is None, na_rep is None, - escape is False, + escape is None, ) ): self._display_funcs.clear() @@ -771,10 +788,17 @@ def wrapper(x): return wrapper -def _str_escape_html(x): - """if escaping html: only use on str, else return input""" +def _str_escape(x, escape): + """if escaping: only use on str, else return input""" if isinstance(x, str): - return escape_html(x) + if escape == "html": + return escape_html(x) + elif escape == "latex": + return _escape_latex(x) + else: + raise ValueError( + f"`escape` only permitted in {{'html', 'latex'}}, got {escape}" + ) return x @@ -784,7 +808,7 @@ def _maybe_wrap_formatter( precision: int | None = None, decimal: str = ".", thousands: str | None = None, - escape: bool = False, + escape: str | None = None, ) -> Callable: """ Allows formatters to be expressed as str, callable or None, where None returns @@ -804,9 +828,9 @@ def _maybe_wrap_formatter( else: raise TypeError(f"'formatter' expected str or callable, got {type(formatter)}") - # Replace HTML chars if escaping - if escape: - func_1 = lambda x: func_0(_str_escape_html(x)) + # Replace chars if escaping + if escape is not None: + func_1 = lambda x: func_0(_str_escape(x, escape=escape)) else: func_1 = func_0 @@ -1187,3 +1211,38 @@ def _parse_latex_options_strip(value: str | int | float, arg: str) -> str: For example: 'red /* --wrap */ ' --> 'red' """ return str(value).replace(arg, "").replace("/*", "").replace("*/", "").strip() + + +def _escape_latex(s): + r""" + Replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, ``{``, ``}``, + ``~``, ``^``, and ``\`` in the string with LaTeX-safe sequences. + + Use this if you need to display text that might contain such characters in LaTeX. + + Parameters + ---------- + s : str + Input to be escaped + + Return + ------ + str : + Escaped string + """ + return ( + s.replace("\\", "ab2§=§8yz") # rare string for final conversion: avoid \\ clash + .replace("ab2§=§8yz ", "ab2§=§8yz\\space ") # since \backslash gobbles spaces + .replace("&", "\\&") + .replace("%", "\\%") + .replace("$", "\\$") + .replace("#", "\\#") + .replace("_", "\\_") + .replace("{", "\\{") + .replace("}", "\\}") + .replace("~ ", "~\\space ") # since \textasciitilde gobbles spaces + .replace("~", "\\textasciitilde ") + .replace("^ ", "^\\space ") # since \textasciicircum gobbles spaces + .replace("^", "\\textasciicircum ") + .replace("ab2§=§8yz", "\\textbackslash ") + ) diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py index 9db27689a53f5..77a547098036c 100644 --- a/pandas/tests/io/formats/style/test_format.py +++ b/pandas/tests/io/formats/style/test_format.py @@ -11,6 +11,7 @@ pytest.importorskip("jinja2") from pandas.io.formats.style import Styler +from pandas.io.formats.style_render import _str_escape @pytest.fixture @@ -106,22 +107,36 @@ def test_format_clear(styler): assert (0, 0) not in styler._display_funcs # formatter cleared to default -def test_format_escape(): - df = DataFrame([['<>&"']]) - s = Styler(df, uuid_len=0).format("X&{0}>X", escape=False) - expected = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>' +@pytest.mark.parametrize( + "escape, exp", + [ + ("html", "&lt;&gt;&amp;&#34;%$#_{}~^\\~ ^ \\ "), + ( + "latex", + '<>\\&"\\%\\$\\#\\_\\{\\}\\textasciitilde \\textasciicircum ' + "\\textbackslash \\textasciitilde \\space \\textasciicircum \\space " + "\\textbackslash \\space ", + ), + ], +) +def test_format_escape_html(escape, exp): + chars = '<>&"%$#_{}~^\\~ ^ \\ ' + df = DataFrame([[chars]]) + + s = Styler(df, uuid_len=0).format("&{0}&", escape=None) + expected = f'<td id="T__row0_col0" class="data row0 col0" >&{chars}&</td>' assert expected in s.render() # only the value should be escaped before passing to the formatter - s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True) - ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>' - assert ex in s.render() + s = Styler(df, uuid_len=0).format("&{0}&", escape=escape) + expected = f'<td id="T__row0_col0" class="data row0 col0" >&{exp}&</td>' + assert expected in s.render() def test_format_escape_na_rep(): # tests the na_rep is not escaped df = DataFrame([['<>&"', None]]) - s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True, na_rep="&") + s = Styler(df, uuid_len=0).format("X&{0}>X", escape="html", na_rep="&") ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>' expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>' assert ex in s.render() @@ -130,11 +145,11 @@ def test_format_escape_na_rep(): def test_format_escape_floats(styler): # test given formatter for number format is not impacted by escape - s = styler.format("{:.1f}", escape=True) + s = styler.format("{:.1f}", escape="html") for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]: assert expected in s.render() # tests precision of floats is not impacted by escape - s = styler.format(precision=1, escape=True) + s = styler.format(precision=1, escape="html") for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]: assert expected in s.render() @@ -239,3 +254,14 @@ def test_format_decimal(formatter, thousands, precision): decimal="_", formatter=formatter, thousands=thousands, precision=precision )._translate(True, True) assert "000_123" in result["body"][0][1]["display_value"] + + +def test_str_escape_error(): + msg = "`escape` only permitted in {'html', 'latex'}, got " + with pytest.raises(ValueError, match=msg): + _str_escape("text", "bad_escape") + + with pytest.raises(ValueError, match=msg): + _str_escape("text", []) + + _str_escape(2.00, "bad_escape") # OK since dtype is float
Change is made ahead of 1.3.0 to pre-empt the addition of `escape_latex` and to avoid name ambiguity. This is not user facing since the `escape` kwarg was added for 1.3.0 only recently. **Alternative** If instead of having separate `escape_html` and `escape_latex` kwargs we could have `escape={None, 'html', 'latex'}` since it is likely they will be used exclusively??
https://api.github.com/repos/pandas-dev/pandas/pulls/41619
2021-05-22T17:36:03Z
2021-05-27T15:09:07Z
2021-05-27T15:09:07Z
2021-05-27T21:23:16Z
REF: _try_cast
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 51b9ed5fd22c7..c0759e90da980 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -39,6 +39,7 @@ maybe_cast_to_datetime, maybe_cast_to_integer_array, maybe_convert_platform, + maybe_infer_to_datetimelike, maybe_upcast, sanitize_to_nanoseconds, ) @@ -546,11 +547,12 @@ def sanitize_array( if dtype is not None or len(data) == 0: subarr = _try_cast(data, dtype, copy, raise_cast_failure) else: + # TODO: copy? subarr = maybe_convert_platform(data) - # error: Incompatible types in assignment (expression has type - # "Union[ExtensionArray, ndarray, List[Any]]", variable has type - # "ExtensionArray") - subarr = maybe_cast_to_datetime(subarr, dtype) # type: ignore[assignment] + if subarr.dtype == object: + # Argument 1 to "maybe_infer_to_datetimelike" has incompatible + # type "Union[ExtensionArray, ndarray]"; expected "ndarray" + subarr = maybe_infer_to_datetimelike(subarr) # type: ignore[arg-type] subarr = _sanitize_ndim(subarr, data, dtype, index) @@ -658,22 +660,29 @@ def _try_cast( """ is_ndarray = isinstance(arr, np.ndarray) - # perf shortcut as this is the most common case - # Item "List[Any]" of "Union[List[Any], ndarray]" has no attribute "dtype" - if ( - is_ndarray - and arr.dtype != object # type: ignore[union-attr] - and not copy - and dtype is None - ): - # Argument 1 to "sanitize_to_nanoseconds" has incompatible type - # "Union[List[Any], ndarray]"; expected "ndarray" - return sanitize_to_nanoseconds(arr) # type: ignore[arg-type] + if dtype is None: + # perf shortcut as this is the most common case + if is_ndarray: + arr = cast(np.ndarray, arr) + if arr.dtype != object: + return sanitize_to_nanoseconds(arr, copy=copy) + + out = maybe_infer_to_datetimelike(arr) + if out is arr and copy: + out = out.copy() + return out - if isinstance(dtype, ExtensionDtype): + else: + # i.e. list + varr = np.array(arr, copy=False) + # filter out cases that we _dont_ want to go through + # maybe_infer_to_datetimelike + if varr.dtype != object or varr.size == 0: + return varr + return maybe_infer_to_datetimelike(varr) + + elif isinstance(dtype, ExtensionDtype): # create an extension array from its dtype - # DatetimeTZ case needs to go through maybe_cast_to_datetime but - # SparseDtype does not if isinstance(dtype, DatetimeTZDtype): # We can't go through _from_sequence because it handles dt64naive # data differently; _from_sequence treats naive as wall times, @@ -695,22 +704,12 @@ def _try_cast( return subarr return ensure_wrapped_if_datetimelike(arr).astype(dtype, copy=copy) - elif dtype is None and not is_ndarray: - # filter out cases that we _dont_ want to go through maybe_cast_to_datetime - varr = np.array(arr, copy=False) - if varr.dtype != object or varr.size == 0: - return varr - # error: Incompatible return value type (got "Union[ExtensionArray, - # ndarray, List[Any]]", expected "Union[ExtensionArray, ndarray]") - return maybe_cast_to_datetime(varr, None) # type: ignore[return-value] - try: # GH#15832: Check if we are requesting a numeric dtype and # that we can convert the data to the requested dtype. if is_integer_dtype(dtype): # this will raise if we have e.g. floats - dtype = cast(np.dtype, dtype) maybe_cast_to_integer_array(arr, dtype) subarr = arr else: @@ -719,7 +718,11 @@ def _try_cast( return subarr if not isinstance(subarr, ABCExtensionArray): + # 4 tests fail if we move this to a try/except/else; see + # test_constructor_compound_dtypes, test_constructor_cast_failure + # test_constructor_dict_cast2, test_loc_setitem_dtype subarr = construct_1d_ndarray_preserving_na(subarr, dtype, copy=copy) + except OutOfBoundsDatetime: # in case of out of bound datetime64 -> always raise raise diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e3616bc857140..c23f8f423c3d8 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1687,7 +1687,7 @@ def maybe_cast_to_datetime( return value -def sanitize_to_nanoseconds(values: np.ndarray) -> np.ndarray: +def sanitize_to_nanoseconds(values: np.ndarray, copy: bool = False) -> np.ndarray: """ Safely convert non-nanosecond datetime64 or timedelta64 values to nanosecond. """ @@ -1698,6 +1698,9 @@ def sanitize_to_nanoseconds(values: np.ndarray) -> np.ndarray: elif dtype.kind == "m" and dtype != TD64NS_DTYPE: values = conversion.ensure_timedelta64ns(values) + elif copy: + values = values.copy() + return values
collect all the `dtype is None` cases together
https://api.github.com/repos/pandas-dev/pandas/pulls/41618
2021-05-22T15:37:02Z
2021-05-25T13:26:41Z
2021-05-25T13:26:41Z
2021-05-25T14:03:09Z
CLN: various related to numeric indexes
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index aaf58f1fcb150..40f23c25a1e99 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -30,9 +30,13 @@ from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, + is_float_dtype, + is_integer_dtype, is_period_dtype, is_sequence, is_timedelta64_dtype, + is_unsigned_integer_dtype, + pandas_dtype, ) import pandas as pd @@ -41,11 +45,14 @@ CategoricalIndex, DataFrame, DatetimeIndex, + Float64Index, Index, + Int64Index, IntervalIndex, MultiIndex, RangeIndex, Series, + UInt64Index, bdate_range, ) from pandas._testing._io import ( # noqa:F401 @@ -292,12 +299,32 @@ def makeBoolIndex(k=10, name=None): return Index([False, True] + [False] * (k - 2), name=name) +def makeNumericIndex(k=10, name=None, *, dtype): + dtype = pandas_dtype(dtype) + assert isinstance(dtype, np.dtype) + + if is_integer_dtype(dtype): + values = np.arange(k, dtype=dtype) + if is_unsigned_integer_dtype(dtype): + values += 2 ** (dtype.itemsize * 8 - 1) + elif is_float_dtype(dtype): + values = np.random.random_sample(k) - np.random.random_sample(1) + values.sort() + values = values * (10 ** np.random.randint(0, 9)) + else: + raise NotImplementedError(f"wrong dtype {dtype}") + + return Index(values, dtype=dtype, name=name) + + def makeIntIndex(k=10, name=None): - return Index(list(range(k)), name=name) + base_idx = makeNumericIndex(k, name=name, dtype="int64") + return Int64Index(base_idx) def makeUIntIndex(k=10, name=None): - return Index([2 ** 63 + i for i in range(k)], name=name) + base_idx = makeNumericIndex(k, name=name, dtype="uint64") + return UInt64Index(base_idx) def makeRangeIndex(k=10, name=None, **kwargs): @@ -305,8 +332,8 @@ def makeRangeIndex(k=10, name=None, **kwargs): def makeFloatIndex(k=10, name=None): - values = sorted(np.random.random_sample(k)) - np.random.random_sample(1) - return Index(values * (10 ** np.random.randint(0, 9)), name=name) + base_idx = makeNumericIndex(k, name=name, dtype="float64") + return Float64Index(base_idx) def makeDateIndex(k: int = 10, freq="B", name=None, **kwargs) -> DatetimeIndex: diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 2d695458e32e6..96d010b487a79 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -308,7 +308,7 @@ def assert_index_equal( """ __tracebackhide__ = True - def _check_types(left, right, obj="Index"): + def _check_types(left, right, obj="Index") -> None: if not exact: return diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index e6526bd0eaf2f..ea2d5d9eec6ac 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -106,20 +106,22 @@ def _can_hold_na(self) -> bool: else: return False - @cache_readonly + _engine_types: dict[np.dtype, type[libindex.IndexEngine]] = { + np.dtype(np.int8): libindex.Int8Engine, + np.dtype(np.int16): libindex.Int16Engine, + np.dtype(np.int32): libindex.Int32Engine, + np.dtype(np.int64): libindex.Int64Engine, + np.dtype(np.uint8): libindex.UInt8Engine, + np.dtype(np.uint16): libindex.UInt16Engine, + np.dtype(np.uint32): libindex.UInt32Engine, + np.dtype(np.uint64): libindex.UInt64Engine, + np.dtype(np.float32): libindex.Float32Engine, + np.dtype(np.float64): libindex.Float64Engine, + } + + @property def _engine_type(self): - return { - np.int8: libindex.Int8Engine, - np.int16: libindex.Int16Engine, - np.int32: libindex.Int32Engine, - np.int64: libindex.Int64Engine, - np.uint8: libindex.UInt8Engine, - np.uint16: libindex.UInt16Engine, - np.uint32: libindex.UInt32Engine, - np.uint64: libindex.UInt64Engine, - np.float32: libindex.Float32Engine, - np.float64: libindex.Float64Engine, - }[self.dtype.type] + return self._engine_types[self.dtype] @cache_readonly def inferred_type(self) -> str: diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index c36552f59da71..8b7070e945439 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -214,7 +214,7 @@ def test_api(self): + self.funcs_to + self.private_modules ) - self.check(pd, checkthese, self.ignored) + self.check(namespace=pd, expected=checkthese, ignored=self.ignored) def test_depr(self): deprecated_list = ( diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py index 26e785a2796b1..cabe766a4e9eb 100644 --- a/pandas/tests/base/test_unique.py +++ b/pandas/tests/base/test_unique.py @@ -23,12 +23,12 @@ def test_unique(index_or_series_obj): if isinstance(obj, pd.MultiIndex): expected = pd.MultiIndex.from_tuples(unique_values) expected.names = obj.names - tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, expected, exact=True) elif isinstance(obj, pd.Index): expected = pd.Index(unique_values, dtype=obj.dtype) if is_datetime64tz_dtype(obj.dtype): expected = expected.normalize() - tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, expected, exact=True) else: expected = np.array(unique_values) tm.assert_numpy_array_equal(result, expected) @@ -67,7 +67,7 @@ def test_unique_null(null_obj, index_or_series_obj): if is_datetime64tz_dtype(obj.dtype): result = result.normalize() expected = expected.normalize() - tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, expected, exact=True) else: expected = np.array(unique_values, dtype=obj.dtype) tm.assert_numpy_array_equal(result, expected) @@ -118,7 +118,7 @@ def test_unique_bad_unicode(idx_or_series_w_bad_unicode): if isinstance(obj, pd.Index): expected = pd.Index(["\ud83d"], dtype=object) - tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, expected, exact=True) else: expected = np.array(["\ud83d"], dtype=object) tm.assert_numpy_array_equal(result, expected)
A few bits to make #41153 smaller. Also fixes an issue with the current implementation of NumericIndex._engine_type: The implementation currently uses `self.dtype.type`, which is a problem when we are given platform-specific dtypes, e.g. `np.intc`. For example: ```python >>> d1 = np.dtype(np.intc) >>> d1 dtype('int32') >>> d2 = np.dtype(np.int32) >>> d1 == d2 True >>> d1.type == d2.type False # a problem ``` So the _engine_type dict should use np.dtype(np.int64) etc., so avoid such problems.
https://api.github.com/repos/pandas-dev/pandas/pulls/41615
2021-05-22T11:22:03Z
2021-06-03T23:24:05Z
2021-06-03T23:24:05Z
2021-06-03T23:31:22Z
REGR: CategoricalIndex(None)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d357e4a633347..5e76310e5f514 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -652,6 +652,7 @@ Build Deprecations ~~~~~~~~~~~~ - Deprecated allowing scalars to be passed to the :class:`Categorical` constructor (:issue:`38433`) +- Deprecated constructing :class:`CategoricalIndex` without passing list-like data (:issue:`38944`) - Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`, :issue:`21311`, :issue:`22315`, :issue:`26974`) - Deprecated ``astype`` of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`) - Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth`, use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e835990eb8d89..ec3552cf751b9 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -222,6 +222,17 @@ def __new__( name = maybe_extract_name(name, data, cls) + if data is None: + # GH#38944 + warnings.warn( + "Constructing a CategoricalIndex without passing data is " + "deprecated and will raise in a future version. " + "Use CategoricalIndex([], ...) instead", + FutureWarning, + stacklevel=2, + ) + data = [] + if is_scalar(data): raise cls._scalar_data_error(data) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 40ab887d5bb5d..6a9f7c2a80922 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -38,6 +38,11 @@ def test_can_hold_identifiers(self): key = idx[0] assert idx._can_hold_identifiers_and_holds_name(key) is True + def test_pickle_compat_construction(self): + # Once the deprecation is enforced, we can use the parent class's test + with tm.assert_produces_warning(FutureWarning, match="without passing data"): + self._index_cls() + def test_insert(self, simple_index): ci = simple_index diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index 35620875d5a1a..98da8038401e7 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -11,10 +11,17 @@ class TestCategoricalIndexConstructors: + def test_construction_without_data_deprecated(self): + # Once the deprecation is enforced, we can add this case to + # test_construction_disallows_scalar + msg = "without passing data" + with tm.assert_produces_warning(FutureWarning, match=msg): + CategoricalIndex(categories=list("abcd"), ordered=False) + def test_construction_disallows_scalar(self): msg = "must be called with a collection of some kind" with pytest.raises(TypeError, match=msg): - CategoricalIndex(categories=list("abcd"), ordered=False) + CategoricalIndex(data=1, categories=list("abcd"), ordered=False) def test_construction(self): diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 8c4f25c5b20fc..0ea3abcaefcf2 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -47,11 +47,17 @@ def create_index(self) -> Index: def test_pickle_compat_construction(self): # need an object to create with - msg = ( - r"Index\(\.\.\.\) must be called with a collection of some " - r"kind, None was passed|" - r"__new__\(\) missing 1 required positional argument: 'data'|" - r"__new__\(\) takes at least 2 arguments \(1 given\)" + msg = "|".join( + [ + r"Index\(\.\.\.\) must be called with a collection of some " + r"kind, None was passed", + r"DatetimeIndex\(\) must be called with a collection of some " + r"kind, None was passed", + r"TimedeltaIndex\(\) must be called with a collection of some " + r"kind, None was passed", + r"__new__\(\) missing 1 required positional argument: 'data'", + r"__new__\(\) takes at least 2 arguments \(1 given\)", + ] ) with pytest.raises(TypeError, match=msg): self._index_cls() diff --git a/pandas/tests/indexes/datetimes/test_datetimelike.py b/pandas/tests/indexes/datetimes/test_datetimelike.py index 0a387fe3141e4..31ec8c497299e 100644 --- a/pandas/tests/indexes/datetimes/test_datetimelike.py +++ b/pandas/tests/indexes/datetimes/test_datetimelike.py @@ -32,9 +32,6 @@ def test_format(self, simple_index): def test_shift(self): pass # handled in test_ops - def test_pickle_compat_construction(self): - pass - def test_intersection(self): pass # handled in test_setops diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index b80e92b105dbd..83c82c18f3d1e 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -35,8 +35,9 @@ def simple_index(self) -> Index: def index(self, request): return request.param + @pytest.mark.xfail(reason="Goes through a generate_range path") def test_pickle_compat_construction(self): - pass + super().test_pickle_compat_construction() @pytest.mark.parametrize("freq", ["D", "M", "A"]) def test_pickle_round_trip(self, freq): diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 478697ed1a5be..33f0565c0b23b 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -42,9 +42,6 @@ def test_numeric_compat(self): def test_shift(self): pass # this is handled in test_arithmetic.py - def test_pickle_compat_construction(self): - pass - def test_pickle_after_set_freq(self): tdi = timedelta_range("1 day", periods=4, freq="s") tdi = tdi._with_freq(None)
- [x] closes #38944 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41612
2021-05-22T05:29:06Z
2021-05-25T08:14:34Z
2021-05-25T08:14:34Z
2021-05-25T14:19:12Z
REF: re-use sanitize_array in DataFrame._sanitize_columns
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index e83aa02f25ada..e18ba805be052 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -467,6 +467,8 @@ def sanitize_array( dtype: DtypeObj | None = None, copy: bool = False, raise_cast_failure: bool = True, + *, + allow_2d: bool = False, ) -> ArrayLike: """ Sanitize input data to an ndarray or ExtensionArray, copy if specified, @@ -479,6 +481,8 @@ def sanitize_array( dtype : np.dtype, ExtensionDtype, or None, default None copy : bool, default False raise_cast_failure : bool, default True + allow_2d : bool, default False + If False, raise if we have a 2D Arraylike. Returns ------- @@ -552,7 +556,7 @@ def sanitize_array( # "ExtensionArray") subarr = maybe_cast_to_datetime(subarr, dtype) # type: ignore[assignment] - subarr = _sanitize_ndim(subarr, data, dtype, index) + subarr = _sanitize_ndim(subarr, data, dtype, index, allow_2d=allow_2d) if not ( isinstance(subarr.dtype, ExtensionDtype) or isinstance(dtype, ExtensionDtype) @@ -570,7 +574,12 @@ def sanitize_array( def _sanitize_ndim( - result: ArrayLike, data, dtype: DtypeObj | None, index: Index | None + result: ArrayLike, + data, + dtype: DtypeObj | None, + index: Index | None, + *, + allow_2d: bool = False, ) -> ArrayLike: """ Ensure we have a 1-dimensional result array. @@ -584,6 +593,8 @@ def _sanitize_ndim( elif result.ndim > 1: if isinstance(data, np.ndarray): + if allow_2d: + return result raise ValueError("Data must be 1-dimensional") if is_object_dtype(dtype) and isinstance(dtype, ExtensionDtype): # i.e. PandasDtype("O") diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 18ee1ad9bcd96..99da79c2d643c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -94,7 +94,6 @@ infer_dtype_from_scalar, invalidate_string_dtypes, maybe_box_native, - maybe_convert_platform, maybe_downcast_to_dtype, validate_numeric_casting, ) @@ -4498,35 +4497,11 @@ def _sanitize_column(self, value) -> ArrayLike: # We should never get here with DataFrame value if isinstance(value, Series): - value = _reindex_for_setitem(value, self.index) + return _reindex_for_setitem(value, self.index) - elif isinstance(value, ExtensionArray): - # Explicitly copy here - value = value.copy() + if is_list_like(value): com.require_length_match(value, self.index) - - elif is_sequence(value): - com.require_length_match(value, self.index) - - # turn me into an ndarray - if not isinstance(value, (np.ndarray, Index)): - if isinstance(value, list) and len(value) > 0: - value = maybe_convert_platform(value) - else: - value = com.asarray_tuplesafe(value) - elif isinstance(value, Index): - value = value.copy(deep=True)._values - else: - value = value.copy() - - # possibly infer to datetimelike - if is_object_dtype(value.dtype): - value = sanitize_array(value, None) - - else: - value = construct_1d_arraylike_from_scalar(value, len(self), dtype=None) - - return value + return sanitize_array(value, self.index, copy=True, allow_2d=True) @property def _series(self): diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 35e5abe9ce4e7..a680ae5cd695c 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -55,6 +55,25 @@ def _can_hold_element_patched(obj, element) -> bool: return can_hold_element(obj, element) +orig_assert_attr_equal = tm.assert_attr_equal + + +def _assert_attr_equal(attr: str, left, right, obj: str = "Attributes"): + """ + patch tm.assert_attr_equal so PandasDtype("object") is closed enough to + np.dtype("object") + """ + if attr == "dtype": + lattr = getattr(left, "dtype", None) + rattr = getattr(right, "dtype", None) + if isinstance(lattr, PandasDtype) and not isinstance(rattr, PandasDtype): + left = left.astype(lattr.numpy_dtype) + elif isinstance(rattr, PandasDtype) and not isinstance(lattr, PandasDtype): + right = right.astype(rattr.numpy_dtype) + + orig_assert_attr_equal(attr, left, right, obj) + + @pytest.fixture(params=["float", "object"]) def dtype(request): return PandasDtype(np.dtype(request.param)) @@ -81,6 +100,7 @@ def allow_in_pandas(monkeypatch): m.setattr(PandasArray, "_typ", "extension") m.setattr(managers, "_extract_array", _extract_array_patched) m.setattr(blocks, "can_hold_element", _can_hold_element_patched) + m.setattr(tm.asserters, "assert_attr_equal", _assert_attr_equal) yield diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index dd26a978fe81d..693e67652c912 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -386,58 +386,51 @@ def test_partial_set_empty_frame(self): with pytest.raises(ValueError, match=msg): df.loc[:, 1] = 1 + def test_partial_set_empty_frame2(self): # these work as they don't really change # anything but the index # GH5632 expected = DataFrame(columns=["foo"], index=Index([], dtype="object")) - def f(): - df = DataFrame(index=Index([], dtype="object")) - df["foo"] = Series([], dtype="object") - return df + df = DataFrame(index=Index([], dtype="object")) + df["foo"] = Series([], dtype="object") - tm.assert_frame_equal(f(), expected) + tm.assert_frame_equal(df, expected) - def f(): - df = DataFrame() - df["foo"] = Series(df.index) - return df + df = DataFrame() + df["foo"] = Series(df.index) - tm.assert_frame_equal(f(), expected) + tm.assert_frame_equal(df, expected) - def f(): - df = DataFrame() - df["foo"] = df.index - return df + df = DataFrame() + df["foo"] = df.index - tm.assert_frame_equal(f(), expected) + tm.assert_frame_equal(df, expected) + def test_partial_set_empty_frame3(self): expected = DataFrame(columns=["foo"], index=Index([], dtype="int64")) expected["foo"] = expected["foo"].astype("float64") - def f(): - df = DataFrame(index=Index([], dtype="int64")) - df["foo"] = [] - return df + df = DataFrame(index=Index([], dtype="int64")) + df["foo"] = [] - tm.assert_frame_equal(f(), expected) + tm.assert_frame_equal(df, expected) - def f(): - df = DataFrame(index=Index([], dtype="int64")) - df["foo"] = Series(np.arange(len(df)), dtype="float64") - return df + df = DataFrame(index=Index([], dtype="int64")) + df["foo"] = Series(np.arange(len(df)), dtype="float64") - tm.assert_frame_equal(f(), expected) + tm.assert_frame_equal(df, expected) - def f(): - df = DataFrame(index=Index([], dtype="int64")) - df["foo"] = range(len(df)) - return df + def test_partial_set_empty_frame4(self): + df = DataFrame(index=Index([], dtype="int64")) + df["foo"] = range(len(df)) expected = DataFrame(columns=["foo"], index=Index([], dtype="int64")) - expected["foo"] = expected["foo"].astype("float64") - tm.assert_frame_equal(f(), expected) + # range is int-dtype-like, so we get int64 dtype + expected["foo"] = expected["foo"].astype("int64") + tm.assert_frame_equal(df, expected) + def test_partial_set_empty_frame5(self): df = DataFrame() tm.assert_index_equal(df.columns, Index([], dtype=object)) df2 = DataFrame() @@ -446,6 +439,7 @@ def f(): tm.assert_frame_equal(df, DataFrame([[1]], index=["foo"], columns=[1])) tm.assert_frame_equal(df, df2) + def test_partial_set_empty_frame_no_index(self): # no index to start expected = DataFrame({0: Series(1, index=range(4))}, columns=["A", "B", 0])
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry A big partial-indexing test is split and has a non-trivial diff, but the only _actual_ change is this line https://github.com/pandas-dev/pandas/compare/master...jbrockmendel:ref-sanitize_column?expand=1#diff-1723bf927d192314f9d8c4faa220e26b1c3b39c2fe3bb65d8c43966ec7e596e8R430 declaring that empty range is int-dtype-like instead of float-dtype-like, which i think we should call a bug.
https://api.github.com/repos/pandas-dev/pandas/pulls/41611
2021-05-22T04:07:38Z
2021-05-26T01:49:26Z
2021-05-26T01:49:26Z
2021-05-26T04:24:30Z
BUG: pydatetime case followup to #41555
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 80d9a22a39b1e..53d196c78d988 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1915,13 +1915,19 @@ def maybe_unbox_datetimelike_tz_deprecation( along with a timezone-naive datetime64 dtype, which is deprecated. """ # Caller is responsible for checking dtype.kind in ["m", "M"] + + if isinstance(value, datetime): + # we dont want to box dt64, in particular datetime64("NaT") + value = maybe_box_datetimelike(value, dtype) + try: value = maybe_unbox_datetimelike(value, dtype) except TypeError: if ( isinstance(value, Timestamp) - and value.tz is not None + and value.tzinfo is not None and isinstance(dtype, np.dtype) + and dtype.kind == "M" ): warnings.warn( "Data is timezone-aware. Converting " diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index eee322e33bc8d..cca8c9283d552 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2474,10 +2474,13 @@ def test_construction_preserves_tzaware_dtypes(self, tz): ) tm.assert_series_equal(result, expected) - def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): + @pytest.mark.parametrize("pydt", [True, False]) + def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture, pydt): # GH#25843, GH#41555, GH#33401 tz = tz_aware_fixture ts = Timestamp("2019", tz=tz) + if pydt: + ts = ts.to_pydatetime() ts_naive = Timestamp("2019") with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 41c0cbf58e438..8b1f268896240 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1535,10 +1535,13 @@ def test_constructor_tz_mixed_data(self): expected = Series(dt_list, dtype=object) tm.assert_series_equal(result, expected) - def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): + @pytest.mark.parametrize("pydt", [True, False]) + def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture, pydt): # GH#25843, GH#41555, GH#33401 tz = tz_aware_fixture ts = Timestamp("2019", tz=tz) + if pydt: + ts = ts.to_pydatetime() ts_naive = Timestamp("2019") with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
#41555 was merged before i got a chance to push these suggested edits
https://api.github.com/repos/pandas-dev/pandas/pulls/41609
2021-05-21T20:36:30Z
2021-05-22T01:23:37Z
2021-05-22T01:23:37Z
2021-05-22T01:25:58Z
TYP deprecate_nonkeyword_arguments
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index f4c360f476514..5d53ab0cc41be 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -261,7 +261,7 @@ def deprecate_nonkeyword_arguments( version: str | None, allowed_args: list[str] | None = None, stacklevel: int = 2, -) -> Callable: +) -> Callable[[F], F]: """ Decorator to deprecate a use of non-keyword arguments of a function.
If we have ```python import pandas as pd reveal_type(pd.Series(range(3)).interpolate('linear')) ``` then on master we get: ```console $ mypy t.py t.py:3: note: Revealed type is 'Any' ``` while here ```console $ mypy t.py t.py:3: note: Revealed type is 'Union[pandas.core.series.Series, None]' ```
https://api.github.com/repos/pandas-dev/pandas/pulls/41608
2021-05-21T19:58:53Z
2021-05-22T00:24:57Z
2021-05-22T00:24:57Z
2021-05-22T08:51:42Z
TST: Old issues
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 7244624e563e3..32a499f6e9168 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -745,3 +745,15 @@ def test_where_bool_comparison(): } ) tm.assert_frame_equal(result, expected) + + +def test_where_none_nan_coerce(): + # GH 15613 + expected = DataFrame( + { + "A": [Timestamp("20130101"), pd.NaT, Timestamp("20130103")], + "B": [1, 2, np.nan], + } + ) + result = expected.where(expected.notnull(), None) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py index 3b2668aea001c..769b08373b890 100644 --- a/pandas/tests/frame/methods/test_to_csv.py +++ b/pandas/tests/frame/methods/test_to_csv.py @@ -1330,3 +1330,14 @@ def test_to_csv_numpy_16_bug(self): result = buf.getvalue() assert "2000-01-01" in result + + def test_to_csv_na_quoting(self): + # GH 15891 + # Normalize carriage return for Windows OS + result = ( + DataFrame([None, None]) + .to_csv(None, header=False, index=False, na_rep="") + .replace("\r\n", "\n") + ) + expected = '""\n""\n' + assert result == expected diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index c37dc17b85dd2..31acbb02518fb 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1657,7 +1657,7 @@ def test_index_label_overlaps_location(): expected = ser.take([1, 3, 4]) tm.assert_series_equal(actual, expected) - # ... and again, with a generic Index of floats + # and again, with a generic Index of floats df.index = df.index.astype(float) g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) @@ -2283,3 +2283,23 @@ def test_groupby_empty_multi_column(): [], columns=["C"], index=MultiIndex([[], []], [[], []], names=["A", "B"]) ) tm.assert_frame_equal(result, expected) + + +def test_groupby_filtered_df_std(): + # GH 16174 + dicts = [ + {"filter_col": False, "groupby_col": True, "bool_col": True, "float_col": 10.5}, + {"filter_col": True, "groupby_col": True, "bool_col": True, "float_col": 20.5}, + {"filter_col": True, "groupby_col": True, "bool_col": True, "float_col": 30.5}, + ] + df = DataFrame(dicts) + + df_filter = df[df["filter_col"] == True] # noqa:E712 + dfgb = df_filter.groupby("groupby_col") + result = dfgb.std() + expected = DataFrame( + [[0.0, 0.0, 7.071068]], + columns=["filter_col", "bool_col", "float_col"], + index=Index([True], name="groupby_col"), + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 0c6f2faf77f00..558270ac86532 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -801,3 +801,33 @@ def test_mi_partial_indexing_list_raises(): frame.columns.names = ["state", "color"] with pytest.raises(KeyError, match="\\[2\\] not in index"): frame.loc[["b", 2], "Colorado"] + + +def test_mi_indexing_list_nonexistent_raises(): + # GH 15452 + s = Series(range(4), index=MultiIndex.from_product([[1, 2], ["a", "b"]])) + with pytest.raises(KeyError, match="\\['not' 'found'\\] not in index"): + s.loc[["not", "found"]] + + +def test_mi_add_cell_missing_row_non_unique(): + # GH 16018 + result = DataFrame( + [[1, 2, 5, 6], [3, 4, 7, 8]], + index=["a", "a"], + columns=MultiIndex.from_product([[1, 2], ["A", "B"]]), + ) + result.loc["c"] = -1 + result.loc["c", (1, "A")] = 3 + result.loc["d", (1, "A")] = 3 + expected = DataFrame( + [ + [1.0, 2.0, 5.0, 6.0], + [3.0, 4.0, 7.0, 8.0], + [3.0, -1.0, -1, -1], + [3.0, np.nan, np.nan, np.nan], + ], + index=["a", "a", "c", "d"], + columns=MultiIndex.from_product([[1, 2], ["A", "B"]]), + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 48bc3e18d9883..b8e7b83c97ddb 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2684,3 +2684,14 @@ def test_loc_assign_dict_to_row(self, dtype): expected = DataFrame({"A": ["newA", "def"], "B": ["newB", "jkl"]}, dtype=dtype) tm.assert_frame_equal(df, expected) + + @td.skip_array_manager_invalid_test + def test_loc_setitem_dict_timedelta_multiple_set(self): + # GH 16309 + result = DataFrame(columns=["time", "value"]) + result.loc[1] = {"time": Timedelta(6, unit="s"), "value": "foo"} + result.loc[1] = {"time": Timedelta(6, unit="s"), "value": "foo"} + expected = DataFrame( + [[Timedelta(6, unit="s"), "foo"]], columns=["time", "value"], index=[1] + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index 2340d154e9e10..83e40aa5cb96b 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -437,6 +437,13 @@ def test_bounds_with_different_units(self): dt64 = np.datetime64(date_string, unit) Timestamp(dt64) + @pytest.mark.parametrize("arg", ["001-01-01", "0001-01-01"]) + def test_out_of_bounds_string_consistency(self, arg): + # GH 15829 + msg = "Out of bounds" + with pytest.raises(OutOfBoundsDatetime, match=msg): + Timestamp(arg) + def test_min_valid(self): # Ensure that Timestamp.min is a valid Timestamp Timestamp(Timestamp.min) diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py index e863fb45b1f81..eecb9492f29e3 100644 --- a/pandas/tests/tools/test_to_numeric.py +++ b/pandas/tests/tools/test_to_numeric.py @@ -780,3 +780,10 @@ def test_downcast_nullable_mask_is_copied(): arr[1] = pd.NA # should not modify result tm.assert_extension_array_equal(result, expected) + + +def test_to_numeric_scientific_notation(): + # GH 15898 + result = to_numeric("1.7e+308") + expected = np.float64(1.7e308) + assert result == expected
- [x] closes #15452 - [x] closes #15613 - [x] closes #15829 - [x] closes #15891 - [x] closes #15898 - [x] closes #16018 - [x] closes #16174 - [x] closes #16309 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/41607
2021-05-21T17:15:18Z
2021-05-24T18:55:31Z
2021-05-24T18:55:28Z
2021-05-24T19:30:17Z
BUG: case argument ignored when regex is False in Series.str.replace
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c6c4dadaf8c9d..b686bcf690e8f 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -782,6 +782,7 @@ Strings - Bug in the conversion from ``pyarrow.ChunkedArray`` to :class:`~arrays.StringArray` when the original had zero chunks (:issue:`41040`) - Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` ignoring replacements with ``regex=True`` for ``StringDType`` data (:issue:`41333`, :issue:`35977`) - Bug in :meth:`Series.str.extract` with :class:`~arrays.StringArray` returning object dtype for empty :class:`DataFrame` (:issue:`41441`) +- Bug in :meth:`Series.str.replace` where the ``case`` argument was ignored when ``regex=False`` (:issue:`41602`) Interval ^^^^^^^^ diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 8e6f4bfd3b320..ca0067b77ee23 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -1358,14 +1358,13 @@ def replace( "*not* be treated as literal strings when regex=True." ) warnings.warn(msg, FutureWarning, stacklevel=3) - regex = True # Check whether repl is valid (GH 13438, GH 15055) if not (isinstance(repl, str) or callable(repl)): raise TypeError("repl must be a string or callable") is_compiled_re = is_re(pat) - if regex: + if regex or regex is None: if is_compiled_re and (case is not None or flags != 0): raise ValueError( "case and flags cannot be set when pat is a compiled regex" @@ -1378,6 +1377,14 @@ def replace( elif callable(repl): raise ValueError("Cannot use a callable replacement when regex=False") + # The current behavior is to treat single character patterns as literal strings, + # even when ``regex`` is set to ``True``. + if isinstance(pat, str) and len(pat) == 1: + regex = False + + if regex is None: + regex = True + if case is None: case = True diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index fb9fd77d21732..c214ada9c1ada 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -145,10 +145,10 @@ def _str_replace( # add case flag, if provided flags |= re.IGNORECASE - if regex and ( - isinstance(pat, re.Pattern) or len(pat) > 1 or flags or callable(repl) - ): + if regex or flags or callable(repl): if not isinstance(pat, re.Pattern): + if regex is False: + pat = re.escape(pat) pat = re.compile(pat, flags=flags) n = n if n >= 0 else 0 diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py index 2104b50c5121a..391c71e57399a 100644 --- a/pandas/tests/strings/test_find_replace.py +++ b/pandas/tests/strings/test_find_replace.py @@ -555,6 +555,19 @@ def test_replace_moar(any_string_dtype): tm.assert_series_equal(result, expected) +def test_replace_not_case_sensitive_not_regex(any_string_dtype): + # https://github.com/pandas-dev/pandas/issues/41602 + ser = Series(["A.", "a.", "Ab", "ab", np.nan], dtype=any_string_dtype) + + result = ser.str.replace("a", "c", case=False, regex=False) + expected = Series(["c.", "c.", "cb", "cb", np.nan], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) + + result = ser.str.replace("a.", "c.", case=False, regex=False) + expected = Series(["c.", "c.", "Ab", "ab", np.nan], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) + + def test_replace_regex_default_warning(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/24809 s = Series(["a", "b", "ac", np.nan, ""], dtype=any_string_dtype)
- [ ] closes #41602 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41606
2021-05-21T16:01:19Z
2021-05-25T13:35:30Z
2021-05-25T13:35:29Z
2021-05-25T14:36:47Z
[ArrowStringArray] TYP: add annotations to str.replace
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index c2b2454c1b858..028b88cb0b1d8 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -1,12 +1,12 @@ from __future__ import annotations import codecs +from collections.abc import Callable # noqa: PDF001 from functools import wraps import re from typing import ( TYPE_CHECKING, Hashable, - Pattern, ) import warnings @@ -1217,7 +1217,15 @@ def fullmatch(self, pat, case=True, flags=0, na=None): return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) - def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): + def replace( + self, + pat: str | re.Pattern, + repl: str | Callable, + n: int = -1, + case: bool | None = None, + flags: int = 0, + regex: bool | None = None, + ): r""" Replace each occurrence of pattern/regex in the Series/Index. @@ -1358,14 +1366,10 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): is_compiled_re = is_re(pat) if regex: - if is_compiled_re: - if (case is not None) or (flags != 0): - raise ValueError( - "case and flags cannot be set when pat is a compiled regex" - ) - elif case is None: - # not a compiled regex, set default case - case = True + if is_compiled_re and (case is not None or flags != 0): + raise ValueError( + "case and flags cannot be set when pat is a compiled regex" + ) elif is_compiled_re: raise ValueError( @@ -1374,6 +1378,9 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): elif callable(repl): raise ValueError("Cannot use a callable replacement when regex=False") + if case is None: + case = True + result = self._data.array._str_replace( pat, repl, n=n, case=case, flags=flags, regex=regex ) @@ -3044,14 +3051,14 @@ def _result_dtype(arr): return object -def _get_single_group_name(regex: Pattern) -> Hashable: +def _get_single_group_name(regex: re.Pattern) -> Hashable: if regex.groupindex: return next(iter(regex.groupindex)) else: return None -def _get_group_names(regex: Pattern) -> list[Hashable]: +def _get_group_names(regex: re.Pattern) -> list[Hashable]: """ Get named groups from compiled regex. diff --git a/pandas/core/strings/base.py b/pandas/core/strings/base.py index add156efc0263..730870b448cb2 100644 --- a/pandas/core/strings/base.py +++ b/pandas/core/strings/base.py @@ -1,7 +1,8 @@ from __future__ import annotations import abc -from typing import Pattern +from collections.abc import Callable # noqa: PDF001 +import re import numpy as np @@ -51,7 +52,15 @@ def _str_endswith(self, pat, na=None): pass @abc.abstractmethod - def _str_replace(self, pat, repl, n=-1, case=None, flags=0, regex=True): + def _str_replace( + self, + pat: str | re.Pattern, + repl: str | Callable, + n: int = -1, + case: bool = True, + flags: int = 0, + regex: bool = True, + ): pass @abc.abstractmethod @@ -67,7 +76,7 @@ def _str_match( @abc.abstractmethod def _str_fullmatch( self, - pat: str | Pattern, + pat: str | re.Pattern, case: bool = True, flags: int = 0, na: Scalar = np.nan, diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 401e0217d5adf..fb9fd77d21732 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -1,8 +1,8 @@ from __future__ import annotations +from collections.abc import Callable # noqa: PDF001 import re import textwrap -from typing import Pattern import unicodedata import numpy as np @@ -15,10 +15,7 @@ Scalar, ) -from pandas.core.dtypes.common import ( - is_re, - is_scalar, -) +from pandas.core.dtypes.common import is_scalar from pandas.core.dtypes.missing import isna from pandas.core.strings.base import BaseStringArrayMethods @@ -135,15 +132,23 @@ def _str_endswith(self, pat, na=None): f = lambda x: x.endswith(pat) return self._str_map(f, na_value=na, dtype=np.dtype(bool)) - def _str_replace(self, pat, repl, n=-1, case: bool = True, flags=0, regex=True): - is_compiled_re = is_re(pat) - + def _str_replace( + self, + pat: str | re.Pattern, + repl: str | Callable, + n: int = -1, + case: bool = True, + flags: int = 0, + regex: bool = True, + ): if case is False: # add case flag, if provided flags |= re.IGNORECASE - if regex and (is_compiled_re or len(pat) > 1 or flags or callable(repl)): - if not is_compiled_re: + if regex and ( + isinstance(pat, re.Pattern) or len(pat) > 1 or flags or callable(repl) + ): + if not isinstance(pat, re.Pattern): pat = re.compile(pat, flags=flags) n = n if n >= 0 else 0 @@ -195,7 +200,7 @@ def _str_match( def _str_fullmatch( self, - pat: str | Pattern, + pat: str | re.Pattern, case: bool = True, flags: int = 0, na: Scalar = None,
pre-cursor to #41590
https://api.github.com/repos/pandas-dev/pandas/pulls/41603
2021-05-21T13:12:32Z
2021-05-21T15:11:15Z
2021-05-21T15:11:15Z
2021-05-21T15:19:32Z
[ArrowStringArray] TYP: use future annotations more
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 43df34a7ecbb2..c2b2454c1b858 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -1,14 +1,12 @@ +from __future__ import annotations + import codecs from functools import wraps import re from typing import ( TYPE_CHECKING, - Dict, Hashable, - List, - Optional, Pattern, - Union, ) import warnings @@ -43,7 +41,7 @@ if TYPE_CHECKING: from pandas import Index -_shared_docs: Dict[str, str] = {} +_shared_docs: dict[str, str] = {} _cpython_optimized_encoders = ( "utf-8", "utf8", @@ -325,7 +323,7 @@ def cons_row(x): else: index = self._orig.index # This is a mess. - dtype: Optional[str] + dtype: str | None if self._is_string and returns_string: dtype = self._orig.dtype else: @@ -391,7 +389,7 @@ def _get_series_list(self, others): or (isinstance(x, np.ndarray) and x.ndim == 1) for x in others ): - los: List[Series] = [] + los: list[Series] = [] while others: # iterate through list and append each element los = los + self._get_series_list(others.pop(0)) return los @@ -2292,7 +2290,7 @@ def findall(self, pat, flags=0): @forbid_nonstring_types(["bytes"]) def extract( self, pat: str, flags: int = 0, expand: bool = True - ) -> Union[FrameOrSeriesUnion, "Index"]: + ) -> FrameOrSeriesUnion | Index: r""" Extract capture groups in the regex `pat` as columns in a DataFrame. @@ -2733,7 +2731,7 @@ def len(self): # boolean: # isalpha, isnumeric isalnum isdigit isdecimal isspace islower isupper istitle # _doc_args holds dict of strings to use in substituting casemethod docs - _doc_args: Dict[str, Dict[str, str]] = {} + _doc_args: dict[str, dict[str, str]] = {} _doc_args["lower"] = {"type": "lowercase", "method": "lower", "version": ""} _doc_args["upper"] = {"type": "uppercase", "method": "upper", "version": ""} _doc_args["title"] = {"type": "titlecase", "method": "title", "version": ""} @@ -2971,7 +2969,7 @@ def casefold(self): ) -def cat_safe(list_of_columns: List, sep: str): +def cat_safe(list_of_columns: list, sep: str): """ Auxiliary function for :meth:`str.cat`. @@ -3007,7 +3005,7 @@ def cat_safe(list_of_columns: List, sep: str): return result -def cat_core(list_of_columns: List, sep: str): +def cat_core(list_of_columns: list, sep: str): """ Auxiliary function for :meth:`str.cat` @@ -3053,7 +3051,7 @@ def _get_single_group_name(regex: Pattern) -> Hashable: return None -def _get_group_names(regex: Pattern) -> List[Hashable]: +def _get_group_names(regex: Pattern) -> list[Hashable]: """ Get named groups from compiled regex. @@ -3119,7 +3117,7 @@ def str_extract(accessor: StringMethods, pat: str, flags: int = 0, expand: bool else: result_list = _str_extract(obj.array, pat, flags=flags, expand=returns_df) - result_index: Optional["Index"] + result_index: Index | None if isinstance(obj, ABCSeries): result_index = obj.index else: diff --git a/pandas/core/strings/base.py b/pandas/core/strings/base.py index a77f8861a7c02..add156efc0263 100644 --- a/pandas/core/strings/base.py +++ b/pandas/core/strings/base.py @@ -1,8 +1,7 @@ +from __future__ import annotations + import abc -from typing import ( - Pattern, - Union, -) +from typing import Pattern import numpy as np @@ -68,7 +67,7 @@ def _str_match( @abc.abstractmethod def _str_fullmatch( self, - pat: Union[str, Pattern], + pat: str | Pattern, case: bool = True, flags: int = 0, na: Scalar = np.nan, diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 869eabc76b555..401e0217d5adf 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -1,11 +1,8 @@ +from __future__ import annotations + import re import textwrap -from typing import ( - Optional, - Pattern, - Set, - Union, -) +from typing import Pattern import unicodedata import numpy as np @@ -38,7 +35,7 @@ def __len__(self): # For typing, _str_map relies on the object being sized. raise NotImplementedError - def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None): + def _str_map(self, f, na_value=None, dtype: Dtype | None = None): """ Map a callable over valid element of the array. @@ -198,7 +195,7 @@ def _str_match( def _str_fullmatch( self, - pat: Union[str, Pattern], + pat: str | Pattern, case: bool = True, flags: int = 0, na: Scalar = None, @@ -339,7 +336,7 @@ def _str_get_dummies(self, sep="|"): except TypeError: arr = sep + arr.astype(str) + sep - tags: Set[str] = set() + tags: set[str] = set() for ts in Series(arr).str.split(sep): tags.update(ts) tags2 = sorted(tags - {""})
pre-cursor to #41590
https://api.github.com/repos/pandas-dev/pandas/pulls/41601
2021-05-21T09:59:46Z
2021-05-21T12:29:59Z
2021-05-21T12:29:59Z
2021-05-21T12:30:22Z
[ArrowStringArray] TST/CLN: cleanup str.replace tests
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 43df34a7ecbb2..020291f1caf45 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -1348,7 +1348,7 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): ) if len(pat) == 1: msg += ( - " In addition, single character regular expressions will" + " In addition, single character regular expressions will " "*not* be treated as literal strings when regex=True." ) warnings.warn(msg, FutureWarning, stacklevel=3) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index b21a2c54ae615..c32d74c17a47e 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -449,14 +449,3 @@ def test_replace_with_compiled_regex(self): result = s.replace({regex: "z"}, regex=True) expected = pd.Series(["z", "b", "c"]) tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("pattern", ["^.$", "."]) - def test_str_replace_regex_default_raises_warning(self, pattern): - # https://github.com/pandas-dev/pandas/pull/24809 - s = pd.Series(["a", "b", "c"]) - msg = r"The default value of regex will change from True to False" - if len(pattern) == 1: - msg += r".*single character regular expressions.*not.*literal strings" - with tm.assert_produces_warning(FutureWarning) as w: - s.str.replace(pattern, "") - assert re.match(msg, str(w[0].message)) diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py index 0815d23f2b493..2104b50c5121a 100644 --- a/pandas/tests/strings/test_find_replace.py +++ b/pandas/tests/strings/test_find_replace.py @@ -10,6 +10,10 @@ _testing as tm, ) +# -------------------------------------------------------------------------------------- +# str.contains +# -------------------------------------------------------------------------------------- + def test_contains(any_string_dtype): values = np.array( @@ -148,6 +152,81 @@ def test_contains_na_kwarg_for_nullable_string_dtype( tm.assert_series_equal(result, expected) +def test_contains_moar(any_string_dtype): + # PR #1179 + s = Series( + ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"], + dtype=any_string_dtype, + ) + + result = s.str.contains("a") + expected_dtype = "object" if any_string_dtype == "object" else "boolean" + expected = Series( + [False, False, False, True, True, False, np.nan, False, False, True], + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + result = s.str.contains("a", case=False) + expected = Series( + [True, False, False, True, True, False, np.nan, True, False, True], + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + result = s.str.contains("Aa") + expected = Series( + [False, False, False, True, False, False, np.nan, False, False, False], + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + result = s.str.contains("ba") + expected = Series( + [False, False, False, True, False, False, np.nan, False, False, False], + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + result = s.str.contains("ba", case=False) + expected = Series( + [False, False, False, True, True, False, np.nan, True, False, False], + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + +def test_contains_nan(any_string_dtype): + # PR #14171 + s = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype) + + result = s.str.contains("foo", na=False) + expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean" + expected = Series([False, False, False], dtype=expected_dtype) + tm.assert_series_equal(result, expected) + + result = s.str.contains("foo", na=True) + expected = Series([True, True, True], dtype=expected_dtype) + tm.assert_series_equal(result, expected) + + result = s.str.contains("foo", na="foo") + if any_string_dtype == "object": + expected = Series(["foo", "foo", "foo"], dtype=np.object_) + else: + expected = Series([True, True, True], dtype="boolean") + tm.assert_series_equal(result, expected) + + result = s.str.contains("foo") + expected_dtype = "object" if any_string_dtype == "object" else "boolean" + expected = Series([np.nan, np.nan, np.nan], dtype=expected_dtype) + tm.assert_series_equal(result, expected) + + +# -------------------------------------------------------------------------------------- +# str.startswith +# -------------------------------------------------------------------------------------- + + @pytest.mark.parametrize("dtype", [None, "category"]) @pytest.mark.parametrize("null_value", [None, np.nan, pd.NA]) @pytest.mark.parametrize("na", [True, False]) @@ -195,6 +274,11 @@ def test_startswith_nullable_string_dtype(nullable_string_dtype, na): tm.assert_series_equal(result, exp) +# -------------------------------------------------------------------------------------- +# str.endswith +# -------------------------------------------------------------------------------------- + + @pytest.mark.parametrize("dtype", [None, "category"]) @pytest.mark.parametrize("null_value", [None, np.nan, pd.NA]) @pytest.mark.parametrize("na", [True, False]) @@ -242,39 +326,50 @@ def test_endswith_nullable_string_dtype(nullable_string_dtype, na): tm.assert_series_equal(result, exp) +# -------------------------------------------------------------------------------------- +# str.replace +# -------------------------------------------------------------------------------------- + + def test_replace(any_string_dtype): - values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) + ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) - result = values.str.replace("BAD[_]*", "", regex=True) + result = ser.str.replace("BAD[_]*", "", regex=True) expected = Series(["foobar", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) - result = values.str.replace("BAD[_]*", "", n=1, regex=True) + +def test_replace_max_replacements(any_string_dtype): + ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) + expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype) + result = ser.str.replace("BAD[_]*", "", n=1, regex=True) + tm.assert_series_equal(result, expected) + + expected = Series(["foo__barBAD", np.nan], dtype=any_string_dtype) + result = ser.str.replace("BAD", "", n=1, regex=False) tm.assert_series_equal(result, expected) def test_replace_mixed_object(): - mixed = Series( + ser = Series( ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0] ) - - result = Series(mixed).str.replace("BAD[_]*", "", regex=True) + result = Series(ser).str.replace("BAD[_]*", "", regex=True) expected = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan]) - assert isinstance(result, Series) - tm.assert_almost_equal(result, expected) + tm.assert_series_equal(result, expected) def test_replace_unicode(any_string_dtype): - values = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype) + ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype) expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype) - result = values.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True) + result = ser.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("repl", [None, 3, {"a": "b"}]) @pytest.mark.parametrize("data", [["a", "b", None], ["a", "b", "c", "ad"]]) -def test_replace_raises(any_string_dtype, index_or_series, repl, data): +def test_replace_wrong_repl_type_raises(any_string_dtype, index_or_series, repl, data): # https://github.com/pandas-dev/pandas/issues/13438 msg = "repl must be a string or callable" obj = index_or_series(data, dtype=any_string_dtype) @@ -284,11 +379,11 @@ def test_replace_raises(any_string_dtype, index_or_series, repl, data): def test_replace_callable(any_string_dtype): # GH 15055 - values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) + ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) # test with callable repl = lambda m: m.group(0).swapcase() - result = values.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True) + result = ser.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True) expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) @@ -311,100 +406,195 @@ def test_replace_callable_raises(any_string_dtype, repl): def test_replace_callable_named_groups(any_string_dtype): # test regex named groups - values = Series(["Foo Bar Baz", np.nan], dtype=any_string_dtype) + ser = Series(["Foo Bar Baz", np.nan], dtype=any_string_dtype) pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)" repl = lambda m: m.group("middle").swapcase() - result = values.str.replace(pat, repl, regex=True) + result = ser.str.replace(pat, repl, regex=True) expected = Series(["bAR", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) def test_replace_compiled_regex(any_string_dtype): # GH 15446 - values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) + ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) # test with compiled regex pat = re.compile(r"BAD_*") - result = values.str.replace(pat, "", regex=True) + result = ser.str.replace(pat, "", regex=True) expected = Series(["foobar", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) - result = values.str.replace(pat, "", n=1, regex=True) + result = ser.str.replace(pat, "", n=1, regex=True) expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) def test_replace_compiled_regex_mixed_object(): pat = re.compile(r"BAD_*") - mixed = Series( + ser = Series( ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0] ) - - result = Series(mixed).str.replace(pat, "", regex=True) + result = Series(ser).str.replace(pat, "", regex=True) expected = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan]) - assert isinstance(result, Series) - tm.assert_almost_equal(result, expected) + tm.assert_series_equal(result, expected) def test_replace_compiled_regex_unicode(any_string_dtype): - values = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype) + ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype) expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype) pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE) - result = values.str.replace(pat, ", ") + result = ser.str.replace(pat, ", ") tm.assert_series_equal(result, expected) def test_replace_compiled_regex_raises(any_string_dtype): # case and flags provided to str.replace will have no effect # and will produce warnings - values = Series(["fooBAD__barBAD__bad", np.nan], dtype=any_string_dtype) + ser = Series(["fooBAD__barBAD__bad", np.nan], dtype=any_string_dtype) pat = re.compile(r"BAD_*") msg = "case and flags cannot be set when pat is a compiled regex" with pytest.raises(ValueError, match=msg): - values.str.replace(pat, "", flags=re.IGNORECASE) + ser.str.replace(pat, "", flags=re.IGNORECASE) with pytest.raises(ValueError, match=msg): - values.str.replace(pat, "", case=False) + ser.str.replace(pat, "", case=False) with pytest.raises(ValueError, match=msg): - values.str.replace(pat, "", case=True) + ser.str.replace(pat, "", case=True) def test_replace_compiled_regex_callable(any_string_dtype): # test with callable - values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) + ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) repl = lambda m: m.group(0).swapcase() pat = re.compile("[a-z][A-Z]{2}") - result = values.str.replace(pat, repl, n=2) + result = ser.str.replace(pat, repl, n=2) expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) -def test_replace_literal(any_string_dtype): +@pytest.mark.parametrize( + "regex,expected", [(True, ["bao", "bao", np.nan]), (False, ["bao", "foo", np.nan])] +) +def test_replace_literal(regex, expected, any_string_dtype): # GH16808 literal replace (regex=False vs regex=True) - values = Series(["f.o", "foo", np.nan], dtype=any_string_dtype) - expected = Series(["bao", "bao", np.nan], dtype=any_string_dtype) - result = values.str.replace("f.", "ba", regex=True) + ser = Series(["f.o", "foo", np.nan], dtype=any_string_dtype) + expected = Series(expected, dtype=any_string_dtype) + result = ser.str.replace("f.", "ba", regex=regex) tm.assert_series_equal(result, expected) - expected = Series(["bao", "foo", np.nan], dtype=any_string_dtype) - result = values.str.replace("f.", "ba", regex=False) - tm.assert_series_equal(result, expected) - # Cannot do a literal replace if given a callable repl or compiled - # pattern - callable_repl = lambda m: m.group(0).swapcase() - compiled_pat = re.compile("[a-z][A-Z]{2}") +def test_replace_literal_callable_raises(any_string_dtype): + ser = Series([], dtype=any_string_dtype) + repl = lambda m: m.group(0).swapcase() msg = "Cannot use a callable replacement when regex=False" with pytest.raises(ValueError, match=msg): - values.str.replace("abc", callable_repl, regex=False) + ser.str.replace("abc", repl, regex=False) + + +def test_replace_literal_compiled_raises(any_string_dtype): + ser = Series([], dtype=any_string_dtype) + pat = re.compile("[a-z][A-Z]{2}") msg = "Cannot use a compiled regex as replacement pattern with regex=False" with pytest.raises(ValueError, match=msg): - values.str.replace(compiled_pat, "", regex=False) + ser.str.replace(pat, "", regex=False) + + +def test_replace_moar(any_string_dtype): + # PR #1179 + ser = Series( + ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"], + dtype=any_string_dtype, + ) + + result = ser.str.replace("A", "YYY") + expected = Series( + ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"], + dtype=any_string_dtype, + ) + tm.assert_series_equal(result, expected) + + result = ser.str.replace("A", "YYY", case=False) + expected = Series( + [ + "YYY", + "B", + "C", + "YYYYYYbYYY", + "BYYYcYYY", + "", + np.nan, + "CYYYBYYY", + "dog", + "cYYYt", + ], + dtype=any_string_dtype, + ) + tm.assert_series_equal(result, expected) + + result = ser.str.replace("^.a|dog", "XX-XX ", case=False, regex=True) + expected = Series( + [ + "A", + "B", + "C", + "XX-XX ba", + "XX-XX ca", + "", + np.nan, + "XX-XX BA", + "XX-XX ", + "XX-XX t", + ], + dtype=any_string_dtype, + ) + tm.assert_series_equal(result, expected) + + +def test_replace_regex_default_warning(any_string_dtype): + # https://github.com/pandas-dev/pandas/pull/24809 + s = Series(["a", "b", "ac", np.nan, ""], dtype=any_string_dtype) + msg = ( + "The default value of regex will change from True to False in a " + "future version\\.$" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.str.replace("^.$", "a") + expected = Series(["a", "a", "ac", np.nan, ""], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("regex", [True, False, None]) +def test_replace_regex_single_character(regex, any_string_dtype): + # https://github.com/pandas-dev/pandas/pull/24809 + + # The current behavior is to treat single character patterns as literal strings, + # even when ``regex`` is set to ``True``. + + s = Series(["a.b", ".", "b", np.nan, ""], dtype=any_string_dtype) + + if regex is None: + msg = re.escape( + "The default value of regex will change from True to False in a future " + "version. In addition, single character regular expressions will *not* " + "be treated as literal strings when regex=True." + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.str.replace(".", "a", regex=regex) + else: + result = s.str.replace(".", "a", regex=regex) + + expected = Series(["aab", "a", "b", np.nan, ""], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) + + +# -------------------------------------------------------------------------------------- +# str.match +# -------------------------------------------------------------------------------------- def test_match(any_string_dtype): @@ -484,6 +674,11 @@ def test_match_case_kwarg(any_string_dtype): tm.assert_series_equal(result, expected) +# -------------------------------------------------------------------------------------- +# str.fullmatch +# -------------------------------------------------------------------------------------- + + def test_fullmatch(any_string_dtype): # GH 32806 ser = Series( @@ -523,6 +718,11 @@ def test_fullmatch_case_kwarg(any_string_dtype): tm.assert_series_equal(result, expected) +# -------------------------------------------------------------------------------------- +# str.findall +# -------------------------------------------------------------------------------------- + + def test_findall(any_string_dtype): ser = Series(["fooBAD__barBAD", np.nan, "foo", "BAD"], dtype=any_string_dtype) result = ser.str.findall("BAD[_]*") @@ -563,6 +763,11 @@ def test_findall_mixed_object(): tm.assert_series_equal(result, expected) +# -------------------------------------------------------------------------------------- +# str.find +# -------------------------------------------------------------------------------------- + + def test_find(any_string_dtype): ser = Series( ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF", "XXXX"], dtype=any_string_dtype @@ -646,6 +851,11 @@ def test_find_nan(any_string_dtype): tm.assert_series_equal(result, expected) +# -------------------------------------------------------------------------------------- +# str.translate +# -------------------------------------------------------------------------------------- + + def test_translate(index_or_series, any_string_dtype): obj = index_or_series( ["abcdefg", "abcc", "cdddfg", "cdefggg"], dtype=any_string_dtype @@ -670,125 +880,7 @@ def test_translate_mixed_object(): tm.assert_series_equal(result, expected) -def test_contains_moar(any_string_dtype): - # PR #1179 - s = Series( - ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"], - dtype=any_string_dtype, - ) - - result = s.str.contains("a") - expected_dtype = "object" if any_string_dtype == "object" else "boolean" - expected = Series( - [False, False, False, True, True, False, np.nan, False, False, True], - dtype=expected_dtype, - ) - tm.assert_series_equal(result, expected) - - result = s.str.contains("a", case=False) - expected = Series( - [True, False, False, True, True, False, np.nan, True, False, True], - dtype=expected_dtype, - ) - tm.assert_series_equal(result, expected) - - result = s.str.contains("Aa") - expected = Series( - [False, False, False, True, False, False, np.nan, False, False, False], - dtype=expected_dtype, - ) - tm.assert_series_equal(result, expected) - - result = s.str.contains("ba") - expected = Series( - [False, False, False, True, False, False, np.nan, False, False, False], - dtype=expected_dtype, - ) - tm.assert_series_equal(result, expected) - - result = s.str.contains("ba", case=False) - expected = Series( - [False, False, False, True, True, False, np.nan, True, False, False], - dtype=expected_dtype, - ) - tm.assert_series_equal(result, expected) - - -def test_contains_nan(any_string_dtype): - # PR #14171 - s = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype) - - result = s.str.contains("foo", na=False) - expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean" - expected = Series([False, False, False], dtype=expected_dtype) - tm.assert_series_equal(result, expected) - - result = s.str.contains("foo", na=True) - expected = Series([True, True, True], dtype=expected_dtype) - tm.assert_series_equal(result, expected) - - result = s.str.contains("foo", na="foo") - if any_string_dtype == "object": - expected = Series(["foo", "foo", "foo"], dtype=np.object_) - else: - expected = Series([True, True, True], dtype="boolean") - tm.assert_series_equal(result, expected) - - result = s.str.contains("foo") - expected_dtype = "object" if any_string_dtype == "object" else "boolean" - expected = Series([np.nan, np.nan, np.nan], dtype=expected_dtype) - tm.assert_series_equal(result, expected) - - -def test_replace_moar(any_string_dtype): - # PR #1179 - s = Series( - ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"], - dtype=any_string_dtype, - ) - - result = s.str.replace("A", "YYY") - expected = Series( - ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"], - dtype=any_string_dtype, - ) - tm.assert_series_equal(result, expected) - - result = s.str.replace("A", "YYY", case=False) - expected = Series( - [ - "YYY", - "B", - "C", - "YYYYYYbYYY", - "BYYYcYYY", - "", - np.nan, - "CYYYBYYY", - "dog", - "cYYYt", - ], - dtype=any_string_dtype, - ) - tm.assert_series_equal(result, expected) - - result = s.str.replace("^.a|dog", "XX-XX ", case=False, regex=True) - expected = Series( - [ - "A", - "B", - "C", - "XX-XX ba", - "XX-XX ca", - "", - np.nan, - "XX-XX BA", - "XX-XX ", - "XX-XX t", - ], - dtype=any_string_dtype, - ) - tm.assert_series_equal(result, expected) +# -------------------------------------------------------------------------------------- def test_flags_kwarg(any_string_dtype):
pre-cursor to #41590
https://api.github.com/repos/pandas-dev/pandas/pulls/41600
2021-05-21T09:19:12Z
2021-05-21T15:31:34Z
2021-05-21T15:31:33Z
2021-05-21T15:43:00Z
BUG: DataFrame(ndarray[dt64], dtype=object)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c6c4dadaf8c9d..b3d9252acd3cb 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -775,6 +775,8 @@ Conversion - Bug in :func:`factorize` where, when given an array with a numeric numpy dtype lower than int64, uint64 and float64, the unique values did not keep their original dtype (:issue:`41132`) - Bug in :class:`DataFrame` construction with a dictionary containing an arraylike with ``ExtensionDtype`` and ``copy=True`` failing to make a copy (:issue:`38939`) - Bug in :meth:`qcut` raising error when taking ``Float64DType`` as input (:issue:`40730`) +- Bug in :class:`DataFrame` and :class:`Series` construction with ``datetime64[ns]`` data and ``dtype=object`` resulting in ``datetime`` objects instead of :class:`Timestamp` objects (:issue:`41599`) +- Bug in :class:`DataFrame` and :class:`Series` construction with ``timedelta64[ns]`` data and ``dtype=object`` resulting in ``np.timedelta64`` objects instead of :class:`Timedelta` objects (:issue:`41599`) Strings ^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index b4bdb2f9c4b53..cac41f88e08e0 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -31,7 +31,6 @@ Timedelta, Timestamp, conversion, - ints_to_pydatetime, ) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas._typing import ( @@ -1665,18 +1664,13 @@ def maybe_cast_to_datetime( raise pass - # coerce datetimelike to object - elif is_datetime64_dtype(vdtype) and not is_datetime64_dtype(dtype): - if is_object_dtype(dtype): - value = cast(np.ndarray, value) - - if value.dtype != DT64NS_DTYPE: - value = value.astype(DT64NS_DTYPE) - ints = np.asarray(value).view("i8") - return ints_to_pydatetime(ints) - - # we have a non-castable dtype that was passed - raise TypeError(f"Cannot cast datetime64 to {dtype}") + elif getattr(vdtype, "kind", None) in ["m", "M"]: + # we are already datetimelike and want to coerce to non-datetimelike; + # astype_nansafe will raise for anything other than object, then upcast. + # see test_datetimelike_values_with_object_dtype + # error: Argument 2 to "astype_nansafe" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "dtype[Any]" + return astype_nansafe(value, dtype) # type: ignore[arg-type] elif isinstance(value, np.ndarray): if value.dtype.kind in ["M", "m"]: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7162bda0eff43..6d7c803685255 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -267,7 +267,7 @@ def _init_mgr( if ( isinstance(mgr, BlockManager) and len(mgr.blocks) == 1 - and mgr.blocks[0].values.dtype == dtype + and is_dtype_equal(mgr.blocks[0].values.dtype, dtype) ): pass else: diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 94cb85a0945f2..e57f5ebf79b6f 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -24,6 +24,7 @@ from pandas.core.dtypes.dtypes import ( DatetimeTZDtype, IntervalDtype, + PandasDtype, PeriodDtype, ) @@ -111,6 +112,40 @@ def test_array_of_dt64_nat_with_td64dtype_raises(self, frame_or_series): with pytest.raises(ValueError, match=msg): frame_or_series(arr, dtype="m8[ns]") + @pytest.mark.parametrize("kind", ["m", "M"]) + def test_datetimelike_values_with_object_dtype(self, kind, frame_or_series): + # with dtype=object, we should cast dt64 values to Timestamps, not pydatetimes + if kind == "M": + dtype = "M8[ns]" + scalar_type = Timestamp + else: + dtype = "m8[ns]" + scalar_type = Timedelta + + arr = np.arange(6, dtype="i8").view(dtype).reshape(3, 2) + if frame_or_series is Series: + arr = arr[:, 0] + + obj = frame_or_series(arr, dtype=object) + assert obj._mgr.arrays[0].dtype == object + assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type) + + # go through a different path in internals.construction + obj = frame_or_series(frame_or_series(arr), dtype=object) + assert obj._mgr.arrays[0].dtype == object + assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type) + + obj = frame_or_series(frame_or_series(arr), dtype=PandasDtype(object)) + assert obj._mgr.arrays[0].dtype == object + assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type) + + if frame_or_series is DataFrame: + # other paths through internals.construction + sers = [Series(x) for x in arr] + obj = frame_or_series(sers, dtype=object) + assert obj._mgr.arrays[0].dtype == object + assert isinstance(obj._mgr.arrays[0].ravel()[0], scalar_type) + def test_series_with_name_not_matching_column(self): # GH#9232 x = Series(range(5), name=1)
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41599
2021-05-21T05:10:26Z
2021-05-21T21:17:15Z
2021-05-21T21:17:15Z
2021-05-21T21:21:42Z
REF: _try_cast; go through fastpath more often
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index e83aa02f25ada..51b9ed5fd22c7 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -38,9 +38,9 @@ construct_1d_object_array_from_listlike, maybe_cast_to_datetime, maybe_cast_to_integer_array, - maybe_castable, maybe_convert_platform, maybe_upcast, + sanitize_to_nanoseconds, ) from pandas.core.dtypes.common import ( is_datetime64_ns_dtype, @@ -656,33 +656,53 @@ def _try_cast( ------- np.ndarray or ExtensionArray """ + is_ndarray = isinstance(arr, np.ndarray) + # perf shortcut as this is the most common case + # Item "List[Any]" of "Union[List[Any], ndarray]" has no attribute "dtype" if ( - isinstance(arr, np.ndarray) - and maybe_castable(arr.dtype) + is_ndarray + and arr.dtype != object # type: ignore[union-attr] and not copy and dtype is None ): - return arr + # Argument 1 to "sanitize_to_nanoseconds" has incompatible type + # "Union[List[Any], ndarray]"; expected "ndarray" + return sanitize_to_nanoseconds(arr) # type: ignore[arg-type] - if isinstance(dtype, ExtensionDtype) and not isinstance(dtype, DatetimeTZDtype): + if isinstance(dtype, ExtensionDtype): # create an extension array from its dtype # DatetimeTZ case needs to go through maybe_cast_to_datetime but # SparseDtype does not + if isinstance(dtype, DatetimeTZDtype): + # We can't go through _from_sequence because it handles dt64naive + # data differently; _from_sequence treats naive as wall times, + # while maybe_cast_to_datetime treats it as UTC + # see test_maybe_promote_any_numpy_dtype_with_datetimetz + + # error: Incompatible return value type (got "Union[ExtensionArray, + # ndarray, List[Any]]", expected "Union[ExtensionArray, ndarray]") + return maybe_cast_to_datetime(arr, dtype) # type: ignore[return-value] + # TODO: copy? + array_type = dtype.construct_array_type()._from_sequence subarr = array_type(arr, dtype=dtype, copy=copy) return subarr - if is_object_dtype(dtype) and not isinstance(arr, np.ndarray): - subarr = construct_1d_object_array_from_listlike(arr) - return subarr + elif is_object_dtype(dtype): + if not is_ndarray: + subarr = construct_1d_object_array_from_listlike(arr) + return subarr + return ensure_wrapped_if_datetimelike(arr).astype(dtype, copy=copy) - if dtype is None and isinstance(arr, list): + elif dtype is None and not is_ndarray: # filter out cases that we _dont_ want to go through maybe_cast_to_datetime varr = np.array(arr, copy=False) if varr.dtype != object or varr.size == 0: return varr - arr = varr + # error: Incompatible return value type (got "Union[ExtensionArray, + # ndarray, List[Any]]", expected "Union[ExtensionArray, ndarray]") + return maybe_cast_to_datetime(varr, None) # type: ignore[return-value] try: # GH#15832: Check if we are requesting a numeric dtype and diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 80d9a22a39b1e..3341e34305c2d 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -46,7 +46,6 @@ from pandas.core.dtypes.common import ( DT64NS_DTYPE, - POSSIBLY_CAST_DTYPES, TD64NS_DTYPE, ensure_int8, ensure_int16, @@ -59,7 +58,6 @@ is_complex, is_complex_dtype, is_datetime64_dtype, - is_datetime64_ns_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_dtype_equal, @@ -74,7 +72,6 @@ is_sparse, is_string_dtype, is_timedelta64_dtype, - is_timedelta64_ns_dtype, is_unsigned_integer_dtype, pandas_dtype, ) @@ -1480,20 +1477,6 @@ def convert_dtypes( return inferred_dtype -def maybe_castable(dtype: np.dtype) -> bool: - # return False to force a non-fastpath - - # check datetime64[ns]/timedelta64[ns] are valid - # otherwise try to coerce - kind = dtype.kind - if kind == "M": - return is_datetime64_ns_dtype(dtype) - elif kind == "m": - return is_timedelta64_ns_dtype(dtype) - - return dtype.name not in POSSIBLY_CAST_DTYPES - - def maybe_infer_to_datetimelike( value: np.ndarray, ) -> np.ndarray | DatetimeArray | TimedeltaArray: diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 593e42f7ed749..3f43681687945 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -58,21 +58,6 @@ is_sequence, ) -POSSIBLY_CAST_DTYPES = { - np.dtype(t).name - for t in [ - "O", - "int8", - "uint8", - "int16", - "uint16", - "int32", - "uint32", - "int64", - "uint64", - ] -} - DT64NS_DTYPE = conversion.DT64NS_DTYPE TD64NS_DTYPE = conversion.TD64NS_DTYPE INT64_DTYPE = np.dtype(np.int64)
- [x] closes #28145 - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41597
2021-05-20T22:55:46Z
2021-05-22T01:24:08Z
2021-05-22T01:24:08Z
2021-05-22T01:39:22Z
CI: Xfails on Python 3.10
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 8ccf89c73704c..57e0144c967ea 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -10,6 +10,12 @@ on: paths-ignore: - "doc/**" +env: + PYTEST_WORKERS: "auto" + PANDAS_CI: 1 + PATTERN: "not slow and not network and not clipboard" + COVERAGE: true + jobs: build: runs-on: ubuntu-latest @@ -36,7 +42,7 @@ jobs: pip install git+https://github.com/numpy/numpy.git pip install git+https://github.com/pytest-dev/pytest.git pip install git+https://github.com/nedbat/coveragepy.git - pip install cython python-dateutil pytz hypothesis pytest-xdist + pip install cython python-dateutil pytz hypothesis pytest-xdist pytest-cov pip list - name: Build Pandas @@ -50,7 +56,8 @@ jobs: - name: Test with pytest run: | - coverage run -m pytest -m 'not slow and not network and not clipboard' pandas + ci/run_tests.sh + # GH 41935 continue-on-error: true - name: Publish test results diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 5731f02430a9d..c6240600d3a05 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -2,9 +2,6 @@ This module tests the functionality of StringArray and ArrowStringArray. Tests for the str accessors are in pandas/tests/strings/test_string_array.py """ - -import re - import numpy as np import pytest @@ -314,7 +311,7 @@ def test_astype_int(dtype): tm.assert_numpy_array_equal(result, expected) arr = pd.array(["1", pd.NA, "3"], dtype=dtype) - msg = re.escape("int() argument must be a string, a bytes-like object or a number") + msg = r"int\(\) argument must be a string, a bytes-like object or a( real)? number" with pytest.raises(TypeError, match=msg): arr.astype("int64") diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index f0d3fb7ff9e1b..9c21f717573c1 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -13,6 +13,7 @@ be added to the array-specific tests in `pandas/tests/arrays/`. """ + import numpy as np import pytest diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index d7abaf0b5dfbe..af781f0b58f85 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -12,6 +12,7 @@ from pandas.compat import ( IS64, + PY310, np_datetime64_compat, ) from pandas.util._test_decorators import async_mark @@ -992,7 +993,7 @@ def test_isin(self, values, index, expected): result = index.isin(values) tm.assert_numpy_array_equal(result, expected) - def test_isin_nan_common_object(self, nulls_fixture, nulls_fixture2): + def test_isin_nan_common_object(self, request, nulls_fixture, nulls_fixture2): # Test cartesian product of null fixtures and ensure that we don't # mangle the various types (save a corner case with PyPy) @@ -1003,6 +1004,24 @@ def test_isin_nan_common_object(self, nulls_fixture, nulls_fixture2): and math.isnan(nulls_fixture) and math.isnan(nulls_fixture2) ): + if PY310: + if ( + # Failing cases are + # np.nan, float('nan') + # float('nan'), np.nan + # float('nan'), float('nan') + # Since only float('nan'), np.nan is float + # Use not np.nan to identify float('nan') + nulls_fixture is np.nan + and nulls_fixture2 is not np.nan + or nulls_fixture is not np.nan + ): + request.applymarker( + # This test is flaky :( + pytest.mark.xfail( + reason="Failing on Python 3.10 GH41940", strict=False + ) + ) tm.assert_numpy_array_equal( Index(["a", nulls_fixture]).isin([nulls_fixture2]), np.array([False, True]), diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 805f6b8dbe461..57a6b214cec84 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -16,6 +16,7 @@ import pandas._libs.json as ujson from pandas.compat import ( IS64, + PY310, is_platform_windows, ) @@ -248,7 +249,21 @@ def test_double_precision(self): assert rounded_input == json.loads(output) assert rounded_input == ujson.decode(output) - @pytest.mark.parametrize("invalid_val", [20, -1, "9", None]) + @pytest.mark.parametrize( + "invalid_val", + [ + 20, + -1, + pytest.param( + "9", + marks=pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940"), + ), + pytest.param( + None, + marks=pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940"), + ), + ], + ) def test_invalid_double_precision(self, invalid_val): double_input = 30.12345678901234567890 expected_exception = ValueError if isinstance(invalid_val, int) else TypeError diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py index 653ea88ed62ac..d33721c796efa 100644 --- a/pandas/tests/reshape/test_get_dummies.py +++ b/pandas/tests/reshape/test_get_dummies.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat import PY310 + from pandas.core.dtypes.common import is_integer_dtype import pandas as pd @@ -428,6 +430,8 @@ def test_dataframe_dummies_unicode(self, get_dummies_kwargs, expected): result = get_dummies(**get_dummies_kwargs) tm.assert_frame_equal(result, expected) + # This is flaky on Python 3.10 + @pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940", strict=False) def test_get_dummies_basic_drop_first(self, sparse): # GH12402 Add a new parameter `drop_first` to avoid collinearity # Basic case @@ -467,6 +471,7 @@ def test_get_dummies_basic_drop_first_one_level(self, sparse): result = get_dummies(s_series_index, drop_first=True, sparse=sparse) tm.assert_frame_equal(result, expected) + @pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940", strict=False) def test_get_dummies_basic_drop_first_NA(self, sparse): # Test NA handling together with drop_first s_NA = ["a", "b", np.nan] diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 4df95d895e475..490052c793fdc 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -9,7 +9,10 @@ algos as libalgos, hashtable as ht, ) -from pandas.compat import np_array_datetime64_compat +from pandas.compat import ( + PY310, + np_array_datetime64_compat, +) import pandas.util._test_decorators as td from pandas.core.dtypes.common import ( @@ -783,6 +786,8 @@ def test_different_nans(self): expected = np.array([np.nan]) tm.assert_numpy_array_equal(result, expected) + # Flaky on Python 3.10 -> Don't make strict + @pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940", strict=False) def test_first_nan_kept(self): # GH 22295 # create different nans from bit-patterns: @@ -988,6 +993,8 @@ def __hash__(self): # different objects -> False tm.assert_numpy_array_equal(algos.isin([a], [b]), np.array([False])) + # Flaky on Python 3.10 -> Don't make strict + @pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940", strict=False) def test_different_nans(self): # GH 22160 # all nans are handled as equivalent @@ -1030,6 +1037,8 @@ def test_empty(self, empty): result = algos.isin(vals, empty) tm.assert_numpy_array_equal(expected, result) + # Flaky on Python 3.10 -> Don't make strict + @pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940", strict=False) def test_different_nan_objects(self): # GH 22119 comps = np.array(["nan", np.nan * 1j, float("nan")], dtype=object)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry ~~The Python 3.10 CI is actually red, but the continue-on-error flag makes it so that the job is not failed. WIP because tests actually have to be fixed.~~ Added Xfails for some tests. Pretty much green except for #41935
https://api.github.com/repos/pandas-dev/pandas/pulls/41595
2021-05-20T22:34:51Z
2021-06-29T12:26:09Z
2021-06-29T12:26:09Z
2021-06-29T13:55:27Z
TYP and DOC: pd.merge accepts Series
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 18ee1ad9bcd96..7b564d55a342c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -260,6 +260,8 @@ _merge_doc = """ Merge DataFrame or named Series objects with a database-style join. +A named Series object is treated as a DataFrame with a single named column. + The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 4791bbf0ba7f7..be9eeb64bc35d 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -27,7 +27,6 @@ ArrayLike, DtypeObj, FrameOrSeries, - FrameOrSeriesUnion, IndexLabel, Suffixes, ) @@ -81,15 +80,18 @@ from pandas.core.sorting import is_int64_overflow_possible if TYPE_CHECKING: - from pandas import DataFrame + from pandas import ( + DataFrame, + Series, + ) from pandas.core.arrays import DatetimeArray -@Substitution("\nleft : DataFrame") +@Substitution("\nleft : DataFrame or named Series") @Appender(_merge_doc, indents=0) def merge( - left: FrameOrSeriesUnion, - right: FrameOrSeriesUnion, + left: DataFrame | Series, + right: DataFrame | Series, how: str = "inner", on: IndexLabel | None = None, left_on: IndexLabel | None = None, @@ -322,8 +324,8 @@ def _merger(x, y) -> DataFrame: def merge_asof( - left: DataFrame, - right: DataFrame, + left: DataFrame | Series, + right: DataFrame | Series, on: IndexLabel | None = None, left_on: IndexLabel | None = None, right_on: IndexLabel | None = None, @@ -362,8 +364,8 @@ def merge_asof( Parameters ---------- - left : DataFrame - right : DataFrame + left : DataFrame or named Series + right : DataFrame or named Series on : label Field name to join on. Must be found in both DataFrames. The data MUST be ordered. Furthermore this must be a numeric column, @@ -608,8 +610,8 @@ class _MergeOperation: def __init__( self, - left: FrameOrSeriesUnion, - right: FrameOrSeriesUnion, + left: DataFrame | Series, + right: DataFrame | Series, how: str = "inner", on: IndexLabel | None = None, left_on: IndexLabel | None = None, @@ -1599,8 +1601,8 @@ class _OrderedMerge(_MergeOperation): def __init__( self, - left: DataFrame, - right: DataFrame, + left: DataFrame | Series, + right: DataFrame | Series, on: IndexLabel | None = None, left_on: IndexLabel | None = None, right_on: IndexLabel | None = None, @@ -1704,8 +1706,8 @@ class _AsOfMerge(_OrderedMerge): def __init__( self, - left: DataFrame, - right: DataFrame, + left: DataFrame | Series, + right: DataFrame | Series, on: IndexLabel | None = None, left_on: IndexLabel | None = None, right_on: IndexLabel | None = None,
I noticed that the docs for `pd.merge()` and `pd.merge_asof()` were requiring the first argument to be a `DataFrame`, but in fact, they can be a `Series`. This PR updates the docs and the types to fix that issue. Didn't think a `whatsnew` entry was needed, and I skipped creating an issue, but will do so if required.
https://api.github.com/repos/pandas-dev/pandas/pulls/41594
2021-05-20T21:28:47Z
2021-05-24T09:07:27Z
2021-05-24T09:07:27Z
2021-05-24T11:47:32Z
TYP: mypy fixups- something upgraded?
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index f337589c35583..7dddb9f3d6f25 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -493,8 +493,7 @@ def size(self) -> int: """ The number of elements in the array. """ - # error: Incompatible return value type (got "number", expected "int") - return np.prod(self.shape) # type: ignore[return-value] + return np.prod(self.shape) @property def ndim(self) -> int: diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index d4faea4fbc42c..8efdfb719bbfa 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -354,9 +354,8 @@ def density(self) -> float: """ Ratio of non-sparse points to total (dense) data points. """ - # error: Incompatible return value type (got "number", expected "float") tmp = np.mean([column.array.density for _, column in self._parent.items()]) - return tmp # type: ignore[return-value] + return tmp @staticmethod def _prep_index(data, index, columns): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c9982db97e824..7162bda0eff43 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -693,8 +693,7 @@ def size(self) -> int: >>> df.size 4 """ - # error: Incompatible return value type (got "number", expected "int") - return np.prod(self.shape) # type: ignore[return-value] + return np.prod(self.shape) @overload def set_axis( diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 2c31e45d0b4e1..b8909f16ee876 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -588,17 +588,9 @@ def nansum( dtype_sum = np.float64 # type: ignore[assignment] the_sum = values.sum(axis, dtype=dtype_sum) - # error: Incompatible types in assignment (expression has type "float", variable has - # type "Union[number, ndarray]") - # error: Argument 1 to "_maybe_null_out" has incompatible type "Union[number, - # ndarray]"; expected "ndarray" - the_sum = _maybe_null_out( # type: ignore[assignment] - the_sum, axis, mask, values.shape, min_count=min_count # type: ignore[arg-type] - ) + the_sum = _maybe_null_out(the_sum, axis, mask, values.shape, min_count=min_count) - # error: Incompatible return value type (got "Union[number, ndarray]", expected - # "float") - return the_sum # type: ignore[return-value] + return the_sum def _mask_datetimelike_result( @@ -1343,12 +1335,10 @@ def nanprod( values = values.copy() values[mask] = 1 result = values.prod(axis) - # error: Argument 1 to "_maybe_null_out" has incompatible type "Union[number, - # ndarray]"; expected "ndarray" # error: Incompatible return value type (got "Union[ndarray, float]", expected # "float") return _maybe_null_out( # type: ignore[return-value] - result, axis, mask, values.shape, min_count=min_count # type: ignore[arg-type] + result, axis, mask, values.shape, min_count=min_count ) @@ -1424,13 +1414,7 @@ def _get_counts( # expected "Union[int, float, ndarray]") return dtype.type(count) # type: ignore[return-value] try: - # error: Incompatible return value type (got "Union[ndarray, generic]", expected - # "Union[int, float, ndarray]") - # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type - # "Union[ExtensionDtype, dtype]"; expected "Union[dtype, None, type, - # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], - # List[Any], _DtypeDict, Tuple[Any, Any]]" - return count.astype(dtype) # type: ignore[return-value,arg-type] + return count.astype(dtype) except AttributeError: # error: Argument "dtype" to "array" has incompatible type # "Union[ExtensionDtype, dtype]"; expected "Union[dtype, None, type, diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 037fe5366255a..93859eb11dd44 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -176,9 +176,7 @@ def _make_selectors(self): self.full_shape = ngroups, stride selector = self.sorted_labels[-1] + stride * comp_index + self.lift - # error: Argument 1 to "zeros" has incompatible type "number"; expected - # "Union[int, Sequence[int]]" - mask = np.zeros(np.prod(self.full_shape), dtype=bool) # type: ignore[arg-type] + mask = np.zeros(np.prod(self.full_shape), dtype=bool) mask.put(selector, True) if mask.sum() < len(self.index): diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index f6c1afbde0bd9..8531f93fba321 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -630,22 +630,15 @@ def get_group_index_sorter( np.ndarray[np.intp] """ if ngroups is None: - # error: Incompatible types in assignment (expression has type "number[Any]", - # variable has type "Optional[int]") - ngroups = 1 + group_index.max() # type: ignore[assignment] + ngroups = 1 + group_index.max() count = len(group_index) alpha = 0.0 # taking complexities literally; there may be beta = 1.0 # some room for fine-tuning these parameters - # error: Unsupported operand types for * ("float" and "None") - do_groupsort = count > 0 and ( - (alpha + beta * ngroups) < (count * np.log(count)) # type: ignore[operator] - ) + do_groupsort = count > 0 and ((alpha + beta * ngroups) < (count * np.log(count))) if do_groupsort: - # Argument 2 to "groupsort_indexer" has incompatible type - # "Optional[int]"; expected "int" sorter, _ = algos.groupsort_indexer( ensure_platform_int(group_index), - ngroups, # type: ignore[arg-type] + ngroups, ) # sorter _should_ already be intp, but mypy is not yet able to verify else: diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 9d653c9a5f97c..485610af747f6 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1664,19 +1664,9 @@ def format_percentiles( ).astype(int) prec = max(1, prec) out = np.empty_like(percentiles, dtype=object) - # error: No overload variant of "__getitem__" of "list" matches argument type - # "Union[bool_, ndarray]" - out[int_idx] = ( - percentiles[int_idx].astype(int).astype(str) # type: ignore[call-overload] - ) + out[int_idx] = percentiles[int_idx].astype(int).astype(str) - # error: Item "float" of "Union[Any, float, str]" has no attribute "round" - # error: Item "str" of "Union[Any, float, str]" has no attribute "round" - # error: Invalid index type "Union[bool_, Any]" for "Union[ndarray, List[Union[int, - # float]], List[float], List[Union[str, float]]]"; expected type "int" - out[~int_idx] = ( - percentiles[~int_idx].round(prec).astype(str) # type: ignore[union-attr,index] - ) + out[~int_idx] = percentiles[~int_idx].round(prec).astype(str) return [i + "%" for i in out] diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 49eb7ea9f26e5..df2bfa7d2a870 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -684,9 +684,7 @@ def _infer_types(self, values, na_values, try_num_bool=True): # error: Argument 2 to "isin" has incompatible type "List[Any]"; expected # "Union[Union[ExtensionArray, ndarray], Index, Series]" mask = algorithms.isin(values, list(na_values)) # type: ignore[arg-type] - # error: Incompatible types in assignment (expression has type - # "number[Any]", variable has type "int") - na_count = mask.sum() # type: ignore[assignment] + na_count = mask.sum() if na_count > 0: if is_integer_dtype(values): values = values.astype(np.float64) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 10d55053d5bc6..75f5a8bf3c357 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3378,10 +3378,7 @@ def validate_multiindex( @property def nrows_expected(self) -> int: """ based on our axes, compute the expected nrows """ - # error: Incompatible return value type (got "number", expected "int") - return np.prod( # type: ignore[return-value] - [i.cvalues.shape[0] for i in self.index_axes] - ) + return np.prod([i.cvalues.shape[0] for i in self.index_axes]) @property def is_exists(self) -> bool:
I've been seeing these locally for a couple weeks, not sure why they just started showing up on the CI
https://api.github.com/repos/pandas-dev/pandas/pulls/41593
2021-05-20T20:58:35Z
2021-05-20T23:48:55Z
2021-05-20T23:48:55Z
2021-05-20T23:54:55Z
REF: simplify sanitize_array
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 0fef02b1489ac..e83aa02f25ada 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -6,7 +6,6 @@ """ from __future__ import annotations -from collections import abc from typing import ( TYPE_CHECKING, Any, @@ -501,6 +500,16 @@ def sanitize_array( if dtype is None: dtype = data.dtype data = lib.item_from_zerodim(data) + elif isinstance(data, range): + # GH#16804 + data = np.arange(data.start, data.stop, data.step, dtype="int64") + copy = False + + if not is_list_like(data): + if index is None: + raise ValueError("index must be specified when data is not list-like") + data = construct_1d_arraylike_from_scalar(data, len(index), dtype) + return data # GH#846 if isinstance(data, np.ndarray): @@ -525,14 +534,16 @@ def sanitize_array( subarr = subarr.copy() return subarr - elif isinstance(data, (list, tuple, abc.Set, abc.ValuesView)) and len(data) > 0: - # TODO: deque, array.array + else: if isinstance(data, (set, frozenset)): # Raise only for unordered sets, e.g., not for dict_keys raise TypeError(f"'{type(data).__name__}' type is unordered") + + # materialize e.g. generators, convert e.g. tuples, abc.ValueView + # TODO: non-standard array-likes we can convert to ndarray more efficiently? data = list(data) - if dtype is not None: + if dtype is not None or len(data) == 0: subarr = _try_cast(data, dtype, copy, raise_cast_failure) else: subarr = maybe_convert_platform(data) @@ -541,22 +552,6 @@ def sanitize_array( # "ExtensionArray") subarr = maybe_cast_to_datetime(subarr, dtype) # type: ignore[assignment] - elif isinstance(data, range): - # GH#16804 - arr = np.arange(data.start, data.stop, data.step, dtype="int64") - subarr = _try_cast(arr, dtype, copy, raise_cast_failure) - - elif not is_list_like(data): - if index is None: - raise ValueError("index must be specified when data is not list-like") - subarr = construct_1d_arraylike_from_scalar(data, len(index), dtype) - - else: - # realize e.g. generators - # TODO: non-standard array-likes we can convert to ndarray more efficiently? - data = list(data) - subarr = _try_cast(data, dtype, copy, raise_cast_failure) - subarr = _sanitize_ndim(subarr, data, dtype, index) if not ( diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 06d30d6ed72e8..fd8896a8a7e6e 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -554,10 +554,8 @@ def convert(v): else: - # drop subclass info, do not copy data - values = np.asarray(values) - if copy: - values = values.copy() + # drop subclass info + values = np.array(values, copy=copy) if values.ndim == 1: values = values.reshape((values.shape[0], 1))
We end up calling _try_cast in 3 places instead of 5
https://api.github.com/repos/pandas-dev/pandas/pulls/41592
2021-05-20T20:31:53Z
2021-05-21T15:26:59Z
2021-05-21T15:26:58Z
2021-05-21T15:42:08Z
[ArrowStringArray] PERF: use pyarrow.compute.replace_substring(_regex) if available
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 4370f3a4e15cf..13903d581793f 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Callable # noqa: PDF001 import re from typing import ( TYPE_CHECKING, @@ -834,6 +835,28 @@ def _str_endswith(self, pat: str, na=None): pat = re.escape(pat) + "$" return self._str_contains(pat, na=na, regex=True) + def _str_replace( + self, + pat: str | re.Pattern, + repl: str | Callable, + n: int = -1, + case: bool = True, + flags: int = 0, + regex: bool = True, + ): + if ( + pa_version_under4p0 + or isinstance(pat, re.Pattern) + or callable(repl) + or not case + or flags + ): + return super()._str_replace(pat, repl, n, case, flags, regex) + + func = pc.replace_substring_regex if regex else pc.replace_substring + result = func(self._data, pattern=pat, replacement=repl, max_replacements=n) + return type(self)(result) + def _str_match( self, pat: str, case: bool = True, flags: int = 0, na: Scalar = None ):
``` [ 50.00%] ··· strings.Methods.time_replace ok [ 50.00%] ··· ============== ========== dtype -------------- ---------- str 20.6±0ms string 16.3±0ms arrow_string 1.83±0ms ============== ========== ``` happy to break up if easier to review.
https://api.github.com/repos/pandas-dev/pandas/pulls/41590
2021-05-20T19:58:06Z
2021-05-26T01:49:55Z
2021-05-26T01:49:55Z
2021-05-30T13:50:00Z
ENH: Deprecate non-keyword arguments for MultiIndex.set_levels
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d654cf5715bdf..3768af266339d 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -681,6 +681,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional (except for ``"levels"``) in :meth:`MultiIndex.set_levels` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.sort_index` and :meth:`Series.sort_index` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`(:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 86d1503fe31c0..6a13ffa5a376b 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -804,6 +804,7 @@ def _set_levels( self._reset_cache() + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "levels"]) def set_levels( self, levels, level=None, inplace=None, verify_integrity: bool = True ): @@ -895,7 +896,7 @@ def set_levels( warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=3, ) else: inplace = False diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 0c561395788ad..9657e74c363b9 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -351,7 +351,7 @@ def test_set_levels_categorical(ordered): index = MultiIndex.from_arrays([list("xyzx"), [0, 1, 2, 3]]) cidx = CategoricalIndex(list("bac"), ordered=ordered) - result = index.set_levels(cidx, 0) + result = index.set_levels(cidx, level=0) expected = MultiIndex(levels=[cidx, [0, 1, 2, 3]], codes=index.codes) tm.assert_index_equal(result, expected) @@ -405,3 +405,30 @@ def test_set_levels_inplace_deprecated(idx, inplace): with tm.assert_produces_warning(FutureWarning): idx.set_levels(levels=new_level, level=1, inplace=inplace) + + +def test_set_levels_pos_args_deprecation(): + # https://github.com/pandas-dev/pandas/issues/41485 + idx = MultiIndex.from_tuples( + [ + (1, "one"), + (2, "one"), + (3, "one"), + ], + names=["foo", "bar"], + ) + msg = ( + r"In a future version of pandas all arguments of MultiIndex.set_levels except " + r"for the argument 'levels' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = idx.set_levels(["a", "b", "c"], 0) + expected = MultiIndex.from_tuples( + [ + ("a", "one"), + ("b", "one"), + ("c", "one"), + ], + names=["foo", "bar"], + ) + tm.assert_index_equal(result, expected)
- [X] xref #41486 - [X] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41589
2021-05-20T19:54:37Z
2021-05-26T10:04:04Z
2021-05-26T10:04:04Z
2021-05-29T09:14:16Z
DEPR: Timestamp.freq
diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst index e6271a7806706..f0e531cd81f84 100644 --- a/doc/source/reference/offset_frequency.rst +++ b/doc/source/reference/offset_frequency.rst @@ -26,6 +26,8 @@ Properties DateOffset.normalize DateOffset.rule_code DateOffset.n + DateOffset.is_month_start + DateOffset.is_month_end Methods ~~~~~~~ @@ -40,6 +42,12 @@ Methods DateOffset.is_anchored DateOffset.is_on_offset DateOffset.__call__ + DateOffset.is_month_start + DateOffset.is_month_end + DateOffset.is_quarter_start + DateOffset.is_quarter_end + DateOffset.is_year_start + DateOffset.is_year_end BusinessDay ----------- @@ -86,6 +94,12 @@ Methods BusinessDay.is_anchored BusinessDay.is_on_offset BusinessDay.__call__ + BusinessDay.is_month_start + BusinessDay.is_month_end + BusinessDay.is_quarter_start + BusinessDay.is_quarter_end + BusinessDay.is_year_start + BusinessDay.is_year_end BusinessHour ------------ @@ -125,6 +139,12 @@ Methods BusinessHour.is_anchored BusinessHour.is_on_offset BusinessHour.__call__ + BusinessHour.is_month_start + BusinessHour.is_month_end + BusinessHour.is_quarter_start + BusinessHour.is_quarter_end + BusinessHour.is_year_start + BusinessHour.is_year_end CustomBusinessDay ----------------- @@ -171,6 +191,12 @@ Methods CustomBusinessDay.is_anchored CustomBusinessDay.is_on_offset CustomBusinessDay.__call__ + CustomBusinessDay.is_month_start + CustomBusinessDay.is_month_end + CustomBusinessDay.is_quarter_start + CustomBusinessDay.is_quarter_end + CustomBusinessDay.is_year_start + CustomBusinessDay.is_year_end CustomBusinessHour ------------------ @@ -210,6 +236,12 @@ Methods CustomBusinessHour.is_anchored CustomBusinessHour.is_on_offset CustomBusinessHour.__call__ + CustomBusinessHour.is_month_start + CustomBusinessHour.is_month_end + CustomBusinessHour.is_quarter_start + CustomBusinessHour.is_quarter_end + CustomBusinessHour.is_year_start + CustomBusinessHour.is_year_end MonthEnd -------- @@ -244,6 +276,12 @@ Methods MonthEnd.is_anchored MonthEnd.is_on_offset MonthEnd.__call__ + MonthEnd.is_month_start + MonthEnd.is_month_end + MonthEnd.is_quarter_start + MonthEnd.is_quarter_end + MonthEnd.is_year_start + MonthEnd.is_year_end MonthBegin ---------- @@ -278,6 +316,12 @@ Methods MonthBegin.is_anchored MonthBegin.is_on_offset MonthBegin.__call__ + MonthBegin.is_month_start + MonthBegin.is_month_end + MonthBegin.is_quarter_start + MonthBegin.is_quarter_end + MonthBegin.is_year_start + MonthBegin.is_year_end BusinessMonthEnd ---------------- @@ -321,6 +365,12 @@ Methods BusinessMonthEnd.is_anchored BusinessMonthEnd.is_on_offset BusinessMonthEnd.__call__ + BusinessMonthEnd.is_month_start + BusinessMonthEnd.is_month_end + BusinessMonthEnd.is_quarter_start + BusinessMonthEnd.is_quarter_end + BusinessMonthEnd.is_year_start + BusinessMonthEnd.is_year_end BusinessMonthBegin ------------------ @@ -364,6 +414,12 @@ Methods BusinessMonthBegin.is_anchored BusinessMonthBegin.is_on_offset BusinessMonthBegin.__call__ + BusinessMonthBegin.is_month_start + BusinessMonthBegin.is_month_end + BusinessMonthBegin.is_quarter_start + BusinessMonthBegin.is_quarter_end + BusinessMonthBegin.is_year_start + BusinessMonthBegin.is_year_end CustomBusinessMonthEnd ---------------------- @@ -411,6 +467,12 @@ Methods CustomBusinessMonthEnd.is_anchored CustomBusinessMonthEnd.is_on_offset CustomBusinessMonthEnd.__call__ + CustomBusinessMonthEnd.is_month_start + CustomBusinessMonthEnd.is_month_end + CustomBusinessMonthEnd.is_quarter_start + CustomBusinessMonthEnd.is_quarter_end + CustomBusinessMonthEnd.is_year_start + CustomBusinessMonthEnd.is_year_end CustomBusinessMonthBegin ------------------------ @@ -458,6 +520,12 @@ Methods CustomBusinessMonthBegin.is_anchored CustomBusinessMonthBegin.is_on_offset CustomBusinessMonthBegin.__call__ + CustomBusinessMonthBegin.is_month_start + CustomBusinessMonthBegin.is_month_end + CustomBusinessMonthBegin.is_quarter_start + CustomBusinessMonthBegin.is_quarter_end + CustomBusinessMonthBegin.is_year_start + CustomBusinessMonthBegin.is_year_end SemiMonthEnd ------------ @@ -493,6 +561,12 @@ Methods SemiMonthEnd.is_anchored SemiMonthEnd.is_on_offset SemiMonthEnd.__call__ + SemiMonthEnd.is_month_start + SemiMonthEnd.is_month_end + SemiMonthEnd.is_quarter_start + SemiMonthEnd.is_quarter_end + SemiMonthEnd.is_year_start + SemiMonthEnd.is_year_end SemiMonthBegin -------------- @@ -528,6 +602,12 @@ Methods SemiMonthBegin.is_anchored SemiMonthBegin.is_on_offset SemiMonthBegin.__call__ + SemiMonthBegin.is_month_start + SemiMonthBegin.is_month_end + SemiMonthBegin.is_quarter_start + SemiMonthBegin.is_quarter_end + SemiMonthBegin.is_year_start + SemiMonthBegin.is_year_end Week ---- @@ -563,6 +643,12 @@ Methods Week.is_anchored Week.is_on_offset Week.__call__ + Week.is_month_start + Week.is_month_end + Week.is_quarter_start + Week.is_quarter_end + Week.is_year_start + Week.is_year_end WeekOfMonth ----------- @@ -599,6 +685,12 @@ Methods WeekOfMonth.is_on_offset WeekOfMonth.__call__ WeekOfMonth.weekday + WeekOfMonth.is_month_start + WeekOfMonth.is_month_end + WeekOfMonth.is_quarter_start + WeekOfMonth.is_quarter_end + WeekOfMonth.is_year_start + WeekOfMonth.is_year_end LastWeekOfMonth --------------- @@ -635,6 +727,12 @@ Methods LastWeekOfMonth.is_anchored LastWeekOfMonth.is_on_offset LastWeekOfMonth.__call__ + LastWeekOfMonth.is_month_start + LastWeekOfMonth.is_month_end + LastWeekOfMonth.is_quarter_start + LastWeekOfMonth.is_quarter_end + LastWeekOfMonth.is_year_start + LastWeekOfMonth.is_year_end BQuarterEnd ----------- @@ -670,6 +768,12 @@ Methods BQuarterEnd.is_anchored BQuarterEnd.is_on_offset BQuarterEnd.__call__ + BQuarterEnd.is_month_start + BQuarterEnd.is_month_end + BQuarterEnd.is_quarter_start + BQuarterEnd.is_quarter_end + BQuarterEnd.is_year_start + BQuarterEnd.is_year_end BQuarterBegin ------------- @@ -705,6 +809,12 @@ Methods BQuarterBegin.is_anchored BQuarterBegin.is_on_offset BQuarterBegin.__call__ + BQuarterBegin.is_month_start + BQuarterBegin.is_month_end + BQuarterBegin.is_quarter_start + BQuarterBegin.is_quarter_end + BQuarterBegin.is_year_start + BQuarterBegin.is_year_end QuarterEnd ---------- @@ -740,6 +850,12 @@ Methods QuarterEnd.is_anchored QuarterEnd.is_on_offset QuarterEnd.__call__ + QuarterEnd.is_month_start + QuarterEnd.is_month_end + QuarterEnd.is_quarter_start + QuarterEnd.is_quarter_end + QuarterEnd.is_year_start + QuarterEnd.is_year_end QuarterBegin ------------ @@ -775,6 +891,12 @@ Methods QuarterBegin.is_anchored QuarterBegin.is_on_offset QuarterBegin.__call__ + QuarterBegin.is_month_start + QuarterBegin.is_month_end + QuarterBegin.is_quarter_start + QuarterBegin.is_quarter_end + QuarterBegin.is_year_start + QuarterBegin.is_year_end BYearEnd -------- @@ -810,6 +932,12 @@ Methods BYearEnd.is_anchored BYearEnd.is_on_offset BYearEnd.__call__ + BYearEnd.is_month_start + BYearEnd.is_month_end + BYearEnd.is_quarter_start + BYearEnd.is_quarter_end + BYearEnd.is_year_start + BYearEnd.is_year_end BYearBegin ---------- @@ -845,6 +973,12 @@ Methods BYearBegin.is_anchored BYearBegin.is_on_offset BYearBegin.__call__ + BYearBegin.is_month_start + BYearBegin.is_month_end + BYearBegin.is_quarter_start + BYearBegin.is_quarter_end + BYearBegin.is_year_start + BYearBegin.is_year_end YearEnd ------- @@ -880,6 +1014,12 @@ Methods YearEnd.is_anchored YearEnd.is_on_offset YearEnd.__call__ + YearEnd.is_month_start + YearEnd.is_month_end + YearEnd.is_quarter_start + YearEnd.is_quarter_end + YearEnd.is_year_start + YearEnd.is_year_end YearBegin --------- @@ -915,6 +1055,12 @@ Methods YearBegin.is_anchored YearBegin.is_on_offset YearBegin.__call__ + YearBegin.is_month_start + YearBegin.is_month_end + YearBegin.is_quarter_start + YearBegin.is_quarter_end + YearBegin.is_year_start + YearBegin.is_year_end FY5253 ------ @@ -954,6 +1100,12 @@ Methods FY5253.is_anchored FY5253.is_on_offset FY5253.__call__ + FY5253.is_month_start + FY5253.is_month_end + FY5253.is_quarter_start + FY5253.is_quarter_end + FY5253.is_year_start + FY5253.is_year_end FY5253Quarter ------------- @@ -995,6 +1147,12 @@ Methods FY5253Quarter.is_on_offset FY5253Quarter.year_has_extra_week FY5253Quarter.__call__ + FY5253Quarter.is_month_start + FY5253Quarter.is_month_end + FY5253Quarter.is_quarter_start + FY5253Quarter.is_quarter_end + FY5253Quarter.is_year_start + FY5253Quarter.is_year_end Easter ------ @@ -1029,6 +1187,12 @@ Methods Easter.is_anchored Easter.is_on_offset Easter.__call__ + Easter.is_month_start + Easter.is_month_end + Easter.is_quarter_start + Easter.is_quarter_end + Easter.is_year_start + Easter.is_year_end Tick ---- @@ -1064,6 +1228,12 @@ Methods Tick.__call__ Tick.apply Tick.apply_index + Tick.is_month_start + Tick.is_month_end + Tick.is_quarter_start + Tick.is_quarter_end + Tick.is_year_start + Tick.is_year_end Day --- @@ -1099,6 +1269,12 @@ Methods Day.__call__ Day.apply Day.apply_index + Day.is_month_start + Day.is_month_end + Day.is_quarter_start + Day.is_quarter_end + Day.is_year_start + Day.is_year_end Hour ---- @@ -1134,6 +1310,12 @@ Methods Hour.__call__ Hour.apply Hour.apply_index + Hour.is_month_start + Hour.is_month_end + Hour.is_quarter_start + Hour.is_quarter_end + Hour.is_year_start + Hour.is_year_end Minute ------ @@ -1169,6 +1351,12 @@ Methods Minute.__call__ Minute.apply Minute.apply_index + Minute.is_month_start + Minute.is_month_end + Minute.is_quarter_start + Minute.is_quarter_end + Minute.is_year_start + Minute.is_year_end Second ------ @@ -1204,6 +1392,12 @@ Methods Second.__call__ Second.apply Second.apply_index + Second.is_month_start + Second.is_month_end + Second.is_quarter_start + Second.is_quarter_end + Second.is_year_start + Second.is_year_end Milli ----- @@ -1239,6 +1433,12 @@ Methods Milli.__call__ Milli.apply Milli.apply_index + Milli.is_month_start + Milli.is_month_end + Milli.is_quarter_start + Milli.is_quarter_end + Milli.is_year_start + Milli.is_year_end Micro ----- @@ -1274,6 +1474,12 @@ Methods Micro.__call__ Micro.apply Micro.apply_index + Micro.is_month_start + Micro.is_month_end + Micro.is_quarter_start + Micro.is_quarter_end + Micro.is_year_start + Micro.is_year_end Nano ---- @@ -1309,6 +1515,12 @@ Methods Nano.__call__ Nano.apply Nano.apply_index + Nano.is_month_start + Nano.is_month_end + Nano.is_quarter_start + Nano.is_quarter_end + Nano.is_year_start + Nano.is_year_end .. _api.frequencies: diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1b2a16244d606..e80b43a5ecad6 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -690,6 +690,7 @@ Deprecations - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated behavior of :class:`DataFrame` constructor when a ``dtype`` is passed and the data cannot be cast to that dtype. In a future version, this will raise instead of being silently ignored (:issue:`24435`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated the :attr:`Timestamp.freq` attribute. For the properties that use it (``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, ``is_year_start``, ``is_year_end``), when you have a ``freq``, use e.g. ``freq.is_month_start(ts)`` (:issue:`15146`) - Deprecated passing arguments as positional in :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, and :meth:`Series.bfill` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.sort_values` (other than ``"by"``) and :meth:`Series.sort_values` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.dropna` and :meth:`Series.dropna` (:issue:`41485`) diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 4e6e5485b2ade..1b1a497df4ca7 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -716,6 +716,26 @@ cdef class BaseOffset: # if there were a canonical docstring for what is_anchored means. return self.n == 1 + # ------------------------------------------------------------------ + + def is_month_start(self, _Timestamp ts): + return ts._get_start_end_field("is_month_start", self) + + def is_month_end(self, _Timestamp ts): + return ts._get_start_end_field("is_month_end", self) + + def is_quarter_start(self, _Timestamp ts): + return ts._get_start_end_field("is_quarter_start", self) + + def is_quarter_end(self, _Timestamp ts): + return ts._get_start_end_field("is_quarter_end", self) + + def is_year_start(self, _Timestamp ts): + return ts._get_start_end_field("is_year_start", self) + + def is_year_end(self, _Timestamp ts): + return ts._get_start_end_field("is_year_end", self) + cdef class SingleConstructorOffset(BaseOffset): @classmethod diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd index eadd7c7022acb..8833a611b0722 100644 --- a/pandas/_libs/tslibs/timestamps.pxd +++ b/pandas/_libs/tslibs/timestamps.pxd @@ -16,9 +16,9 @@ cdef object create_timestamp_from_ts(int64_t value, cdef class _Timestamp(ABCTimestamp): cdef readonly: int64_t value, nanosecond - object freq + object _freq - cdef bint _get_start_end_field(self, str field) + cdef bint _get_start_end_field(self, str field, freq) cdef _get_date_name_field(self, str field, object locale) cdef int64_t _maybe_convert_value_to_local(self) cdef bint _can_compare(self, datetime other) @@ -26,3 +26,5 @@ cdef class _Timestamp(ABCTimestamp): cpdef datetime to_pydatetime(_Timestamp self, bint warn=*) cdef bint _compare_outside_nanorange(_Timestamp self, datetime other, int op) except -1 + cpdef void _set_freq(self, freq) + cdef _warn_on_field_deprecation(_Timestamp self, freq, str field) diff --git a/pandas/_libs/tslibs/timestamps.pyi b/pandas/_libs/tslibs/timestamps.pyi index 8728b700a1f6d..1c06538c7399e 100644 --- a/pandas/_libs/tslibs/timestamps.pyi +++ b/pandas/_libs/tslibs/timestamps.pyi @@ -18,6 +18,7 @@ from typing import ( import numpy as np from pandas._libs.tslibs import ( + BaseOffset, NaT, NaTType, Period, @@ -57,6 +58,8 @@ class Timestamp(datetime): fold: int | None= ..., ) -> _S | NaTType: ... + def _set_freq(self, freq: BaseOffset | None) -> None: ... + @property def year(self) -> int: ... @property diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index a4f764878d19e..7b03522d56d76 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -123,7 +123,7 @@ cdef inline object create_timestamp_from_ts(int64_t value, dts.day, dts.hour, dts.min, dts.sec, dts.us, tz, fold=fold) ts_base.value = value - ts_base.freq = freq + ts_base._freq = freq ts_base.nanosecond = dts.ps // 1000 return ts_base @@ -155,6 +155,21 @@ cdef class _Timestamp(ABCTimestamp): dayofweek = _Timestamp.day_of_week dayofyear = _Timestamp.day_of_year + cpdef void _set_freq(self, freq): + # set the ._freq attribute without going through the constructor, + # which would issue a warning + # Caller is responsible for validation + self._freq = freq + + @property + def freq(self): + warnings.warn( + "Timestamp.freq is deprecated and will be removed in a future version", + FutureWarning, + stacklevel=1, + ) + return self._freq + def __hash__(_Timestamp self): if self.nanosecond: return hash(self.value) @@ -263,7 +278,9 @@ cdef class _Timestamp(ABCTimestamp): if is_any_td_scalar(other): nanos = delta_to_nanoseconds(other) - result = type(self)(self.value + nanos, tz=self.tzinfo, freq=self.freq) + result = type(self)(self.value + nanos, tz=self.tzinfo) + if result is not NaT: + result._set_freq(self._freq) # avoid warning in constructor return result elif is_integer_object(other): @@ -361,18 +378,17 @@ cdef class _Timestamp(ABCTimestamp): val = self.value return val - cdef bint _get_start_end_field(self, str field): + cdef bint _get_start_end_field(self, str field, freq): cdef: int64_t val dict kwds ndarray[uint8_t, cast=True] out int month_kw - freq = self.freq if freq: kwds = freq.kwds month_kw = kwds.get('startingMonth', kwds.get('month', 12)) - freqstr = self.freqstr + freqstr = self._freqstr else: month_kw = 12 freqstr = None @@ -382,6 +398,31 @@ cdef class _Timestamp(ABCTimestamp): field, freqstr, month_kw) return out[0] + cdef _warn_on_field_deprecation(self, freq, str field): + """ + Warn if the removal of .freq change the value of start/end properties. + """ + cdef: + bint needs = False + + if freq is not None: + kwds = freq.kwds + month_kw = kwds.get("startingMonth", kwds.get("month", 12)) + freqstr = self._freqstr + if month_kw != 12: + needs = True + if freqstr.startswith("B"): + needs = True + + if needs: + warnings.warn( + "Timestamp.freq is deprecated and will be removed in a future " + "version. When you have a freq, use " + f"freq.{field}(timestamp) instead", + FutureWarning, + stacklevel=1, + ) + @property def is_month_start(self) -> bool: """ @@ -397,10 +438,11 @@ cdef class _Timestamp(ABCTimestamp): >>> ts.is_month_start True """ - if self.freq is None: + if self._freq is None: # fast-path for non-business frequencies return self.day == 1 - return self._get_start_end_field("is_month_start") + self._warn_on_field_deprecation(self._freq, "is_month_start") + return self._get_start_end_field("is_month_start", self._freq) @property def is_month_end(self) -> bool: @@ -417,10 +459,11 @@ cdef class _Timestamp(ABCTimestamp): >>> ts.is_month_end True """ - if self.freq is None: + if self._freq is None: # fast-path for non-business frequencies return self.day == self.days_in_month - return self._get_start_end_field("is_month_end") + self._warn_on_field_deprecation(self._freq, "is_month_end") + return self._get_start_end_field("is_month_end", self._freq) @property def is_quarter_start(self) -> bool: @@ -437,10 +480,11 @@ cdef class _Timestamp(ABCTimestamp): >>> ts.is_quarter_start True """ - if self.freq is None: + if self._freq is None: # fast-path for non-business frequencies return self.day == 1 and self.month % 3 == 1 - return self._get_start_end_field("is_quarter_start") + self._warn_on_field_deprecation(self._freq, "is_quarter_start") + return self._get_start_end_field("is_quarter_start", self._freq) @property def is_quarter_end(self) -> bool: @@ -457,10 +501,11 @@ cdef class _Timestamp(ABCTimestamp): >>> ts.is_quarter_end True """ - if self.freq is None: + if self._freq is None: # fast-path for non-business frequencies return (self.month % 3) == 0 and self.day == self.days_in_month - return self._get_start_end_field("is_quarter_end") + self._warn_on_field_deprecation(self._freq, "is_quarter_end") + return self._get_start_end_field("is_quarter_end", self._freq) @property def is_year_start(self) -> bool: @@ -477,10 +522,11 @@ cdef class _Timestamp(ABCTimestamp): >>> ts.is_year_start True """ - if self.freq is None: + if self._freq is None: # fast-path for non-business frequencies return self.day == self.month == 1 - return self._get_start_end_field("is_year_start") + self._warn_on_field_deprecation(self._freq, "is_year_start") + return self._get_start_end_field("is_year_start", self._freq) @property def is_year_end(self) -> bool: @@ -497,10 +543,11 @@ cdef class _Timestamp(ABCTimestamp): >>> ts.is_year_end True """ - if self.freq is None: + if self._freq is None: # fast-path for non-business frequencies return self.month == 12 and self.day == 31 - return self._get_start_end_field("is_year_end") + self._warn_on_field_deprecation(self._freq, "is_year_end") + return self._get_start_end_field("is_year_end", self._freq) cdef _get_date_name_field(self, str field, object locale): cdef: @@ -673,11 +720,11 @@ cdef class _Timestamp(ABCTimestamp): def __setstate__(self, state): self.value = state[0] - self.freq = state[1] + self._freq = state[1] self.tzinfo = state[2] def __reduce__(self): - object_state = self.value, self.freq, self.tzinfo + object_state = self.value, self._freq, self.tzinfo return (Timestamp, object_state) # ----------------------------------------------------------------- @@ -719,7 +766,7 @@ cdef class _Timestamp(ABCTimestamp): pass tz = f", tz='{zone}'" if zone is not None else "" - freq = "" if self.freq is None else f", freq='{self.freqstr}'" + freq = "" if self._freq is None else f", freq='{self._freqstr}'" return f"Timestamp('{stamp}'{tz}{freq})" @@ -877,7 +924,13 @@ cdef class _Timestamp(ABCTimestamp): ) if freq is None: - freq = self.freq + freq = self._freq + warnings.warn( + "In a future version, calling 'Timestamp.to_period()' without " + "passing a 'freq' will raise an exception.", + FutureWarning, + stacklevel=2, + ) return Period(self, freq=freq) @@ -1147,7 +1200,7 @@ class Timestamp(_Timestamp): nanosecond=None, tzinfo_type tzinfo=None, *, - fold=None + fold=None, ): # The parameter list folds together legacy parameter names (the first # four) and positional and keyword parameter names from pydatetime. @@ -1276,9 +1329,16 @@ class Timestamp(_Timestamp): if freq is None: # GH 22311: Try to extract the frequency of a given Timestamp input - freq = getattr(ts_input, 'freq', None) - elif not is_offset_object(freq): - freq = to_offset(freq) + freq = getattr(ts_input, '_freq', None) + else: + warnings.warn( + "The 'freq' argument in Timestamp is deprecated and will be " + "removed in a future version.", + FutureWarning, + stacklevel=1, + ) + if not is_offset_object(freq): + freq = to_offset(freq) return create_timestamp_from_ts(ts.value, ts.dts, ts.tzinfo, freq, ts.fold) @@ -1551,12 +1611,21 @@ timedelta}, default 'raise' "Use tz_localize() or tz_convert() as appropriate" ) + @property + def _freqstr(self): + return getattr(self._freq, "freqstr", self._freq) + @property def freqstr(self): """ Return the total number of days in the month. """ - return getattr(self.freq, 'freqstr', self.freq) + warnings.warn( + "Timestamp.freqstr is deprecated and will be removed in a future version.", + FutureWarning, + stacklevel=1, + ) + return self._freqstr def tz_localize(self, tz, ambiguous='raise', nonexistent='raise'): """ @@ -1647,12 +1716,18 @@ default 'raise' value = tz_localize_to_utc_single(self.value, tz, ambiguous=ambiguous, nonexistent=nonexistent) - return Timestamp(value, tz=tz, freq=self.freq) + out = Timestamp(value, tz=tz) + if out is not NaT: + out._set_freq(self._freq) # avoid warning in constructor + return out else: if tz is None: # reset tz value = tz_convert_from_utc_single(self.value, self.tz) - return Timestamp(value, tz=tz, freq=self.freq) + out = Timestamp(value, tz=tz) + if out is not NaT: + out._set_freq(self._freq) # avoid warning in constructor + return out else: raise TypeError( "Cannot localize tz-aware Timestamp, use tz_convert for conversions" @@ -1707,7 +1782,10 @@ default 'raise' ) else: # Same UTC timestamp, different time zone - return Timestamp(self.value, tz=tz, freq=self.freq) + out = Timestamp(self.value, tz=tz) + if out is not NaT: + out._set_freq(self._freq) # avoid warning in constructor + return out astimezone = tz_convert @@ -1840,7 +1918,7 @@ default 'raise' if value != NPY_NAT: check_dts_bounds(&dts) - return create_timestamp_from_ts(value, dts, tzobj, self.freq, fold) + return create_timestamp_from_ts(value, dts, tzobj, self._freq, fold) def to_julian_date(self) -> np.float64: """ diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index ba5be03b93490..df33caab913bd 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1189,7 +1189,11 @@ def _addsub_object_array(self, other: np.ndarray, op): # Caller is responsible for broadcasting if necessary assert self.shape == other.shape, (self.shape, other.shape) - res_values = op(self.astype("O"), np.asarray(other)) + with warnings.catch_warnings(): + # filter out warnings about Timestamp.freq + warnings.filterwarnings("ignore", category=FutureWarning) + res_values = op(self.astype("O"), np.asarray(other)) + result = pd_array(res_values.ravel()) # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no attribute # "reshape" diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 020f708606353..7867471da6b94 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -510,7 +510,14 @@ def _check_compatible_with(self, other, setitem: bool = False): # Descriptive Properties def _box_func(self, x) -> Timestamp | NaTType: - return Timestamp(x, freq=self.freq, tz=self.tz) + ts = Timestamp(x, tz=self.tz) + # Non-overlapping identity check (left operand type: "Timestamp", + # right operand type: "NaTType") + if ts is not NaT: # type: ignore[comparison-overlap] + # GH#41586 + # do this instead of passing to the constructor to avoid FutureWarning + ts._set_freq(self.freq) + return ts @property # error: Return type "Union[dtype, DatetimeTZDtype]" of "dtype" @@ -603,13 +610,18 @@ def __iter__(self): length = len(self) chunksize = 10000 chunks = (length // chunksize) + 1 - for i in range(chunks): - start_i = i * chunksize - end_i = min((i + 1) * chunksize, length) - converted = ints_to_pydatetime( - data[start_i:end_i], tz=self.tz, freq=self.freq, box="timestamp" - ) - yield from converted + + with warnings.catch_warnings(): + # filter out warnings about Timestamp.freq + warnings.filterwarnings("ignore", category=FutureWarning) + + for i in range(chunks): + start_i = i * chunksize + end_i = min((i + 1) * chunksize, length) + converted = ints_to_pydatetime( + data[start_i:end_i], tz=self.tz, freq=self.freq, box="timestamp" + ) + yield from converted def astype(self, dtype, copy: bool = True): # We handle diff --git a/pandas/tests/frame/methods/test_first_valid_index.py b/pandas/tests/frame/methods/test_first_valid_index.py index c2de1a6bb7b14..e4cbd892de38e 100644 --- a/pandas/tests/frame/methods/test_first_valid_index.py +++ b/pandas/tests/frame/methods/test_first_valid_index.py @@ -74,6 +74,7 @@ def test_first_last_valid_all_nan(self, index_func): assert ser.first_valid_index() is None assert ser.last_valid_index() is None + @pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning") def test_first_last_valid_preserves_freq(self): # GH#20499: its preserves freq with holes index = date_range("20110101", periods=30, freq="B") diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 91f354fecca63..76d259707787d 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -421,6 +421,7 @@ def test_reset_index_multiindex_columns(self): result = df2.rename_axis([("c", "ii")]).reset_index(col_level=1, col_fill="C") tm.assert_frame_equal(result, expected) + @pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning") def test_reset_index_datetime(self, tz_naive_fixture): # GH#3950 tz = tz_naive_fixture @@ -509,9 +510,7 @@ def test_reset_index_datetime(self, tz_naive_fixture): }, columns=["level_0", "level_1", "a"], ) - expected["level_1"] = expected["level_1"].apply( - lambda d: Timestamp(d, freq="D", tz=tz) - ) + expected["level_1"] = expected["level_1"].apply(lambda d: Timestamp(d, tz=tz)) result = df.reset_index() tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/methods/test_repeat.py b/pandas/tests/indexes/datetimes/methods/test_repeat.py index 81768622fd3d5..c18109a23b6e8 100644 --- a/pandas/tests/indexes/datetimes/methods/test_repeat.py +++ b/pandas/tests/indexes/datetimes/methods/test_repeat.py @@ -62,10 +62,10 @@ def test_repeat(self, tz_naive_fixture): expected_rng = DatetimeIndex( [ - Timestamp("2016-01-01 00:00:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 00:00:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 00:30:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 00:30:00", tz=tz, freq="30T"), + Timestamp("2016-01-01 00:00:00", tz=tz), + Timestamp("2016-01-01 00:00:00", tz=tz), + Timestamp("2016-01-01 00:30:00", tz=tz), + Timestamp("2016-01-01 00:30:00", tz=tz), ] ) diff --git a/pandas/tests/indexes/datetimes/methods/test_to_period.py b/pandas/tests/indexes/datetimes/methods/test_to_period.py index 51cc6af2eed08..f6a598bd2a1ed 100644 --- a/pandas/tests/indexes/datetimes/methods/test_to_period.py +++ b/pandas/tests/indexes/datetimes/methods/test_to_period.py @@ -147,6 +147,9 @@ def test_to_period_tz(self, tz): with tm.assert_produces_warning(UserWarning): # GH#21333 warning that timezone info will be lost + # filter warning about freq deprecation + warnings.filterwarnings("ignore", category=FutureWarning) + result = ts.to_period()[0] expected = ts[0].to_period() @@ -165,6 +168,8 @@ def test_to_period_tz_utc_offset_consistency(self, tz): # GH#22905 ts = date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1") with tm.assert_produces_warning(UserWarning): + warnings.filterwarnings("ignore", category=FutureWarning) + result = ts.to_period()[0] expected = ts[0].to_period() assert result == expected diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 935e6afec246e..03cfeb245c11d 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -49,21 +49,21 @@ def test_date_range_timestamp_equiv(self): rng = date_range("20090415", "20090519", tz="US/Eastern") stamp = rng[0] - ts = Timestamp("20090415", tz="US/Eastern", freq="D") + ts = Timestamp("20090415", tz="US/Eastern") assert ts == stamp def test_date_range_timestamp_equiv_dateutil(self): rng = date_range("20090415", "20090519", tz="dateutil/US/Eastern") stamp = rng[0] - ts = Timestamp("20090415", tz="dateutil/US/Eastern", freq="D") + ts = Timestamp("20090415", tz="dateutil/US/Eastern") assert ts == stamp def test_date_range_timestamp_equiv_explicit_pytz(self): rng = date_range("20090415", "20090519", tz=pytz.timezone("US/Eastern")) stamp = rng[0] - ts = Timestamp("20090415", tz=pytz.timezone("US/Eastern"), freq="D") + ts = Timestamp("20090415", tz=pytz.timezone("US/Eastern")) assert ts == stamp @td.skip_if_windows_python_3 @@ -73,7 +73,7 @@ def test_date_range_timestamp_equiv_explicit_dateutil(self): rng = date_range("20090415", "20090519", tz=gettz("US/Eastern")) stamp = rng[0] - ts = Timestamp("20090415", tz=gettz("US/Eastern"), freq="D") + ts = Timestamp("20090415", tz=gettz("US/Eastern")) assert ts == stamp def test_date_range_timestamp_equiv_from_datetime_instance(self): @@ -82,12 +82,12 @@ def test_date_range_timestamp_equiv_from_datetime_instance(self): # addition/subtraction of integers timestamp_instance = date_range(datetime_instance, periods=1, freq="D")[0] - ts = Timestamp(datetime_instance, freq="D") + ts = Timestamp(datetime_instance) assert ts == timestamp_instance def test_date_range_timestamp_equiv_preserve_frequency(self): timestamp_instance = date_range("2014-03-05", periods=1, freq="D")[0] - ts = Timestamp("2014-03-05", freq="D") + ts = Timestamp("2014-03-05") assert timestamp_instance == ts @@ -400,9 +400,7 @@ def test_range_misspecified(self): def test_compat_replace(self): # https://github.com/statsmodels/statsmodels/issues/3349 # replace should take ints/longs for compat - result = date_range( - Timestamp("1960-04-01 00:00:00", freq="QS-JAN"), periods=76, freq="QS-JAN" - ) + result = date_range(Timestamp("1960-04-01 00:00:00"), periods=76, freq="QS-JAN") assert len(result) == 76 def test_catch_infinite_loop(self): diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index c3736d588601b..fe84699a89bc5 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -268,40 +268,43 @@ def test_datetimeindex_accessors4(self): assert dti.is_month_start[0] == 1 def test_datetimeindex_accessors5(self): - tests = [ - (Timestamp("2013-06-01", freq="M").is_month_start, 1), - (Timestamp("2013-06-01", freq="BM").is_month_start, 0), - (Timestamp("2013-06-03", freq="M").is_month_start, 0), - (Timestamp("2013-06-03", freq="BM").is_month_start, 1), - (Timestamp("2013-02-28", freq="Q-FEB").is_month_end, 1), - (Timestamp("2013-02-28", freq="Q-FEB").is_quarter_end, 1), - (Timestamp("2013-02-28", freq="Q-FEB").is_year_end, 1), - (Timestamp("2013-03-01", freq="Q-FEB").is_month_start, 1), - (Timestamp("2013-03-01", freq="Q-FEB").is_quarter_start, 1), - (Timestamp("2013-03-01", freq="Q-FEB").is_year_start, 1), - (Timestamp("2013-03-31", freq="QS-FEB").is_month_end, 1), - (Timestamp("2013-03-31", freq="QS-FEB").is_quarter_end, 0), - (Timestamp("2013-03-31", freq="QS-FEB").is_year_end, 0), - (Timestamp("2013-02-01", freq="QS-FEB").is_month_start, 1), - (Timestamp("2013-02-01", freq="QS-FEB").is_quarter_start, 1), - (Timestamp("2013-02-01", freq="QS-FEB").is_year_start, 1), - (Timestamp("2013-06-30", freq="BQ").is_month_end, 0), - (Timestamp("2013-06-30", freq="BQ").is_quarter_end, 0), - (Timestamp("2013-06-30", freq="BQ").is_year_end, 0), - (Timestamp("2013-06-28", freq="BQ").is_month_end, 1), - (Timestamp("2013-06-28", freq="BQ").is_quarter_end, 1), - (Timestamp("2013-06-28", freq="BQ").is_year_end, 0), - (Timestamp("2013-06-30", freq="BQS-APR").is_month_end, 0), - (Timestamp("2013-06-30", freq="BQS-APR").is_quarter_end, 0), - (Timestamp("2013-06-30", freq="BQS-APR").is_year_end, 0), - (Timestamp("2013-06-28", freq="BQS-APR").is_month_end, 1), - (Timestamp("2013-06-28", freq="BQS-APR").is_quarter_end, 1), - (Timestamp("2013-03-29", freq="BQS-APR").is_year_end, 1), - (Timestamp("2013-11-01", freq="AS-NOV").is_year_start, 1), - (Timestamp("2013-10-31", freq="AS-NOV").is_year_end, 1), - (Timestamp("2012-02-01").days_in_month, 29), - (Timestamp("2013-02-01").days_in_month, 28), - ] + with tm.assert_produces_warning( + FutureWarning, match="The 'freq' argument", check_stacklevel=False + ): + tests = [ + (Timestamp("2013-06-01", freq="M").is_month_start, 1), + (Timestamp("2013-06-01", freq="BM").is_month_start, 0), + (Timestamp("2013-06-03", freq="M").is_month_start, 0), + (Timestamp("2013-06-03", freq="BM").is_month_start, 1), + (Timestamp("2013-02-28", freq="Q-FEB").is_month_end, 1), + (Timestamp("2013-02-28", freq="Q-FEB").is_quarter_end, 1), + (Timestamp("2013-02-28", freq="Q-FEB").is_year_end, 1), + (Timestamp("2013-03-01", freq="Q-FEB").is_month_start, 1), + (Timestamp("2013-03-01", freq="Q-FEB").is_quarter_start, 1), + (Timestamp("2013-03-01", freq="Q-FEB").is_year_start, 1), + (Timestamp("2013-03-31", freq="QS-FEB").is_month_end, 1), + (Timestamp("2013-03-31", freq="QS-FEB").is_quarter_end, 0), + (Timestamp("2013-03-31", freq="QS-FEB").is_year_end, 0), + (Timestamp("2013-02-01", freq="QS-FEB").is_month_start, 1), + (Timestamp("2013-02-01", freq="QS-FEB").is_quarter_start, 1), + (Timestamp("2013-02-01", freq="QS-FEB").is_year_start, 1), + (Timestamp("2013-06-30", freq="BQ").is_month_end, 0), + (Timestamp("2013-06-30", freq="BQ").is_quarter_end, 0), + (Timestamp("2013-06-30", freq="BQ").is_year_end, 0), + (Timestamp("2013-06-28", freq="BQ").is_month_end, 1), + (Timestamp("2013-06-28", freq="BQ").is_quarter_end, 1), + (Timestamp("2013-06-28", freq="BQ").is_year_end, 0), + (Timestamp("2013-06-30", freq="BQS-APR").is_month_end, 0), + (Timestamp("2013-06-30", freq="BQS-APR").is_quarter_end, 0), + (Timestamp("2013-06-30", freq="BQS-APR").is_year_end, 0), + (Timestamp("2013-06-28", freq="BQS-APR").is_month_end, 1), + (Timestamp("2013-06-28", freq="BQS-APR").is_quarter_end, 1), + (Timestamp("2013-03-29", freq="BQS-APR").is_year_end, 1), + (Timestamp("2013-11-01", freq="AS-NOV").is_year_start, 1), + (Timestamp("2013-10-31", freq="AS-NOV").is_year_end, 1), + (Timestamp("2012-02-01").days_in_month, 29), + (Timestamp("2013-02-01").days_in_month, 28), + ] for ts, value in tests: assert ts == value diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 40a03396cf98e..da18cc44d5365 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -62,7 +62,12 @@ def test_dti_timestamp_fields(self, field): # extra fields from DatetimeIndex like quarter and week idx = tm.makeDateIndex(100) expected = getattr(idx, field)[-1] - result = getattr(Timestamp(idx[-1]), field) + + warn = FutureWarning if field.startswith("is_") else None + with tm.assert_produces_warning( + warn, match="Timestamp.freq is deprecated", check_stacklevel=False + ): + result = getattr(Timestamp(idx[-1]), field) assert result == expected def test_dti_timestamp_isocalendar_fields(self): @@ -75,8 +80,17 @@ def test_dti_timestamp_freq_fields(self): # extra fields from DatetimeIndex like quarter and week idx = tm.makeDateIndex(100) - assert idx.freq == Timestamp(idx[-1], idx.freq).freq - assert idx.freqstr == Timestamp(idx[-1], idx.freq).freqstr + msg = "The 'freq' argument in Timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + ts = Timestamp(idx[-1], idx.freq) + + msg2 = "Timestamp.freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg2): + assert idx.freq == ts.freq + + msg3 = "Timestamp.freqstr is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg3): + assert idx.freqstr == ts.freqstr # ---------------------------------------------------------------- # DatetimeIndex.round @@ -116,11 +130,11 @@ def test_round(self, tz_naive_fixture): expected_rng = DatetimeIndex( [ - Timestamp("2016-01-01 00:00:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 00:00:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 01:00:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 02:00:00", tz=tz, freq="30T"), - Timestamp("2016-01-01 02:00:00", tz=tz, freq="30T"), + Timestamp("2016-01-01 00:00:00", tz=tz), + Timestamp("2016-01-01 00:00:00", tz=tz), + Timestamp("2016-01-01 01:00:00", tz=tz), + Timestamp("2016-01-01 02:00:00", tz=tz), + Timestamp("2016-01-01 02:00:00", tz=tz), ] ) expected_elt = expected_rng[1] @@ -170,11 +184,11 @@ def test_no_rounding_occurs(self, tz_naive_fixture): expected_rng = DatetimeIndex( [ - Timestamp("2016-01-01 00:00:00", tz=tz, freq="2T"), - Timestamp("2016-01-01 00:02:00", tz=tz, freq="2T"), - Timestamp("2016-01-01 00:04:00", tz=tz, freq="2T"), - Timestamp("2016-01-01 00:06:00", tz=tz, freq="2T"), - Timestamp("2016-01-01 00:08:00", tz=tz, freq="2T"), + Timestamp("2016-01-01 00:00:00", tz=tz), + Timestamp("2016-01-01 00:02:00", tz=tz), + Timestamp("2016-01-01 00:04:00", tz=tz), + Timestamp("2016-01-01 00:06:00", tz=tz), + Timestamp("2016-01-01 00:08:00", tz=tz), ] ) diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 8bba11786e3e5..a12f4c9676d9b 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -591,8 +591,8 @@ def test_dti_construction_ambiguous_endpoint(self, tz): times = date_range( "2013-10-26 23:00", "2013-10-27 01:00", freq="H", tz=tz, ambiguous="infer" ) - assert times[0] == Timestamp("2013-10-26 23:00", tz=tz, freq="H") - assert times[-1] == Timestamp("2013-10-27 01:00:00+0000", tz=tz, freq="H") + assert times[0] == Timestamp("2013-10-26 23:00", tz=tz) + assert times[-1] == Timestamp("2013-10-27 01:00:00+0000", tz=tz) @pytest.mark.parametrize( "tz, option, expected", @@ -615,7 +615,7 @@ def test_dti_construction_nonexistent_endpoint(self, tz, option, expected): times = date_range( "2019-03-10 00:00", "2019-03-10 02:00", freq="H", tz=tz, nonexistent=option ) - assert times[-1] == Timestamp(expected, tz=tz, freq="H") + assert times[-1] == Timestamp(expected, tz=tz) def test_dti_tz_localize_bdate_range(self): dr = bdate_range("1/1/2009", "1/1/2010") diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index dcccd42c52c8c..a8a2055ffb093 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2069,8 +2069,8 @@ def test_loc_getitem_label_slice_across_dst(self): ) series2 = Series([0, 1, 2, 3, 4], index=idx) - t_1 = Timestamp("2017-10-29 02:30:00+02:00", tz="Europe/Berlin", freq="30min") - t_2 = Timestamp("2017-10-29 02:00:00+01:00", tz="Europe/Berlin", freq="30min") + t_1 = Timestamp("2017-10-29 02:30:00+02:00", tz="Europe/Berlin") + t_2 = Timestamp("2017-10-29 02:00:00+01:00", tz="Europe/Berlin") result = series2.loc[t_1:t_2] expected = Series([2, 3], index=idx[2:4]) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index bb3c7afd8ec34..7cf9d7e9a1925 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -23,6 +23,7 @@ import shutil from warnings import ( catch_warnings, + filterwarnings, simplefilter, ) import zipfile @@ -55,7 +56,10 @@ # TODO(ArrayManager) pickling -pytestmark = td.skip_array_manager_not_yet_implemented +pytestmark = [ + td.skip_array_manager_not_yet_implemented, + pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning"), +] @pytest.fixture(scope="module") @@ -63,7 +67,12 @@ def current_pickle_data(): # our current version pickle data from pandas.tests.io.generate_legacy_storage_files import create_pickle_data - return create_pickle_data() + with catch_warnings(): + filterwarnings( + "ignore", "The 'freq' argument in Timestamp", category=FutureWarning + ) + + return create_pickle_data() # --------------------- @@ -205,6 +214,7 @@ def python_unpickler(path): ), ], ) +@pytest.mark.filterwarnings("ignore:The 'freq' argument in Timestamp:FutureWarning") def test_round_trip_current(current_pickle_data, pickle_writer): data = current_pickle_data for typ, dv in data.items(): diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index a6d7d78ff3af2..2f698a82bac49 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -451,8 +451,8 @@ def test_numpy_minmax_range(self): def test_numpy_minmax_datetime64(self): dr = date_range(start="2016-01-15", end="2016-01-20") - assert np.min(dr) == Timestamp("2016-01-15 00:00:00", freq="D") - assert np.max(dr) == Timestamp("2016-01-20 00:00:00", freq="D") + assert np.min(dr) == Timestamp("2016-01-15 00:00:00") + assert np.max(dr) == Timestamp("2016-01-20 00:00:00") errmsg = "the 'out' parameter is not supported" with pytest.raises(ValueError, match=errmsg): diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index abe834b9fff17..5594659fb4b03 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1739,8 +1739,8 @@ def test_get_timestamp_range_edges(first, last, freq, exp_first, exp_last): last = Period(last) last = last.to_timestamp(last.freq) - exp_first = Timestamp(exp_first, freq=freq) - exp_last = Timestamp(exp_last, freq=freq) + exp_first = Timestamp(exp_first) + exp_last = Timestamp(exp_last) freq = pd.tseries.frequencies.to_offset(freq) result = _get_timestamp_range_edges(first, last, freq) diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py index 0a1ba17949ddb..c4fe16b43313a 100644 --- a/pandas/tests/reshape/concat/test_datetimes.py +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -403,6 +403,7 @@ def test_concat_multiple_tzs(self): expected = DataFrame({"time": [ts2, ts3]}) tm.assert_frame_equal(results, expected) + @pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning") def test_concat_multiindex_with_tz(self): # GH 6606 df = DataFrame( diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 63e277c1580af..97e933e9821af 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -516,6 +516,7 @@ def test_pivot_index_with_nan(self, method): result = pd.pivot(df, "b", "a", "c") tm.assert_frame_equal(result, pv.T) + @pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning") @pytest.mark.parametrize("method", [True, False]) def test_pivot_with_tz(self, method): # GH 5878 diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index e178b31b9ae93..fd46954fd4c71 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -36,7 +36,7 @@ def test_overflow_offset_raises(self): # xref https://github.com/statsmodels/statsmodels/issues/3374 # ends up multiplying really large numbers which overflow - stamp = Timestamp("2017-01-13 00:00:00", freq="D") + stamp = Timestamp("2017-01-13 00:00:00") offset_overflow = 20169940 * offsets.Day(1) msg = ( "the add operation between " @@ -116,7 +116,9 @@ def test_addition_subtraction_types(self): td = timedelta(seconds=1) # build a timestamp with a frequency, since then it supports # addition/subtraction of integers - ts = Timestamp(dt, freq="D") + with tm.assert_produces_warning(FutureWarning, match="The 'freq' argument"): + # freq deprecated + ts = Timestamp(dt, freq="D") msg = "Addition/subtraction of integers" with pytest.raises(TypeError, match=msg): @@ -148,6 +150,8 @@ def test_addition_subtraction_types(self): ("M", None, np.timedelta64(1, "M")), ], ) + @pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning") + @pytest.mark.filterwarnings("ignore:The 'freq' argument:FutureWarning") def test_addition_subtraction_preserve_frequency(self, freq, td, td64): ts = Timestamp("2014-03-05 00:00:00", freq=freq) original_freq = ts.freq @@ -189,8 +193,8 @@ def test_timestamp_add_timedelta64_unit(self, other, expected_difference): @pytest.mark.parametrize( "ts", [ - Timestamp("1776-07-04", freq="D"), - Timestamp("1776-07-04", tz="UTC", freq="D"), + Timestamp("1776-07-04"), + Timestamp("1776-07-04", tz="UTC"), ], ) @pytest.mark.parametrize( diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index 83e40aa5cb96b..16ce51a88340e 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -19,6 +19,7 @@ Timestamp, compat, ) +import pandas._testing as tm from pandas.tseries import offsets @@ -195,11 +196,13 @@ def test_constructor_invalid_tz(self): Timestamp("2017-10-22", tzinfo=pytz.utc, tz="UTC") msg = "Invalid frequency:" + msg2 = "The 'freq' argument" with pytest.raises(ValueError, match=msg): # GH#5168 # case where user tries to pass tz as an arg, not kwarg, gets # interpreted as a `freq` - Timestamp("2012-01-01", "US/Pacific") + with tm.assert_produces_warning(FutureWarning, match=msg2): + Timestamp("2012-01-01", "US/Pacific") def test_constructor_strptime(self): # GH25016 @@ -287,6 +290,8 @@ def test_constructor_keyword(self): == repr(Timestamp("2015-11-12 01:02:03.999999")) ) + @pytest.mark.filterwarnings("ignore:Timestamp.freq is:FutureWarning") + @pytest.mark.filterwarnings("ignore:The 'freq' argument:FutureWarning") def test_constructor_fromordinal(self): base = datetime(2000, 1, 1) @@ -523,15 +528,18 @@ def test_construct_with_different_string_format(self, arg): def test_construct_timestamp_preserve_original_frequency(self): # GH 22311 - result = Timestamp(Timestamp("2010-08-08", freq="D")).freq + with tm.assert_produces_warning(FutureWarning, match="The 'freq' argument"): + result = Timestamp(Timestamp("2010-08-08", freq="D")).freq expected = offsets.Day() assert result == expected def test_constructor_invalid_frequency(self): # GH 22311 msg = "Invalid frequency:" + msg2 = "The 'freq' argument" with pytest.raises(ValueError, match=msg): - Timestamp("2012-01-01", freq=[]) + with tm.assert_produces_warning(FutureWarning, match=msg2): + Timestamp("2012-01-01", freq=[]) @pytest.mark.parametrize("box", [datetime, Timestamp]) def test_raise_tz_and_tzinfo_in_datetime_input(self, box): diff --git a/pandas/tests/scalar/timestamp/test_rendering.py b/pandas/tests/scalar/timestamp/test_rendering.py index a27d233d5ab88..2f88f96b6bbea 100644 --- a/pandas/tests/scalar/timestamp/test_rendering.py +++ b/pandas/tests/scalar/timestamp/test_rendering.py @@ -4,6 +4,7 @@ import pytz # noqa # a test below uses pytz but only inside a `eval` call from pandas import Timestamp +import pandas._testing as tm class TestTimestampRendering: @@ -35,17 +36,26 @@ def test_repr(self, date, freq, tz): assert freq_repr not in repr(date_tz) assert date_tz == eval(repr(date_tz)) - date_freq = Timestamp(date, freq=freq) + msg = "The 'freq' argument in Timestamp" + with tm.assert_produces_warning(FutureWarning, match=msg): + date_freq = Timestamp(date, freq=freq) assert date in repr(date_freq) assert tz_repr not in repr(date_freq) assert freq_repr in repr(date_freq) - assert date_freq == eval(repr(date_freq)) + with tm.assert_produces_warning( + FutureWarning, match=msg, check_stacklevel=False + ): + assert date_freq == eval(repr(date_freq)) - date_tz_freq = Timestamp(date, tz=tz, freq=freq) + with tm.assert_produces_warning(FutureWarning, match=msg): + date_tz_freq = Timestamp(date, tz=tz, freq=freq) assert date in repr(date_tz_freq) assert tz_repr in repr(date_tz_freq) assert freq_repr in repr(date_tz_freq) - assert date_tz_freq == eval(repr(date_tz_freq)) + with tm.assert_produces_warning( + FutureWarning, match=msg, check_stacklevel=False + ): + assert date_tz_freq == eval(repr(date_tz_freq)) def test_repr_utcoffset(self): # This can cause the tz field to be populated, but it's redundant to diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 54f3f21dc9f6f..e13242e60e3a3 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -35,13 +35,44 @@ class TestTimestampProperties: + def test_freq_deprecation(self): + # GH#41586 + msg = "The 'freq' argument in Timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + # warning issued at construction + ts = Timestamp("2021-06-01", freq="D") + ts2 = Timestamp("2021-06-01", freq="B") + + msg = "Timestamp.freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + # warning issued at attribute lookup + ts.freq + + for per in ["month", "quarter", "year"]: + for side in ["start", "end"]: + attr = f"is_{per}_{side}" + + with tm.assert_produces_warning(FutureWarning, match=msg): + getattr(ts2, attr) + + # is_(month|quarter|year)_(start|end) does _not_ issue a warning + # with freq="D" bc the result will be unaffected by the deprecation + with tm.assert_produces_warning(None): + getattr(ts, attr) + + @pytest.mark.filterwarnings("ignore:The 'freq' argument:FutureWarning") + @pytest.mark.filterwarnings("ignore:Timestamp.freq is deprecated:FutureWarning") def test_properties_business(self): ts = Timestamp("2017-10-01", freq="B") control = Timestamp("2017-10-01") assert ts.dayofweek == 6 assert ts.day_of_week == 6 assert not ts.is_month_start # not a weekday + assert not ts.freq.is_month_start(ts) + assert ts.freq.is_month_start(ts + Timedelta(days=1)) assert not ts.is_quarter_start # not a weekday + assert not ts.freq.is_quarter_start(ts) + assert ts.freq.is_quarter_start(ts + Timedelta(days=1)) # Control case: non-business is month/qtr start assert control.is_month_start assert control.is_quarter_start @@ -51,7 +82,11 @@ def test_properties_business(self): assert ts.dayofweek == 5 assert ts.day_of_week == 5 assert not ts.is_month_end # not a weekday + assert not ts.freq.is_month_end(ts) + assert ts.freq.is_month_end(ts - Timedelta(days=1)) assert not ts.is_quarter_end # not a weekday + assert not ts.freq.is_quarter_end(ts) + assert ts.freq.is_quarter_end(ts - Timedelta(days=1)) # Control case: non-business is month/qtr start assert control.is_month_end assert control.is_quarter_end @@ -398,10 +433,12 @@ def test_hash_equivalent(self): def test_tz_conversion_freq(self, tz_naive_fixture): # GH25241 - t1 = Timestamp("2019-01-01 10:00", freq="H") - assert t1.tz_localize(tz=tz_naive_fixture).freq == t1.freq - t2 = Timestamp("2019-01-02 12:00", tz="UTC", freq="T") - assert t2.tz_convert(tz="UTC").freq == t2.freq + with tm.assert_produces_warning(FutureWarning, match="freq"): + t1 = Timestamp("2019-01-01 10:00", freq="H") + assert t1.tz_localize(tz=tz_naive_fixture).freq == t1.freq + with tm.assert_produces_warning(FutureWarning, match="freq"): + t2 = Timestamp("2019-01-02 12:00", tz="UTC", freq="T") + assert t2.tz_convert(tz="UTC").freq == t2.freq class TestTimestampNsOperations: @@ -513,26 +550,26 @@ def test_to_pydatetime_nonzero_nano(self): assert result == expected def test_timestamp_to_datetime(self): - stamp = Timestamp("20090415", tz="US/Eastern", freq="D") + stamp = Timestamp("20090415", tz="US/Eastern") dtval = stamp.to_pydatetime() assert stamp == dtval assert stamp.tzinfo == dtval.tzinfo def test_timestamp_to_datetime_dateutil(self): - stamp = Timestamp("20090415", tz="dateutil/US/Eastern", freq="D") + stamp = Timestamp("20090415", tz="dateutil/US/Eastern") dtval = stamp.to_pydatetime() assert stamp == dtval assert stamp.tzinfo == dtval.tzinfo def test_timestamp_to_datetime_explicit_pytz(self): - stamp = Timestamp("20090415", tz=pytz.timezone("US/Eastern"), freq="D") + stamp = Timestamp("20090415", tz=pytz.timezone("US/Eastern")) dtval = stamp.to_pydatetime() assert stamp == dtval assert stamp.tzinfo == dtval.tzinfo @td.skip_if_windows_python_3 def test_timestamp_to_datetime_explicit_dateutil(self): - stamp = Timestamp("20090415", tz=gettz("US/Eastern"), freq="D") + stamp = Timestamp("20090415", tz=gettz("US/Eastern")) dtval = stamp.to_pydatetime() assert stamp == dtval assert stamp.tzinfo == dtval.tzinfo diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index fed9c72d62fa0..56af003c59bf5 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -987,13 +987,9 @@ def test_constructor_with_datetime_tz(self): # indexing result = s.iloc[0] - assert result == Timestamp( - "2013-01-01 00:00:00-0500", tz="US/Eastern", freq="D" - ) + assert result == Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern") result = s[0] - assert result == Timestamp( - "2013-01-01 00:00:00-0500", tz="US/Eastern", freq="D" - ) + assert result == Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern") result = s[Series([True, True, False], index=s.index)] tm.assert_series_equal(result, s[0:2])
- [x] closes #15146 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry This in turn will allow us to remove DatetimeArray.freq and TimedeltaArray.freq, which is needed for #31218
https://api.github.com/repos/pandas-dev/pandas/pulls/41586
2021-05-20T17:15:39Z
2021-06-07T16:47:34Z
2021-06-07T16:47:33Z
2021-07-01T16:21:20Z
Deprecate non-keyword arguments in mask
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 645443c450146..f9a18330d1923 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -680,6 +680,7 @@ Deprecations - Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`) - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) - Deprecated passing arguments as positional in :meth:`Index.set_names` and :meth:`MultiIndex.set_names` (except for ``names``) (:issue:`41485`) +- Deprecated passing arguments (apart from ``cond`` and ``other``) as positional in :meth:`DataFrame.mask` and :meth:`Series.mask` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1d45581fa5047..6e71cb49596c8 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10720,6 +10720,21 @@ def where( ): return super().where(cond, other, inplace, axis, level, errors, try_cast) + @deprecate_nonkeyword_arguments( + version=None, allowed_args=["self", "cond", "other"] + ) + def mask( + self, + cond, + other=np.nan, + inplace=False, + axis=None, + level=None, + errors="raise", + try_cast=lib.no_default, + ): + return super().mask(cond, other, inplace, axis, level, errors, try_cast) + DataFrame._add_numeric_operations() diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3e6642d3b1a72..49dc71954fd8f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9062,7 +9062,7 @@ def mask( "try_cast keyword is deprecated and will be removed in a " "future version", FutureWarning, - stacklevel=2, + stacklevel=4, ) # see gh-21891 diff --git a/pandas/core/series.py b/pandas/core/series.py index 871b7fb4f9f95..2f45a2adbdec7 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5366,6 +5366,21 @@ def where( ): return super().where(cond, other, inplace, axis, level, errors, try_cast) + @deprecate_nonkeyword_arguments( + version=None, allowed_args=["self", "cond", "other"] + ) + def mask( + self, + cond, + other=np.nan, + inplace=False, + axis=None, + level=None, + errors="raise", + try_cast=lib.no_default, + ): + return super().mask(cond, other, inplace, axis, level, errors, try_cast) + # ---------------------------------------------------------------------- # Add index _AXIS_ORDERS = ["index"] diff --git a/pandas/tests/frame/indexing/test_mask.py b/pandas/tests/frame/indexing/test_mask.py index 364475428e529..ac80426883dd5 100644 --- a/pandas/tests/frame/indexing/test_mask.py +++ b/pandas/tests/frame/indexing/test_mask.py @@ -90,6 +90,19 @@ def test_mask_dtype_bool_conversion(self): result = bools.mask(mask) tm.assert_frame_equal(result, expected) + def test_mask_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": range(5)}) + expected = DataFrame({"a": [-1, 1, -1, 3, -1]}) + cond = df % 2 == 0 + msg = ( + r"In a future version of pandas all arguments of DataFrame.mask except for " + r"the arguments 'cond' and 'other' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.mask(cond, -1, False) + tm.assert_frame_equal(result, expected) + def test_mask_try_cast_deprecated(frame_or_series): diff --git a/pandas/tests/series/indexing/test_mask.py b/pandas/tests/series/indexing/test_mask.py index a4dda3a5c0c5b..30a9d925ed7e5 100644 --- a/pandas/tests/series/indexing/test_mask.py +++ b/pandas/tests/series/indexing/test_mask.py @@ -86,3 +86,17 @@ def test_mask_stringdtype(): dtype=StringDtype(), ) tm.assert_series_equal(result, expected) + + +def test_mask_pos_args_deprecation(): + # https://github.com/pandas-dev/pandas/issues/41485 + s = Series(range(5)) + expected = Series([-1, 1, -1, 3, -1]) + cond = s % 2 == 0 + msg = ( + r"In a future version of pandas all arguments of Series.mask except for " + r"the arguments 'cond' and 'other' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.mask(cond, -1, False) + tm.assert_series_equal(result, expected)
- [x] xref #41485 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41580
2021-05-20T07:46:31Z
2021-05-27T14:43:51Z
2021-05-27T14:43:51Z
2021-05-27T15:36:06Z
BUG: Series(range_obj_outside_i8_bounds)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c26f8288f59ab..cfc5ac329a847 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -1008,6 +1008,7 @@ Other - Bug in :meth:`DataFrame.agg()` not sorting the aggregated axis in the order of the provided aggragation functions when one or more aggregation function fails to produce results (:issue:`33634`) - Bug in :meth:`DataFrame.clip` not interpreting missing values as no threshold (:issue:`40420`) - Bug in :class:`Series` backed by :class:`DatetimeArray` or :class:`TimedeltaArray` sometimes failing to set the array's ``freq`` to ``None`` (:issue:`41425`) +- Bug in creating a :class:`Series` from a ``range`` object that does not fit in the bounds of ``int64`` dtype (:issue:`30173`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/construction.py b/pandas/core/construction.py index e83aa02f25ada..b8828f838b94c 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -502,7 +502,7 @@ def sanitize_array( data = lib.item_from_zerodim(data) elif isinstance(data, range): # GH#16804 - data = np.arange(data.start, data.stop, data.step, dtype="int64") + data = range_to_ndarray(data) copy = False if not is_list_like(data): @@ -569,6 +569,25 @@ def sanitize_array( return subarr +def range_to_ndarray(rng: range) -> np.ndarray: + """ + Cast a range object to ndarray. + """ + # GH#30171 perf avoid realizing range as a list in np.array + try: + arr = np.arange(rng.start, rng.stop, rng.step, dtype="int64") + except OverflowError: + # GH#30173 handling for ranges that overflow int64 + if (rng.start >= 0 and rng.step > 0) or (rng.stop >= 0 and rng.step < 0): + try: + arr = np.arange(rng.start, rng.stop, rng.step, dtype="uint64") + except OverflowError: + arr = construct_1d_object_array_from_listlike(list(rng)) + else: + arr = construct_1d_object_array_from_listlike(list(rng)) + return arr + + def _sanitize_ndim( result: ArrayLike, data, dtype: DtypeObj | None, index: Index | None ) -> ArrayLike: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 5e58f6148e6ad..5c2bed109e3bf 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -66,6 +66,7 @@ from pandas.core.construction import ( ensure_wrapped_if_datetimelike, extract_array, + range_to_ndarray, sanitize_array, ) from pandas.core.indexes import base as ibase @@ -530,7 +531,7 @@ def _prep_ndarray(values, copy: bool = True) -> np.ndarray: if len(values) == 0: return np.empty((0, 0), dtype=object) elif isinstance(values, range): - arr = np.arange(values.start, values.stop, values.step, dtype="int64") + arr = range_to_ndarray(values) return arr[..., np.newaxis] def convert(v): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index e74d900d1b04d..0e1c98e381ff7 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1525,6 +1525,36 @@ def test_constructor_range_dtype(self, dtype): result = Series(range(5), dtype=dtype) tm.assert_series_equal(result, expected) + def test_constructor_range_overflows(self): + # GH#30173 range objects that overflow int64 + rng = range(2 ** 63, 2 ** 63 + 4) + ser = Series(rng) + expected = Series(list(rng)) + tm.assert_series_equal(ser, expected) + assert list(ser) == list(rng) + assert ser.dtype == np.uint64 + + rng2 = range(2 ** 63 + 4, 2 ** 63, -1) + ser2 = Series(rng2) + expected2 = Series(list(rng2)) + tm.assert_series_equal(ser2, expected2) + assert list(ser2) == list(rng2) + assert ser2.dtype == np.uint64 + + rng3 = range(-(2 ** 63), -(2 ** 63) - 4, -1) + ser3 = Series(rng3) + expected3 = Series(list(rng3)) + tm.assert_series_equal(ser3, expected3) + assert list(ser3) == list(rng3) + assert ser3.dtype == object + + rng4 = range(2 ** 73, 2 ** 73 + 4) + ser4 = Series(rng4) + expected4 = Series(list(rng4)) + tm.assert_series_equal(ser4, expected4) + assert list(ser4) == list(rng4) + assert ser4.dtype == object + def test_constructor_tz_mixed_data(self): # GH 13051 dt_list = [
- [x] closes #30173 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41579
2021-05-20T03:23:38Z
2021-05-24T18:20:49Z
2021-05-24T18:20:48Z
2021-05-24T19:02:59Z
BUG: DataFrame(floatdata, dtype=inty) does unsafe casting
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1eb22436204a8..bc74b2722d29c 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -808,6 +808,7 @@ Missing - Bug in :func:`isna`, and :meth:`Series.isna`, :meth:`Index.isna`, :meth:`DataFrame.isna` (and the corresponding ``notna`` functions) not recognizing ``Decimal("NaN")`` objects (:issue:`39409`) - Bug in :meth:`DataFrame.fillna` not accepting dictionary for ``downcast`` keyword (:issue:`40809`) - Bug in :func:`isna` not returning a copy of the mask for nullable types, causing any subsequent mask modification to change the original array (:issue:`40935`) +- Bug in :class:`DataFrame` construction with float data containing ``NaN`` and an integer ``dtype`` casting instead of retaining the ``NaN`` (:issue:`26919`) MultiIndex ^^^^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 94cffe8fb840d..b4bdb2f9c4b53 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -40,6 +40,7 @@ DtypeObj, Scalar, ) +from pandas.errors import IntCastingNaNError from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg @@ -1167,9 +1168,7 @@ def astype_nansafe( raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]") elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer): - - if not np.isfinite(arr).all(): - raise ValueError("Cannot convert non-finite values (NA or inf) to integer") + return astype_float_to_int_nansafe(arr, dtype, copy) elif is_object_dtype(arr): @@ -1207,6 +1206,19 @@ def astype_nansafe( return arr.astype(dtype, copy=copy) +def astype_float_to_int_nansafe( + values: np.ndarray, dtype: np.dtype, copy: bool +) -> np.ndarray: + """ + astype with a check preventing converting NaN to an meaningless integer value. + """ + if not np.isfinite(values).all(): + raise IntCastingNaNError( + "Cannot convert non-finite values (NA or inf) to integer" + ) + return values.astype(dtype, copy=copy) + + def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> ArrayLike: """ Cast array (ndarray or ExtensionArray) to the new dtype. @@ -1946,6 +1958,17 @@ def construct_1d_ndarray_preserving_na( ): # TODO(numpy#12550): special-case can be removed subarr = construct_1d_object_array_from_listlike(list(values)) + elif ( + dtype is not None + and dtype.kind in ["i", "u"] + and isinstance(values, np.ndarray) + and values.dtype.kind == "f" + ): + # Argument 2 to "astype_float_to_int_nansafe" has incompatible + # type "Union[dtype[Any], ExtensionDtype]"; expected "dtype[Any]" + return astype_float_to_int_nansafe( + values, dtype, copy=copy # type: ignore[arg-type] + ) else: # error: Argument "dtype" to "array" has incompatible type # "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[dtype[Any], diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 06d30d6ed72e8..6baa1072a0396 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -21,6 +21,7 @@ DtypeObj, Manager, ) +from pandas.errors import IntCastingNaNError from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -315,10 +316,11 @@ def ndarray_to_mgr( values = construct_1d_ndarray_preserving_na( flat, dtype=dtype, copy=False ) - except Exception as err: - # e.g. ValueError when trying to cast object dtype to float64 - msg = f"failed to cast to '{dtype}' (Exception was: {err})" - raise ValueError(msg) from err + except IntCastingNaNError: + # following Series, we ignore the dtype and retain floating + # values instead of casting nans to meaningless ints + pass + values = values.reshape(shape) # _prep_ndarray ensures that values.ndim == 2 at this point diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index a0f6ddfd84d7b..92516a1609f10 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -12,6 +12,15 @@ ) +class IntCastingNaNError(ValueError): + """ + raised when attempting an astype operation on an array with NaN to an integer + dtype. + """ + + pass + + class NullFrequencyError(ValueError): """ Error raised when a null `freq` attribute is used in an operation diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 6e9991ff17ac3..94cb85a0945f2 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -66,6 +66,18 @@ class TestDataFrameConstructors: + def test_construct_ndarray_with_nas_and_int_dtype(self): + # GH#26919 match Series by not casting np.nan to meaningless int + arr = np.array([[1, np.nan], [2, 3]]) + df = DataFrame(arr, dtype="i8") + assert df.values.dtype == arr.dtype + assert isna(df.iloc[0, 1]) + + # check this matches Series behavior + ser = Series(arr[0], dtype="i8", name=0) + expected = df.iloc[0] + tm.assert_series_equal(ser, expected) + def test_construct_from_list_of_datetimes(self): df = DataFrame([datetime.now(), datetime.now()]) assert df[0].dtype == np.dtype("M8[ns]") @@ -851,9 +863,17 @@ def _check_basic_constructor(self, empty): assert len(frame.index) == 3 assert len(frame.columns) == 1 - # cast type frame = DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64) - assert frame.values.dtype == np.int64 + if empty is np.ones: + # passing dtype casts + assert frame.values.dtype == np.int64 + else: + # i.e. ma.masked_all + # Since we have NaNs, refuse to cast to int dtype, which would take NaN + # to meaningless integers. This matches Series behavior. GH#26919 + assert frame.isna().all().all() + assert frame.values.dtype == np.float64 + assert isna(frame.values).all() # wrong size axis labels msg = r"Shape of passed values is \(2, 3\), indices imply \(1, 3\)"
- [x] closes #26919 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41578
2021-05-20T01:06:50Z
2021-05-21T15:45:13Z
2021-05-21T15:45:13Z
2021-05-21T15:54:04Z
DOC: fixup docstring of deprecate_nonkeyword_arguments
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index f4c360f476514..fb073b1d3d039 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -267,7 +267,7 @@ def deprecate_nonkeyword_arguments( Parameters ---------- - version : str + version : str, optional The version in which positional arguments will become keyword-only. If None, then the warning message won't specify any particular version.
- [ ] closes #41553 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41577
2021-05-20T00:29:31Z
2021-05-24T17:19:50Z
2021-05-24T17:19:50Z
2021-05-24T17:20:47Z
DEPS: clean outdated version compat, sync min versions
diff --git a/ci/deps/actions-37-db-min.yaml b/ci/deps/actions-37-db-min.yaml index 65c4c5769b1a3..cae4361ca37a7 100644 --- a/ci/deps/actions-37-db-min.yaml +++ b/ci/deps/actions-37-db-min.yaml @@ -6,7 +6,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-37-db.yaml index fa58f412cebf4..e568f8615a8df 100644 --- a/ci/deps/actions-37-db.yaml +++ b/ci/deps/actions-37-db.yaml @@ -6,7 +6,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-xdist>=1.21 - hypothesis>=3.58.0 - pytest-cov>=2.10.1 # this is only needed in the coverage build, ref: GH 35737 @@ -25,7 +25,7 @@ dependencies: - flask - nomkl - numexpr - - numpy=1.16.* + - numpy=1.17.* - odfpy - openpyxl - pandas-gbq diff --git a/ci/deps/actions-37-locale_slow.yaml b/ci/deps/actions-37-locale_slow.yaml index d9ad1f538908e..c6eb3b00a63ac 100644 --- a/ci/deps/actions-37-locale_slow.yaml +++ b/ci/deps/actions-37-locale_slow.yaml @@ -7,7 +7,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 @@ -17,13 +17,13 @@ dependencies: - bottleneck=1.2.* - lxml - matplotlib=3.0.0 - - numpy=1.16.* + - numpy=1.17.* - openpyxl=3.0.0 - python-dateutil - python-blosc - pytz=2017.3 - scipy - - sqlalchemy=1.2.8 + - sqlalchemy=1.3.0 - xlrd=1.2.0 - xlsxwriter=1.0.2 - xlwt=1.3.0 diff --git a/ci/deps/actions-37-slow.yaml b/ci/deps/actions-37-slow.yaml index 573ff7f02c162..166f2237dcad3 100644 --- a/ci/deps/actions-37-slow.yaml +++ b/ci/deps/actions-37-slow.yaml @@ -7,7 +7,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/actions-37.yaml b/ci/deps/actions-37.yaml index a209a9099d2bb..0effe6f80df86 100644 --- a/ci/deps/actions-37.yaml +++ b/ci/deps/actions-37.yaml @@ -7,7 +7,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/actions-38-locale.yaml b/ci/deps/actions-38-locale.yaml index 629804c71e726..34a6860936550 100644 --- a/ci/deps/actions-38-locale.yaml +++ b/ci/deps/actions-38-locale.yaml @@ -6,7 +6,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - pytest-asyncio>=0.12.0 @@ -20,7 +20,7 @@ dependencies: - jinja2 - jedi<0.18.0 - lxml - - matplotlib <3.3.0 + - matplotlib<3.3.0 - moto - nomkl - numexpr diff --git a/ci/deps/actions-38-numpydev.yaml b/ci/deps/actions-38-numpydev.yaml index e7ee6ccfd7bac..1c1ea582a3454 100644 --- a/ci/deps/actions-38-numpydev.yaml +++ b/ci/deps/actions-38-numpydev.yaml @@ -5,7 +5,7 @@ dependencies: - python=3.8.* # tools - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/actions-38-slow.yaml b/ci/deps/actions-38-slow.yaml index 2106f48755560..afba60e451b90 100644 --- a/ci/deps/actions-38-slow.yaml +++ b/ci/deps/actions-38-slow.yaml @@ -6,7 +6,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml index e2660d07c3558..11daa92046eb4 100644 --- a/ci/deps/actions-38.yaml +++ b/ci/deps/actions-38.yaml @@ -7,7 +7,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index 36e8bf528fc3e..b74f1af8ee0f6 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -6,7 +6,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-cov - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml index a0b1cdc684d2c..63e858eac433f 100644 --- a/ci/deps/azure-macos-37.yaml +++ b/ci/deps/azure-macos-37.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.7.* # tools - - pytest>=5.0.1 + - pytest>=6.0 - pytest-xdist>=1.21 - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 8266e3bc4d07d..5cbc029f8c03d 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -7,7 +7,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-xdist>=1.21 - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml index 200e695a69d1f..7fdecae626f9d 100644 --- a/ci/deps/azure-windows-38.yaml +++ b/ci/deps/azure-windows-38.yaml @@ -7,7 +7,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-xdist>=1.21 - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/travis-37-arm64.yaml b/ci/deps/travis-37-arm64.yaml index 8df6104f43a50..995ebda1f97e7 100644 --- a/ci/deps/travis-37-arm64.yaml +++ b/ci/deps/travis-37-arm64.yaml @@ -6,7 +6,7 @@ dependencies: # tools - cython>=0.29.21 - - pytest>=5.0.1 + - pytest>=6.0 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c26f8288f59ab..be7eb466a37e0 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -615,7 +615,7 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+---------+ | scipy | 1.2.0 | | +-----------------+-----------------+---------+ -| sqlalchemy | 1.2.8 | | +| sqlalchemy | 1.3.0 | X | +-----------------+-----------------+---------+ | tabulate | 0.8.7 | X | +-----------------+-----------------+---------+ diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 2c184c38e6b1a..941c59592dbbd 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -22,11 +22,11 @@ "openpyxl": "3.0.0", "pandas_gbq": "0.12.0", "pyarrow": "0.17.0", - "pytest": "5.0.1", + "pytest": "6.0", "pyxlsb": "1.0.6", "s3fs": "0.4.0", "scipy": "1.2.0", - "sqlalchemy": "1.2.8", + "sqlalchemy": "1.3.0", "tables": "3.5.1", "tabulate": "0.8.7", "xarray": "0.12.3", diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index 63ea5554e32d7..69dc3ac417510 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -22,10 +22,7 @@ Union, ) -from numpy import ( - __version__, - ndarray, -) +from numpy import ndarray from pandas._libs.lib import ( is_bool, @@ -38,8 +35,6 @@ validate_kwargs, ) -from pandas.util.version import Version - class CompatValidator: def __init__( @@ -128,10 +123,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs): ARGSORT_DEFAULTS["axis"] = -1 ARGSORT_DEFAULTS["kind"] = "quicksort" ARGSORT_DEFAULTS["order"] = None - -if Version(__version__) >= Version("1.17.0"): - # GH-26361. NumPy added radix sort and changed default to None. - ARGSORT_DEFAULTS["kind"] = None +ARGSORT_DEFAULTS["kind"] = None validate_argsort = CompatValidator( diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index d5ee28eb7017e..4370f3a4e15cf 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -26,6 +26,7 @@ pa_version_under3p0, pa_version_under4p0, ) +from pandas.compat.pyarrow import pa_version_under1p0 from pandas.util._decorators import doc from pandas.util._validators import validate_fillna_kwargs @@ -52,7 +53,6 @@ validate_indices, ) from pandas.core.strings.object_array import ObjectStringArrayMixin -from pandas.util.version import Version try: import pyarrow as pa @@ -62,7 +62,7 @@ # PyArrow backed StringArrays are available starting at 1.0.0, but this # file is imported from even if pyarrow is < 1.0.0, before pyarrow.compute # and its compute functions existed. GH38801 - if Version(pa.__version__) >= Version("1.0.0"): + if not pa_version_under1p0: import pyarrow.compute as pc ARROW_CMP_FUNCS = { @@ -232,7 +232,7 @@ def __init__(self, values): def _chk_pyarrow_available(cls) -> None: # TODO: maybe update import_optional_dependency to allow a minimum # version to be specified rather than use the global minimum - if pa is None or Version(pa.__version__) < Version("1.0.0"): + if pa is None or pa_version_under1p0: msg = "pyarrow>=1.0.0 is required for PyArrow backed StringArray." raise ImportError(msg) diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 34d5edee06791..bccf3c3f1011b 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -210,27 +210,21 @@ def read( to_pandas_kwargs = {} if use_nullable_dtypes: - if Version(self.api.__version__) >= Version("0.16"): - import pandas as pd - - mapping = { - self.api.int8(): pd.Int8Dtype(), - self.api.int16(): pd.Int16Dtype(), - self.api.int32(): pd.Int32Dtype(), - self.api.int64(): pd.Int64Dtype(), - self.api.uint8(): pd.UInt8Dtype(), - self.api.uint16(): pd.UInt16Dtype(), - self.api.uint32(): pd.UInt32Dtype(), - self.api.uint64(): pd.UInt64Dtype(), - self.api.bool_(): pd.BooleanDtype(), - self.api.string(): pd.StringDtype(), - } - to_pandas_kwargs["types_mapper"] = mapping.get - else: - raise ValueError( - "'use_nullable_dtypes=True' is only supported for pyarrow >= 0.16 " - f"({self.api.__version__} is installed" - ) + import pandas as pd + + mapping = { + self.api.int8(): pd.Int8Dtype(), + self.api.int16(): pd.Int16Dtype(), + self.api.int32(): pd.Int32Dtype(), + self.api.int64(): pd.Int64Dtype(), + self.api.uint8(): pd.UInt8Dtype(), + self.api.uint16(): pd.UInt16Dtype(), + self.api.uint32(): pd.UInt32Dtype(), + self.api.uint64(): pd.UInt64Dtype(), + self.api.bool_(): pd.BooleanDtype(), + self.api.string(): pd.StringDtype(), + } + to_pandas_kwargs["types_mapper"] = mapping.get manager = get_option("mode.data_manager") if manager == "array": to_pandas_kwargs["split_blocks"] = True # type: ignore[assignment]
numpy: #40851 sqlalchemy: #38344. pytest: #40656
https://api.github.com/repos/pandas-dev/pandas/pulls/41576
2021-05-20T00:13:36Z
2021-05-24T18:41:53Z
2021-05-24T18:41:53Z
2022-11-18T02:21:35Z
[ArrowStringArray] PERF: bypass some padding code in _wrap_result
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 43df34a7ecbb2..30b2f0e377c12 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -284,7 +284,7 @@ def cons_row(x): return [x] result = [cons_row(x) for x in result] - if result: + if result and not self._is_string: # propagate nan values to match longest sequence (GH 18450) max_len = max(len(x) for x in result) result = [
The padding of np.nan across all columns is not needed for StringArray/ArrowStringArray ``` before after ratio [896256ee] [1c883e0d] <master> <bypass> - 99.3±0.6ms 87.4±1ms 0.88 strings.Split.time_split('string', True) - 89.6±0.3ms 78.7±1ms 0.88 strings.Split.time_rsplit('arrow_string', True) - 71.3±0.5ms 58.7±0.8ms 0.82 strings.Split.time_rsplit('string', True) - 60.0±0.4ms 49.1±1ms 0.82 strings.Methods.time_partition('arrow_string') - 59.0±0.7ms 47.5±1ms 0.80 strings.Methods.time_rpartition('arrow_string') - 50.5±0.08ms 38.3±0.4ms 0.76 strings.Methods.time_partition('string') - 49.5±0.3ms 37.2±0.2ms 0.75 strings.Methods.time_rpartition('string') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ``` this is a small change for perf. The padding code logic does not work for st.extract since the first value of a list maybe np.nan followed by other values. I made that change here and then reverted as is moreless perf neutral. so will do in another PR that uses _wrap_result more for str_extract. (str.extract returns list of lists where any value in the list could be np.nan, str.split returns array of lists with different lengths without np.nans and the np.nans returned as scalars) some further gains can also be achieved by bypassing the converting of `np.nan` to `[np.nan]` for partition (for StringArray/ArrowStringArray) since the DataFrame constructor does not need this for a list of tuples. (str.partition returns array of tuples, str.split returns array of lists) #41507
https://api.github.com/repos/pandas-dev/pandas/pulls/41567
2021-05-19T12:07:18Z
2021-05-21T16:47:43Z
2021-05-21T16:47:42Z
2021-05-21T16:55:02Z
DOC: redocument the `subset` arg in styler for clarity of use
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index a96196a698f43..3a83d50884017 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -614,9 +614,10 @@ def apply( Apply to each column (``axis=0`` or ``'index'``), to each row (``axis=1`` or ``'columns'``), or to the entire DataFrame at once with ``axis=None``. - subset : IndexSlice - A valid indexer to limit ``data`` to *before* applying the - function. Consider using a pandas.IndexSlice. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. **kwargs : dict Pass along to ``func``. @@ -642,10 +643,20 @@ def apply( -------- >>> def highlight_max(x, color): ... return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None) - >>> df = pd.DataFrame(np.random.randn(5, 2)) + >>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"]) >>> df.style.apply(highlight_max, color='red') >>> df.style.apply(highlight_max, color='blue', axis=1) >>> df.style.apply(highlight_max, color='green', axis=None) + + Using ``subset`` to restrict application to a single column or multiple columns + + >>> df.style.apply(highlight_max, color='red', subset="A") + >>> df.style.apply(highlight_max, color='red', subset=["A", "B"]) + + Using a 2d input to ``subset`` to select rows in addition to columns + + >>> df.style.apply(highlight_max, color='red', subset=([0,1,2], slice(None)) + >>> df.style.apply(highlight_max, color='red', subset=(slice(0,5,2), "A") """ self._todo.append( (lambda instance: getattr(instance, "_apply"), (func, axis, subset), kwargs) @@ -675,9 +686,10 @@ def applymap( ---------- func : function ``func`` should take a scalar and return a scalar. - subset : IndexSlice - A valid indexer to limit ``data`` to *before* applying the - function. Consider using a pandas.IndexSlice. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. **kwargs : dict Pass along to ``func``. @@ -699,8 +711,18 @@ def applymap( -------- >>> def color_negative(v, color): ... return f"color: {color};" if v < 0 else None - >>> df = pd.DataFrame(np.random.randn(5, 2)) + >>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"]) >>> df.style.applymap(color_negative, color='red') + + Using ``subset`` to restrict application to a single column or multiple columns + + >>> df.style.applymap(color_negative, color='red', subset="A") + >>> df.style.applymap(color_negative, color='red', subset=["A", "B"]) + + Using a 2d input to ``subset`` to select rows in addition to columns + + >>> df.style.applymap(color_negative, color='red', subset=([0,1,2], slice(None)) + >>> df.style.applymap(color_negative, color='red', subset=(slice(0,5,2), "A") """ self._todo.append( (lambda instance: getattr(instance, "_applymap"), (func, subset), kwargs) @@ -732,9 +754,10 @@ def where( Applied when ``cond`` returns true. other : str Applied when ``cond`` returns false. - subset : IndexSlice - A valid indexer to limit ``data`` to *before* applying the - function. Consider using a pandas.IndexSlice. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. **kwargs : dict Pass along to ``cond``. @@ -1072,9 +1095,9 @@ def hide_columns(self, subset: Subset) -> Styler: Parameters ---------- - subset : IndexSlice - An argument to ``DataFrame.loc`` that identifies which columns - are hidden. + subset : label, array-like, IndexSlice + A valid 1d input or single key along the appropriate axis within + `DataFrame.loc[]`, to limit ``data`` to *before* applying the function. Returns ------- @@ -1127,8 +1150,10 @@ def background_gradient( Apply to each column (``axis=0`` or ``'index'``), to each row (``axis=1`` or ``'columns'``), or to the entire DataFrame at once with ``axis=None``. - subset : IndexSlice - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. text_color_threshold : float or int Luminance threshold for determining text color in [0, 1]. Facilitates text visibility across varying background colors. All text is dark if 0, and @@ -1251,8 +1276,10 @@ def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler: Parameters ---------- - subset : IndexSlice - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. **kwargs : dict A dictionary of property, value pairs to be set for each cell. @@ -1349,8 +1376,10 @@ def bar( Parameters ---------- - subset : IndexSlice, optional - A valid slice for `data` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. axis : {0 or 'index', 1 or 'columns', None}, default 0 Apply to each column (``axis=0`` or ``'index'``), to each row (``axis=1`` or ``'columns'``), or to the entire DataFrame at once @@ -1431,8 +1460,10 @@ def highlight_null( Parameters ---------- null_color : str, default 'red' - subset : label or list of labels, default None - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. .. versionadded:: 1.1.0 @@ -1477,8 +1508,10 @@ def highlight_max( Parameters ---------- - subset : IndexSlice, default None - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. color : str, default 'yellow' Background color to use for highlighting. axis : {0 or 'index', 1 or 'columns', None}, default 0 @@ -1526,8 +1559,10 @@ def highlight_min( Parameters ---------- - subset : IndexSlice, default None - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. color : str, default 'yellow' Background color to use for highlighting. axis : {0 or 'index', 1 or 'columns', None}, default 0 @@ -1580,8 +1615,10 @@ def highlight_between( Parameters ---------- - subset : IndexSlice, default None - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. color : str, default 'yellow' Background color to use for highlighting. axis : {0 or 'index', 1 or 'columns', None}, default 0 @@ -1688,8 +1725,10 @@ def highlight_quantile( Parameters ---------- - subset : IndexSlice, default None - A valid slice for ``data`` to limit the style application to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. color : str, default 'yellow' Background color to use for highlighting axis : {0 or 'index', 1 or 'columns', None}, default 0 diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 6f7d298c7dec0..1d45e30e64d7c 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -417,9 +417,10 @@ def format( ---------- formatter : str, callable, dict or None Object to define how values are displayed. See notes. - subset : IndexSlice - An argument to ``DataFrame.loc`` that restricts which elements - ``formatter`` is applied to. + subset : label, array-like, IndexSlice, optional + A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input + or single key, to `DataFrame.loc[:, <subset>]` where the columns are + prioritised, to limit ``data`` to *before* applying the function. na_rep : str, optional Representation for missing values. If ``na_rep`` is None, no special formatting is applied.
came up in a comment to another PR, so here it is changed for all appropriate methods.
https://api.github.com/repos/pandas-dev/pandas/pulls/41566
2021-05-19T11:34:39Z
2021-05-21T15:18:29Z
2021-05-21T15:18:29Z
2021-05-22T06:28:39Z
TST: tighten stacklevel checks
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index a3c58b6c6ae15..ff46715d0a527 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -599,7 +599,9 @@ def _validate_shift_value(self, fill_value): "will raise in a future version, pass " f"{self._scalar_type.__name__} instead.", FutureWarning, - stacklevel=8, + # There is no way to hard-code the level since this might be + # reached directly or called from the Index or Block method + stacklevel=find_stack_level(), ) fill_value = new_fill diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index f07a04b8087e0..aee0d4fecd6ae 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1175,6 +1175,7 @@ def to_perioddelta(self, freq) -> TimedeltaArray: "future version. " "Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead", FutureWarning, + # stacklevel chosen to be correct for when called from DatetimeIndex stacklevel=3, ) from pandas.core.arrays.timedeltas import TimedeltaArray diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1fa149cd834b0..18611cefa68bc 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1763,6 +1763,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, ) if orient.startswith("d"): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a09cc0a6324c0..3014930110620 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -481,13 +481,19 @@ def _data(self): @property def _AXIS_NUMBERS(self) -> dict[str, int]: """.. deprecated:: 1.1.0""" - warnings.warn("_AXIS_NUMBERS has been deprecated.", FutureWarning, stacklevel=3) + level = self.ndim + 1 + warnings.warn( + "_AXIS_NUMBERS has been deprecated.", FutureWarning, stacklevel=level + ) return {"index": 0} @property def _AXIS_NAMES(self) -> dict[int, str]: """.. deprecated:: 1.1.0""" - warnings.warn("_AXIS_NAMES has been deprecated.", FutureWarning, stacklevel=3) + level = self.ndim + 1 + warnings.warn( + "_AXIS_NAMES has been deprecated.", FutureWarning, stacklevel=level + ) return {0: "index"} @final diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 96556df73ffaf..b9fd18dfdce73 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3691,7 +3691,7 @@ def is_int(v): "and will raise TypeError in a future version. " "Use .loc with labels or .iloc with positions instead.", FutureWarning, - stacklevel=6, + stacklevel=5, ) indexer = key else: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e8b21f3cec668..ac09159c23566 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -40,6 +40,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( DT64NS_DTYPE, @@ -660,7 +661,7 @@ def _deprecate_mismatched_indexing(self, key) -> None: "raise KeyError in a future version. " "Use a timezone-aware object instead." ) - warnings.warn(msg, FutureWarning, stacklevel=5) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) def get_loc(self, key, method=None, tolerance=None): """ diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index f8085b2bab1ed..4791bbf0ba7f7 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -673,6 +673,8 @@ def __init__( f"in a future version. ({left.columns.nlevels} levels on the left," f"{right.columns.nlevels} on the right)" ) + # stacklevel chosen to be correct when this is reached via pd.merge + # (and not DataFrame.join) warnings.warn(msg, FutureWarning, stacklevel=3) self._validate_specification() diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 8581e9a20526f..c6f8efe7b939e 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -561,7 +561,8 @@ def test_shift_fill_int_deprecated(self): data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9 arr = self.array_cls(data, freq="D") - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "Passing <class 'int'> to shift" + with tm.assert_produces_warning(FutureWarning, match=msg): result = arr.shift(1, fill_value=1) expected = arr.copy() @@ -783,10 +784,13 @@ def test_to_perioddelta(self, datetime_index, freqstr): dti = datetime_index arr = DatetimeArray(dti) - with tm.assert_produces_warning(FutureWarning): + msg = "to_perioddelta is deprecated and will be removed" + with tm.assert_produces_warning(FutureWarning, match=msg): # Deprecation GH#34853 expected = dti.to_perioddelta(freq=freqstr) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning( + FutureWarning, match=msg, check_stacklevel=False + ): # stacklevel is chosen to be "correct" for DatetimeIndex, not # DatetimeArray result = arr.to_perioddelta(freq=freqstr) diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py index 70af64064ff85..f4ad3c6285f74 100644 --- a/pandas/tests/dtypes/cast/test_promote.py +++ b/pandas/tests/dtypes/cast/test_promote.py @@ -406,11 +406,13 @@ def test_maybe_promote_any_with_datetime64( exp_val_for_scalar = fill_value warn = None + msg = "Using a `date` object for fill_value" if type(fill_value) is datetime.date and dtype.kind == "M": # Casting date to dt64 is deprecated warn = FutureWarning - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False): + # stacklevel is chosen to make sense when called from higher-level functions _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 14fc18aff170e..778373fc7f0df 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -443,8 +443,10 @@ def test_array_equivalent(dtype_equal): ) def test_array_equivalent_series(val): arr = np.array([1, 2]) + msg = "elementwise comparison failed" cm = ( - tm.assert_produces_warning(FutureWarning, check_stacklevel=False) + # stacklevel is chosen to make sense when called from .equals + tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False) if isinstance(val, str) else nullcontext() ) diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py index 36fd5d399c300..989a9be181a3f 100644 --- a/pandas/tests/frame/methods/test_join.py +++ b/pandas/tests/frame/methods/test_join.py @@ -345,7 +345,11 @@ def test_merge_join_different_levels(self): # join, see discussion in GH#12219 columns = ["a", "b", ("a", ""), ("c", "c1")] expected = DataFrame(columns=columns, data=[[1, 11, 0, 44], [0, 22, 1, 33]]) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "merging between different levels is deprecated" + with tm.assert_produces_warning( + FutureWarning, match=msg, check_stacklevel=False + ): + # stacklevel is chosen to be correct for pd.merge, not DataFrame.join result = df1.join(df2, on="a") tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 5a87803ddc21e..f50b2c179ad9a 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -341,7 +341,7 @@ def test_reset_index_with_datetimeindex_cols(self, name): ) df.index.name = name - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): result = df.reset_index() item = name if name is not None else "index" diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py index 022b0f273493b..c33f649206f54 100644 --- a/pandas/tests/frame/methods/test_to_dict.py +++ b/pandas/tests/frame/methods/test_to_dict.py @@ -81,7 +81,8 @@ def test_to_dict_invalid_orient(self): def test_to_dict_short_orient_warns(self, orient): # GH#32515 df = DataFrame({"A": [0, 1]}) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "Using short name for 'orient' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): df.to_dict(orient=orient) @pytest.mark.parametrize("mapping", [dict, defaultdict(list), OrderedDict]) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 771d31aa6865b..254a0b8dfd34e 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -474,14 +474,16 @@ def test_axis_names_deprecated(self, frame_or_series): # GH33637 box = frame_or_series obj = box(dtype=object) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "_AXIS_NAMES has been deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): obj._AXIS_NAMES def test_axis_numbers_deprecated(self, frame_or_series): # GH33637 box = frame_or_series obj = box(dtype=object) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "_AXIS_NUMBERS has been deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): obj._AXIS_NUMBERS def test_flags_identity(self, frame_or_series): diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 1cef932f7bf0a..8c4f25c5b20fc 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -719,7 +719,11 @@ def test_engine_reference_cycle(self, simple_index): def test_getitem_2d_deprecated(self, simple_index): # GH#30588 idx = simple_index - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "Support for multi-dimensional indexing" + check = not isinstance(idx, (RangeIndex, CategoricalIndex)) + with tm.assert_produces_warning( + FutureWarning, match=msg, check_stacklevel=check + ): res = idx[:, None] assert isinstance(res, np.ndarray), type(res) diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 2773543b74764..de6fa4e8f4238 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -735,7 +735,7 @@ def test_get_slice_bounds_datetime_within( key = box(year=2000, month=1, day=7) warn = None if tz is None else FutureWarning - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): # GH#36148 will require tzawareness-compat result = index.get_slice_bound(key, kind=kind, side=side) assert result == expected @@ -753,7 +753,7 @@ def test_get_slice_bounds_datetime_outside( key = box(year=year, month=1, day=7) warn = None if tz is None else FutureWarning - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): # GH#36148 will require tzawareness-compat result = index.get_slice_bound(key, kind=kind, side=side) assert result == expected @@ -767,7 +767,7 @@ def test_slice_datetime_locs(self, box, kind, tz_aware_fixture): key = box(2010, 1, 1) warn = None if tz is None else FutureWarning - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): # GH#36148 will require tzawareness-compat result = index.slice_locs(key, box(2010, 1, 2)) expected = (0, 1) diff --git a/pandas/tests/indexes/interval/test_astype.py b/pandas/tests/indexes/interval/test_astype.py index f421a4695138c..cac145aa30fd0 100644 --- a/pandas/tests/indexes/interval/test_astype.py +++ b/pandas/tests/indexes/interval/test_astype.py @@ -205,7 +205,7 @@ def index(self, request): @pytest.mark.parametrize("subtype", ["int64", "uint64"]) def test_subtype_integer(self, index, subtype): dtype = IntervalDtype(subtype, "right") - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = index.astype(dtype) expected = IntervalIndex.from_arrays( index.left.astype(subtype), diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py index b14db459f996d..3589fe726b3bb 100644 --- a/pandas/tests/indexes/interval/test_base.py +++ b/pandas/tests/indexes/interval/test_base.py @@ -64,7 +64,7 @@ def test_getitem_2d_deprecated(self, simple_index): # GH#30588 multi-dim indexing is deprecated, but raising is also acceptable idx = simple_index with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): idx[:, None] diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index e3b41e6c5d6bb..65ae904d1083a 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -77,14 +77,14 @@ def test_constructor_dtype(self, constructor, breaks, subtype): # astype(int64) deprecated warn = FutureWarning - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype)) expected = constructor(**expected_kwargs) result_kwargs = self.get_kwargs_from_breaks(breaks) iv_dtype = IntervalDtype(subtype, "right") for dtype in (iv_dtype, str(iv_dtype)): - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): result = constructor(dtype=dtype, **result_kwargs) tm.assert_index_equal(result, expected) @@ -112,7 +112,7 @@ def test_constructor_pass_closed(self, constructor, breaks): result_kwargs = self.get_kwargs_from_breaks(breaks) for dtype in (iv_dtype, str(iv_dtype)): - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): result = constructor(dtype=dtype, closed="left", **result_kwargs) assert result.dtype.closed == "left" diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 5cf0134795b74..ec01e35673647 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -343,7 +343,7 @@ def test_astype_preserves_name(self, index, dtype): warn = FutureWarning try: # Some of these conversions cannot succeed so we use a try / except - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): result = index.astype(dtype) except (ValueError, TypeError, NotImplementedError, SystemError): return diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 90e3ff29977ae..48bc3e18d9883 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2400,7 +2400,7 @@ def test_loc_with_positional_slice_deprecation(): # GH#31840 ser = Series(range(4), index=["A", "B", "C", "D"]) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): ser.loc[:3] = 2 expected = Series([2, 2, 2, 3], index=["A", "B", "C", "D"]) @@ -2423,14 +2423,14 @@ def test_loc_slice_disallows_positional(): with pytest.raises(TypeError, match=msg): obj.loc[1:3] - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior obj.loc[1:3] = 1 with pytest.raises(TypeError, match=msg): df.loc[1:3, 1] - with tm.assert_produces_warning(FutureWarning): + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2 diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 08dba5aa76a2f..61bbd4e12e1ba 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -545,7 +545,7 @@ def test_astype(self, t): mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8") t = np.dtype(t) - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): tmgr = mgr.astype(t, errors="ignore") assert tmgr.iget(2).dtype.type == t assert tmgr.iget(4).dtype.type == t diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index e4ba530d0741c..2c5c977624470 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -147,25 +147,25 @@ def test_getitem_setitem_datetimeindex(): assert result == expected result = ts.copy() - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#36148 will require tzawareness compat result[datetime(1990, 1, 1, 4)] = 0 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#36148 will require tzawareness compat result[datetime(1990, 1, 1, 4)] = ts[4] tm.assert_series_equal(result, ts) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#36148 will require tzawareness compat result = ts[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] expected = ts[4:8] tm.assert_series_equal(result, expected) result = ts.copy() - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#36148 will require tzawareness compat result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = 0 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#36148 will require tzawareness compat result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = ts[4:8] tm.assert_series_equal(result, ts) diff --git a/pandas/tests/series/methods/test_truncate.py b/pandas/tests/series/methods/test_truncate.py index 672faf1e0d541..ca5c3e2639097 100644 --- a/pandas/tests/series/methods/test_truncate.py +++ b/pandas/tests/series/methods/test_truncate.py @@ -13,7 +13,7 @@ def test_truncate_datetimeindex_tz(self): # GH 9243 idx = date_range("4/1/2005", "4/30/2005", freq="D", tz="US/Pacific") s = Series(range(len(idx)), index=idx) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # GH#36148 in the future will require tzawareness compat s.truncate(datetime(2005, 4, 2), datetime(2005, 4, 4)) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 72b6b7527f57f..880fa6398d25a 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -783,7 +783,9 @@ def test_series_ops_name_retention( else: # GH#37374 logical ops behaving as set ops deprecated warn = FutureWarning if is_rlogical and box is Index else None - with tm.assert_produces_warning(warn, check_stacklevel=False): + msg = "operating as a set operation is deprecated" + with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False): + # stacklevel is correct for Index op, not reversed op result = op(left, right) if box is Index and is_rlogical: diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 67649e6e37b35..e74d900d1b04d 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -71,7 +71,7 @@ class TestSeriesConstructors: ) def test_empty_constructor(self, constructor, check_index_type): # TODO: share with frame test of the same name - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): expected = Series() result = constructor() @@ -116,7 +116,7 @@ def test_scalar_extension_dtype(self, ea_scalar_and_dtype): tm.assert_series_equal(ser, expected) def test_constructor(self, datetime_series): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): empty_series = Series() assert datetime_series.index._is_all_dates @@ -134,7 +134,7 @@ def test_constructor(self, datetime_series): assert mixed[1] is np.NaN assert not empty_series.index._is_all_dates - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): assert not Series().index._is_all_dates # exception raised is of type ValueError GH35744 @@ -154,7 +154,7 @@ def test_constructor(self, datetime_series): @pytest.mark.parametrize("input_class", [list, dict, OrderedDict]) def test_constructor_empty(self, input_class): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): empty = Series() empty2 = Series(input_class()) @@ -174,7 +174,7 @@ def test_constructor_empty(self, input_class): if input_class is not list: # With index: - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): empty = Series(index=range(10)) empty2 = Series(input_class(), index=range(10)) tm.assert_series_equal(empty, empty2) @@ -208,7 +208,7 @@ def test_constructor_dtype_only(self, dtype, index): assert len(result) == 0 def test_constructor_no_data_index_order(self): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): result = Series(index=["b", "a", "c"]) assert result.index.tolist() == ["b", "a", "c"] @@ -674,7 +674,7 @@ def test_constructor_limit_copies(self, index): assert s._mgr.blocks[0].values is not index def test_constructor_pass_none(self): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): s = Series(None, index=range(5)) assert s.dtype == np.float64 @@ -683,7 +683,7 @@ def test_constructor_pass_none(self): # GH 7431 # inference on the index - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): s = Series(index=np.array([None])) expected = Series(index=Index([None])) tm.assert_series_equal(s, expected) @@ -840,7 +840,7 @@ def test_constructor_dtype_datetime64_10(self): dts = Series(dates, dtype="datetime64[ns]") # valid astype - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # astype(np.int64) deprecated dts.astype("int64") @@ -852,7 +852,7 @@ def test_constructor_dtype_datetime64_10(self): # ints are ok # we test with np.int64 to get similar results on # windows / 32-bit platforms - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # astype(np.int64) deprecated result = Series(dts, dtype=np.int64) expected = Series(dts.astype(np.int64)) @@ -1341,7 +1341,7 @@ def test_constructor_dtype_timedelta64(self): # td.astype('m8[%s]' % t) # valid astype - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # astype(int64) deprecated td.astype("int64") @@ -1465,7 +1465,7 @@ def test_constructor_cant_cast_datetimelike(self, index): # ints are ok # we test with np.int64 to get similar results on # windows / 32-bit platforms - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # asype(np.int64) deprecated, use .view(np.int64) instead result = Series(index, dtype=np.int64) expected = Series(index.astype(np.int64)) diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index efcca0df639f6..1fc383521d31f 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -174,7 +174,8 @@ def test_to_timedelta_invalid(self): def test_unambiguous_timedelta_values(self, val, warning): # GH36666 Deprecate use of strings denoting units with 'M', 'Y', 'm' or 'y' # in pd.to_timedelta - with tm.assert_produces_warning(warning, check_stacklevel=False): + msg = "Units 'M', 'Y' and 'y' do not represent unambiguous timedelta" + with tm.assert_produces_warning(warning, match=msg, check_stacklevel=False): to_timedelta(val) def test_to_timedelta_via_apply(self): diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py index 9a6c62df76ef2..806e2abe83a92 100644 --- a/pandas/util/_exceptions.py +++ b/pandas/util/_exceptions.py @@ -2,6 +2,7 @@ import contextlib import inspect +import os @contextlib.contextmanager @@ -25,23 +26,20 @@ def rewrite_exception(old_name: str, new_name: str): def find_stack_level() -> int: """ - Find the appropriate stacklevel with which to issue a warning for astype. + Find the first place in the stack that is not inside pandas + (tests notwithstanding). """ stack = inspect.stack() - # find the lowest-level "astype" call that got us here - for n in range(2, 6): - if stack[n].function == "astype": - break - - while stack[n].function in ["astype", "apply", "astype_array_safe", "astype_array"]: - # e.g. - # bump up Block.astype -> BlockManager.astype -> NDFrame.astype - # bump up Datetime.Array.astype -> DatetimeIndex.astype - n += 1 + import pandas as pd - if stack[n].function == "__init__": - # Series.__init__ - n += 1 + pkg_dir = os.path.dirname(pd.__file__) + test_dir = os.path.join(pkg_dir, "tests") + for n in range(len(stack)): + fname = stack[n].filename + if fname.startswith(pkg_dir) and not fname.startswith(test_dir): + continue + else: + break return n
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41560
2021-05-19T06:00:32Z
2021-05-19T12:53:24Z
2021-05-19T12:53:24Z
2021-05-19T14:43:35Z
ENH: Deprecate positional arguments for DataFrame.fillna and Series.fillna (GH41485)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1eb22436204a8..c25a27e6bb740 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -649,6 +649,7 @@ Deprecations - Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`) - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 705962bef8086..e55b3984b1c39 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5179,6 +5179,7 @@ def fillna( ) -> DataFrame | None: ... + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "value"]) @doc(NDFrame.fillna, **_shared_doc_kwargs) def fillna( self, diff --git a/pandas/core/series.py b/pandas/core/series.py index aaf37ad191e87..2e060014fdb53 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4708,6 +4708,7 @@ def fillna( ... # error: Cannot determine type of 'fillna' + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "value"]) @doc(NDFrame.fillna, **_shared_doc_kwargs) # type: ignore[has-type] def fillna( self, diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index b827547b0753e..cb01de11a4be9 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -538,6 +538,18 @@ def test_fillna_downcast_dict(self): expected = DataFrame({"col1": [1, 2]}) tm.assert_frame_equal(result, expected) + def test_fillna_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3, np.nan]}, dtype=float) + msg = ( + r"In a future version of pandas all arguments of DataFrame.fillna " + r"except for the argument 'value' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(0, None, None) + expected = DataFrame({"a": [1, 2, 3, 0]}, dtype=float) + tm.assert_frame_equal(result, expected) + def test_fillna_nonconsolidated_frame(): # https://github.com/pandas-dev/pandas/issues/36495 diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 51864df915f8c..97804e0fef8b9 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -748,6 +748,18 @@ def test_fillna_datetime64_with_timezone_tzinfo(self): expected = Series([ser[0], ts, ser[2]], dtype=object) tm.assert_series_equal(result, expected) + def test_fillna_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + srs = Series([1, 2, 3, np.nan], dtype=float) + msg = ( + r"In a future version of pandas all arguments of Series.fillna " + r"except for the argument 'value' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = srs.fillna(0, None, None) + expected = Series([1, 2, 3, 0], dtype=float) + tm.assert_series_equal(result, expected) + class TestFillnaPad: def test_fillna_bug(self):
- [x] xref #41485 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41559
2021-05-19T05:45:32Z
2021-05-21T15:06:35Z
2021-05-21T15:06:35Z
2021-05-21T15:06:39Z
DEPS: bump min numexpr version to 2.7.0
diff --git a/ci/deps/actions-37-minimum_versions.yaml b/ci/deps/actions-37-minimum_versions.yaml index aa5284e4f35d1..b97601d18917c 100644 --- a/ci/deps/actions-37-minimum_versions.yaml +++ b/ci/deps/actions-37-minimum_versions.yaml @@ -17,7 +17,7 @@ dependencies: - bottleneck=1.2.1 - jinja2=2.10 - numba=0.46.0 - - numexpr=2.6.8 + - numexpr=2.7.0 - numpy=1.17.3 - openpyxl=3.0.0 - pytables=3.5.1 diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index ce35e9e15976f..be9c0da34f8a9 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -234,7 +234,7 @@ Recommended dependencies * `numexpr <https://github.com/pydata/numexpr>`__: for accelerating certain numerical operations. ``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups. - If installed, must be Version 2.6.8 or higher. + If installed, must be Version 2.7.0 or higher. * `bottleneck <https://github.com/pydata/bottleneck>`__: for accelerating certain types of ``nan`` evaluations. ``bottleneck`` uses specialized cython routines to achieve large speedups. If installed, diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1eb22436204a8..0f2b76df2c6d9 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -547,7 +547,7 @@ If installed, we now require: +-----------------+-----------------+----------+---------+ | bottleneck | 1.2.1 | | | +-----------------+-----------------+----------+---------+ -| numexpr | 2.6.8 | | | +| numexpr | 2.7.0 | | X | +-----------------+-----------------+----------+---------+ | pytest (dev) | 6.0 | | X | +-----------------+-----------------+----------+---------+ diff --git a/environment.yml b/environment.yml index 56a36c593a458..bb96235123af3 100644 --- a/environment.yml +++ b/environment.yml @@ -81,7 +81,7 @@ dependencies: - ipython>=7.11.1 - jinja2<3.0.0 # pandas.Styler - matplotlib>=2.2.2 # pandas.plotting, Series.plot, DataFrame.plot - - numexpr>=2.6.8 + - numexpr>=2.7.0 - scipy>=1.2 - numba>=0.46.0 diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index f8eccfeb2c60a..2c184c38e6b1a 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -17,7 +17,7 @@ "gcsfs": "0.6.0", "lxml.etree": "4.3.0", "matplotlib": "2.2.3", - "numexpr": "2.6.8", + "numexpr": "2.7.0", "odfpy": "1.3.0", "openpyxl": "3.0.0", "pandas_gbq": "0.12.0", diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 231beb40e9630..8758565cf9f2a 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -27,7 +27,6 @@ result_type_many, ) from pandas.core.computation.scope import DEFAULT_GLOBALS -from pandas.util.version import Version from pandas.io.formats.printing import ( pprint_thing, @@ -616,18 +615,8 @@ def __repr__(self) -> str: class FuncNode: def __init__(self, name: str): - from pandas.core.computation.check import ( - NUMEXPR_INSTALLED, - NUMEXPR_VERSION, - ) - - if name not in MATHOPS or ( - NUMEXPR_INSTALLED - and Version(NUMEXPR_VERSION) < Version("2.6.9") - and name in ("floor", "ceil") - ): + if name not in MATHOPS: raise ValueError(f'"{name}" is not a supported function') - self.name = name self.func = getattr(np, name) diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 9ee53a9d7c54d..0467bb1dad676 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -29,7 +29,6 @@ ) import pandas._testing as tm from pandas.core.computation import pytables -from pandas.core.computation.check import NUMEXPR_VERSION from pandas.core.computation.engines import ( ENGINES, NumExprClobberingError, @@ -51,7 +50,6 @@ _binary_ops_dict, _unary_math_ops, ) -from pandas.util.version import Version @pytest.fixture( @@ -76,20 +74,8 @@ def parser(request): return request.param -@pytest.fixture -def ne_lt_2_6_9(): - if NUMEXPR_INSTALLED and Version(NUMEXPR_VERSION) >= Version("2.6.9"): - pytest.skip("numexpr is >= 2.6.9") - return "numexpr" - - def _get_unary_fns_for_ne(): - if NUMEXPR_INSTALLED: - if Version(NUMEXPR_VERSION) >= Version("2.6.9"): - return list(_unary_math_ops) - else: - return [x for x in _unary_math_ops if x not in ["floor", "ceil"]] - return [] + return list(_unary_math_ops) if NUMEXPR_INSTALLED else [] @pytest.fixture(params=_get_unary_fns_for_ne()) @@ -1766,13 +1752,6 @@ def test_unary_functions(self, unary_fns_for_ne): expect = getattr(np, fn)(a) tm.assert_series_equal(got, expect, check_names=False) - @pytest.mark.parametrize("fn", ["floor", "ceil"]) - def test_floor_and_ceil_functions_raise_error(self, ne_lt_2_6_9, fn): - msg = f'"{fn}" is not a supported function' - with pytest.raises(ValueError, match=msg): - expr = f"{fn}(100)" - self.eval(expr) - @pytest.mark.parametrize("fn", _binary_math_ops) def test_binary_functions(self, fn): df = DataFrame({"a": np.random.randn(10), "b": np.random.randn(10)}) diff --git a/requirements-dev.txt b/requirements-dev.txt index d1fafbbf9101d..f454bfd15236c 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -53,7 +53,7 @@ ipykernel ipython>=7.11.1 jinja2<3.0.0 matplotlib>=2.2.2 -numexpr>=2.6.8 +numexpr>=2.7.0 scipy>=1.2 numba>=0.46.0 beautifulsoup4>=4.6.0
Using 2.7.0 as the min support version removes all numexpr compat. And numexpr 2.7.0 was released on Aug 14, 2019.
https://api.github.com/repos/pandas-dev/pandas/pulls/41558
2021-05-19T04:30:39Z
2021-05-21T15:57:52Z
2021-05-21T15:57:52Z
2021-06-18T02:25:13Z
DEPR: DataFrame([categorical, ...]) special casing
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1eb22436204a8..a80f90924c3a5 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -648,6 +648,7 @@ Deprecations - Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`) - Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`) - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) +- Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 06d30d6ed72e8..ed4b9797ca702 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -11,6 +11,7 @@ Hashable, Sequence, ) +import warnings import numpy as np import numpy.ma as ma @@ -772,6 +773,16 @@ def to_arrays( return [], ensure_index([]) elif isinstance(data[0], Categorical): + # GH#38845 deprecate special case + warnings.warn( + "The behavior of DataFrame([categorical, ...]) is deprecated and " + "in a future version will be changed to match the behavior of " + "DataFrame([any_listlike, ...]). " + "To retain the old behavior, pass as a dictionary " + "DataFrame({col: categorical, ..})", + FutureWarning, + stacklevel=4, + ) if columns is None: columns = ibase.default_index(len(data)) return data, columns diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 10d55053d5bc6..33e7c1643d18d 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -4571,7 +4571,7 @@ def read( df = DataFrame(values, columns=cols_, index=index_) else: # Categorical - df = DataFrame([values], columns=cols_, index=index_) + df = DataFrame._from_arrays([values], columns=cols_, index=index_) assert (df.dtypes == values.dtype).all(), (df.dtypes, values.dtype) frames.append(df) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 6e9991ff17ac3..179d1bca7223f 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2089,12 +2089,16 @@ def test_constructor_categorical(self): def test_construct_from_1item_list_of_categorical(self): # ndim != 1 - df = DataFrame([Categorical(list("abc"))]) + msg = "will be changed to match the behavior" + with tm.assert_produces_warning(FutureWarning, match=msg): + df = DataFrame([Categorical(list("abc"))]) expected = DataFrame({0: Series(list("abc"), dtype="category")}) tm.assert_frame_equal(df, expected) def test_construct_from_list_of_categoricals(self): - df = DataFrame([Categorical(list("abc")), Categorical(list("abd"))]) + msg = "will be changed to match the behavior" + with tm.assert_produces_warning(FutureWarning, match=msg): + df = DataFrame([Categorical(list("abc")), Categorical(list("abd"))]) expected = DataFrame( { 0: Series(list("abc"), dtype="category"), @@ -2106,7 +2110,9 @@ def test_construct_from_list_of_categoricals(self): def test_from_nested_listlike_mixed_types(self): # mixed - df = DataFrame([Categorical(list("abc")), list("def")]) + msg = "will be changed to match the behavior" + with tm.assert_produces_warning(FutureWarning, match=msg): + df = DataFrame([Categorical(list("abc")), list("def")]) expected = DataFrame( {0: Series(list("abc"), dtype="category"), 1: list("def")}, columns=[0, 1] ) @@ -2120,8 +2126,10 @@ def test_construct_from_listlikes_mismatched_lengths(self): "Passed arrays should have the same length as the rows Index", ] ) + msg2 = "will be changed to match the behavior" with pytest.raises(ValueError, match=msg): - DataFrame([Categorical(list("abc")), Categorical(list("abdefg"))]) + with tm.assert_produces_warning(FutureWarning, match=msg2): + DataFrame([Categorical(list("abc")), Categorical(list("abdefg"))]) def test_constructor_categorical_series(self):
- [x] closes #38845 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41557
2021-05-19T02:38:17Z
2021-05-21T16:46:34Z
2021-05-21T16:46:34Z
2021-05-21T17:20:15Z
DEPR: Series/DataFrame with tzaware data and tznaive dtype
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 070e47d73cfae..ae82bdf5395d1 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -675,6 +675,7 @@ Deprecations - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) +- Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 94cffe8fb840d..d31d75e7d4398 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -219,6 +219,8 @@ def maybe_unbox_datetimelike(value: Scalar, dtype: DtypeObj) -> Scalar: elif isinstance(value, Timestamp): if value.tz is None: value = value.to_datetime64() + elif not isinstance(dtype, DatetimeTZDtype): + raise TypeError("Cannot unbox tzaware Timestamp to tznaive dtype") elif isinstance(value, Timedelta): value = value.to_timedelta64() @@ -1616,9 +1618,21 @@ def maybe_cast_to_datetime( # didn't specify one if dta.tz is not None: + warnings.warn( + "Data is timezone-aware. Converting " + "timezone-aware data to timezone-naive by " + "passing dtype='datetime64[ns]' to " + "DataFrame or Series is deprecated and will " + "raise in a future version. Use " + "`pd.Series(values).dt.tz_localize(None)` " + "instead.", + FutureWarning, + stacklevel=8, + ) # equiv: dta.view(dtype) # Note: NOT equivalent to dta.astype(dtype) dta = dta.tz_localize(None) + value = dta elif is_datetime64tz: dtype = cast(DatetimeTZDtype, dtype) @@ -1810,7 +1824,7 @@ def construct_2d_arraylike_from_scalar( shape = (length, width) if dtype.kind in ["m", "M"]: - value = maybe_unbox_datetimelike(value, dtype) + value = maybe_unbox_datetimelike_tz_deprecation(value, dtype, stacklevel=4) elif dtype == object: if isinstance(value, (np.timedelta64, np.datetime64)): # calling np.array below would cast to pytimedelta/pydatetime @@ -1873,7 +1887,7 @@ def construct_1d_arraylike_from_scalar( if not isna(value): value = ensure_str(value) elif dtype.kind in ["M", "m"]: - value = maybe_unbox_datetimelike(value, dtype) + value = maybe_unbox_datetimelike_tz_deprecation(value, dtype) subarr = np.empty(length, dtype=dtype) subarr.fill(value) @@ -1881,6 +1895,40 @@ def construct_1d_arraylike_from_scalar( return subarr +def maybe_unbox_datetimelike_tz_deprecation( + value: Scalar, dtype: DtypeObj, stacklevel: int = 5 +): + """ + Wrap maybe_unbox_datetimelike with a check for a timezone-aware Timestamp + along with a timezone-naive datetime64 dtype, which is deprecated. + """ + # Caller is responsible for checking dtype.kind in ["m", "M"] + try: + value = maybe_unbox_datetimelike(value, dtype) + except TypeError: + if ( + isinstance(value, Timestamp) + and value.tz is not None + and isinstance(dtype, np.dtype) + ): + warnings.warn( + "Data is timezone-aware. Converting " + "timezone-aware data to timezone-naive by " + "passing dtype='datetime64[ns]' to " + "DataFrame or Series is deprecated and will " + "raise in a future version. Use " + "`pd.Series(values).dt.tz_localize(None)` " + "instead.", + FutureWarning, + stacklevel=stacklevel, + ) + new_value = value.tz_localize(None) + return maybe_unbox_datetimelike(new_value, dtype) + else: + raise + return value + + def construct_1d_object_array_from_listlike(values: Sized) -> np.ndarray: """ Transform any list-like object in a 1-dimensional numpy array of object diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 6e9991ff17ac3..a5dc37ef32735 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2404,6 +2404,17 @@ def test_from_series_with_name_with_columns(self): expected = DataFrame(columns=["bar"]) tm.assert_frame_equal(result, expected) + def test_nested_list_columns(self): + # GH 14467 + result = DataFrame( + [[1, 2, 3], [4, 5, 6]], columns=[["A", "A", "A"], ["a", "b", "c"]] + ) + expected = DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")]), + ) + tm.assert_frame_equal(result, expected) + class TestDataFrameConstructorWithDatetimeTZ: @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) @@ -2436,12 +2447,41 @@ def test_construction_preserves_tzaware_dtypes(self, tz): tm.assert_series_equal(result, expected) def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): - # GH#25843 + # GH#25843, GH#41555, GH#33401 tz = tz_aware_fixture - result = DataFrame({"d": [Timestamp("2019", tz=tz)]}, dtype="datetime64[ns]") - expected = DataFrame({"d": [Timestamp("2019")]}) + ts = Timestamp("2019", tz=tz) + ts_naive = Timestamp("2019") + + with tm.assert_produces_warning(FutureWarning): + result = DataFrame({0: [ts]}, dtype="datetime64[ns]") + + expected = DataFrame({0: [ts_naive]}) + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = DataFrame({0: ts}, index=[0], dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = DataFrame([ts], dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = DataFrame(np.array([ts], dtype=object), dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning): + result = DataFrame(ts, index=[0], columns=[0], dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + df = DataFrame([Series([ts])], dtype="datetime64[ns]") tm.assert_frame_equal(result, expected) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + df = DataFrame([[ts]], columns=[0], dtype="datetime64[ns]") + tm.assert_equal(df, expected) + def test_from_dict(self): # 8260 @@ -2682,13 +2722,15 @@ def test_from_out_of_bounds_timedelta(self, constructor, cls): assert type(get1(result)) is cls - def test_nested_list_columns(self): - # GH 14467 - result = DataFrame( - [[1, 2, 3], [4, 5, 6]], columns=[["A", "A", "A"], ["a", "b", "c"]] - ) - expected = DataFrame( - [[1, 2, 3], [4, 5, 6]], - columns=MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")]), - ) - tm.assert_frame_equal(result, expected) + def test_tzaware_data_tznaive_dtype(self, constructor): + tz = "US/Eastern" + ts = Timestamp("2019", tz=tz) + ts_naive = Timestamp("2019") + + with tm.assert_produces_warning( + FutureWarning, match="Data is timezone-aware", check_stacklevel=False + ): + result = constructor(ts, dtype="M8[ns]") + + assert np.all(result.dtypes == "M8[ns]") + assert np.all(result == ts_naive) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index e74d900d1b04d..41c0cbf58e438 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1536,10 +1536,26 @@ def test_constructor_tz_mixed_data(self): tm.assert_series_equal(result, expected) def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): - # GH#25843 + # GH#25843, GH#41555, GH#33401 tz = tz_aware_fixture - result = Series([Timestamp("2019", tz=tz)], dtype="datetime64[ns]") - expected = Series([Timestamp("2019")]) + ts = Timestamp("2019", tz=tz) + ts_naive = Timestamp("2019") + + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = Series([ts], dtype="datetime64[ns]") + expected = Series([ts_naive]) + tm.assert_series_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = Series(np.array([ts], dtype=object), dtype="datetime64[ns]") + tm.assert_series_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning): + result = Series({0: ts}, dtype="datetime64[ns]") + tm.assert_series_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning): + result = Series(ts, index=[0], dtype="datetime64[ns]") tm.assert_series_equal(result, expected) def test_constructor_datetime64(self):
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41555
2021-05-18T23:13:06Z
2021-05-21T19:13:04Z
2021-05-21T19:13:04Z
2021-05-21T19:13:05Z
CLN: construction helper methods
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index f3133480108a6..964575ba47d7b 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -688,11 +688,8 @@ def _try_cast( if is_integer_dtype(dtype): # this will raise if we have e.g. floats - # error: Argument 2 to "maybe_cast_to_integer_array" has incompatible type - # "Union[dtype, ExtensionDtype, None]"; expected "Union[ExtensionDtype, str, - # dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool], - # Type[object]]" - maybe_cast_to_integer_array(arr, dtype) # type: ignore[arg-type] + dtype = cast(np.dtype, dtype) + maybe_cast_to_integer_array(arr, dtype) subarr = arr else: subarr = maybe_cast_to_datetime(arr, dtype) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 46dc97214e2f6..b94b6965cc747 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -2017,7 +2017,7 @@ def maybe_cast_to_integer_array( if is_unsigned_integer_dtype(dtype) and (arr < 0).any(): raise OverflowError("Trying to coerce negative values to unsigned integers") - if is_float_dtype(arr) or is_object_dtype(arr): + if is_float_dtype(arr.dtype) or is_object_dtype(arr.dtype): raise ValueError("Trying to coerce float values to integers") diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 9f0a80ba0f5c7..96556df73ffaf 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6386,19 +6386,18 @@ def maybe_extract_name(name, obj, cls) -> Hashable: return name -def _maybe_cast_data_without_dtype(subarr): +def _maybe_cast_data_without_dtype(subarr: np.ndarray) -> ArrayLike: """ If we have an arraylike input but no passed dtype, try to infer a supported dtype. Parameters ---------- - subarr : np.ndarray, Index, or Series + subarr : np.ndarray[object] Returns ------- - converted : np.ndarray or ExtensionArray - dtype : np.dtype or ExtensionDtype + np.ndarray or ExtensionArray """ # Runtime import needed bc IntervalArray imports Index from pandas.core.arrays import ( @@ -6413,11 +6412,7 @@ def _maybe_cast_data_without_dtype(subarr): if inferred == "integer": try: - # error: Argument 3 to "_try_convert_to_int_array" has incompatible type - # "None"; expected "dtype[Any]" - data = _try_convert_to_int_array( - subarr, False, None # type: ignore[arg-type] - ) + data = _try_convert_to_int_array(subarr) return data except ValueError: pass @@ -6463,18 +6458,13 @@ def _maybe_cast_data_without_dtype(subarr): return subarr -def _try_convert_to_int_array( - data: np.ndarray, copy: bool, dtype: np.dtype -) -> np.ndarray: +def _try_convert_to_int_array(data: np.ndarray) -> np.ndarray: """ Attempt to convert an array of data into an integer array. Parameters ---------- - data : The data to convert. - copy : bool - Whether to copy the data or not. - dtype : np.dtype + data : np.ndarray[object] Returns ------- @@ -6484,22 +6474,19 @@ def _try_convert_to_int_array( ------ ValueError if the conversion was not successful. """ - if not is_unsigned_integer_dtype(dtype): - # skip int64 conversion attempt if uint-like dtype is passed, as - # this could return Int64Index when UInt64Index is what's desired - try: - res = data.astype("i8", copy=False) - if (res == data).all(): - return res # TODO: might still need to copy - except (OverflowError, TypeError, ValueError): - pass + try: + res = data.astype("i8", copy=False) + if (res == data).all(): + return res + except (OverflowError, TypeError, ValueError): + pass - # Conversion to int64 failed (possibly due to overflow) or was skipped, + # Conversion to int64 failed (possibly due to overflow), # so let's try now with uint64. try: res = data.astype("u8", copy=False) if (res == data).all(): - return res # TODO: might still need to copy + return res except (OverflowError, TypeError, ValueError): pass
https://api.github.com/repos/pandas-dev/pandas/pulls/41554
2021-05-18T21:48:35Z
2021-05-19T02:58:45Z
2021-05-19T02:58:45Z
2021-05-19T04:56:21Z
ENH: Deprecate non-keyword arguments for Index.set_names.
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index fe88cf93886ce..66d9e720153bd 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -679,6 +679,7 @@ Deprecations - Deprecated the ``convert_float`` optional argument in :func:`read_excel` and :meth:`ExcelFile.parse` (:issue:`41127`) - Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`) - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) +- Deprecated passing arguments as positional in :meth:`Index.set_names` and :meth:`MultiIndex.set_names` (except for ``names``) (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2a6f044288fea..2a50ebd959ace 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1538,7 +1538,7 @@ def _set_names(self, values, level=None) -> None: names = property(fset=_set_names, fget=_get_names) - @final + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "names"]) def set_names(self, names, level=None, inplace: bool = False): """ Set Index or MultiIndex name. diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 6a13ffa5a376b..1362679ae0064 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -292,7 +292,6 @@ class MultiIndex(Index): _levels = FrozenList() _codes = FrozenList() _comparables = ["names"] - rename = Index.set_names sortorder: int | None @@ -3585,7 +3584,9 @@ def _get_reconciled_name_object(self, other) -> MultiIndex: """ names = self._maybe_match_names(other) if self.names != names: - return self.rename(names) + # Incompatible return value type (got "Optional[MultiIndex]", expected + # "MultiIndex") + return self.rename(names) # type: ignore[return-value] return self def _maybe_match_names(self, other): @@ -3784,6 +3785,12 @@ def isin(self, values, level=None) -> np.ndarray: return np.zeros(len(levs), dtype=np.bool_) return levs.isin(values) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "names"]) + def set_names(self, names, level=None, inplace: bool = False) -> MultiIndex | None: + return super().set_names(names=names, level=level, inplace=inplace) + + rename = set_names + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def drop_duplicates(self, keep: str | bool = "first") -> MultiIndex: return super().drop_duplicates(keep=keep) diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 9657e74c363b9..e756f95bb2bc5 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -345,6 +345,23 @@ def test_set_names_with_nlevel_1(inplace): tm.assert_index_equal(result, expected) +def test_multi_set_names_pos_args_deprecation(): + # GH#41485 + idx = MultiIndex.from_product([["python", "cobra"], [2018, 2019]]) + msg = ( + "In a future version of pandas all arguments of MultiIndex.set_names " + "except for the argument 'names' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = idx.set_names(["kind", "year"], None) + expected = MultiIndex( + levels=[["python", "cobra"], [2018, 2019]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=["kind", "year"], + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("ordered", [True, False]) def test_set_levels_categorical(ordered): # GH13854 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f41c79bd09f67..f75e4af888643 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1740,6 +1740,19 @@ def test_construct_from_memoryview(klass, extra_kwargs): tm.assert_index_equal(result, expected) +def test_index_set_names_pos_args_deprecation(): + # GH#41485 + idx = Index([1, 2, 3, 4]) + msg = ( + "In a future version of pandas all arguments of Index.set_names " + "except for the argument 'names' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = idx.set_names("quarter", None) + expected = Index([1, 2, 3, 4], name="quarter") + tm.assert_index_equal(result, expected) + + def test_drop_duplicates_pos_args_deprecation(): # GH#41485 idx = Index([1, 2, 3, 1])
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41551
2021-05-18T20:31:18Z
2021-05-27T13:18:21Z
2021-05-27T13:18:21Z
2021-05-27T13:18:21Z
CLN: simplify libreduction
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index c28db9b669a4b..d730084692dd4 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -1,4 +1,3 @@ -from copy import copy from libc.stdlib cimport ( free, @@ -307,13 +306,11 @@ cpdef inline extract_result(object res): # Preserve EA res = res._values if res.ndim == 1 and len(res) == 1: + # see test_agg_lambda_with_timezone, test_resampler_grouper.py::test_apply res = res[0] - if hasattr(res, 'values') and is_array(res.values): - res = res.values if is_array(res): - if res.ndim == 0: - res = res.item() - elif res.ndim == 1 and len(res) == 1: + if res.ndim == 1 and len(res) == 1: + # see test_resampler_grouper.py::test_apply res = res[0] return res @@ -386,7 +383,7 @@ def apply_frame_axis0(object frame, object f, object names, # Need to infer if low level index slider will cause segfaults require_slow_apply = i == 0 and piece is chunk try: - if not piece.index is chunk.index: + if piece.index is not chunk.index: mutated = True except AttributeError: # `piece` might not have an index, could be e.g. an int @@ -397,7 +394,7 @@ def apply_frame_axis0(object frame, object f, object names, try: piece = piece.copy(deep="all") except (TypeError, AttributeError): - piece = copy(piece) + pass results.append(piece)
https://api.github.com/repos/pandas-dev/pandas/pulls/41542
2021-05-18T15:27:03Z
2021-05-21T19:13:25Z
2021-05-21T19:13:25Z
2021-05-21T19:17:09Z
[ArrowStringArray] REF: str.extract - move code from function to accessor method
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 98d209ae4a899..e581906818eb2 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -2378,6 +2378,11 @@ def extract( 2 NaN dtype: object """ + from pandas import ( + DataFrame, + array as pd_array, + ) + if not isinstance(expand, bool): raise ValueError("expand must be True or False") @@ -2389,7 +2394,40 @@ def extract( raise ValueError("only one regex group is supported with Index") # TODO: dispatch - return str_extract(self, pat, flags, expand=expand) + + obj = self._data + result_dtype = _result_dtype(obj) + + returns_df = regex.groups > 1 or expand + + if returns_df: + name = None + columns = _get_group_names(regex) + + if obj.array.size == 0: + result = DataFrame(columns=columns, dtype=result_dtype) + + else: + result_list = _str_extract( + obj.array, pat, flags=flags, expand=returns_df + ) + + result_index: Index | None + if isinstance(obj, ABCSeries): + result_index = obj.index + else: + result_index = None + + result = DataFrame( + result_list, columns=columns, index=result_index, dtype=result_dtype + ) + + else: + name = _get_single_group_name(regex) + result_arr = _str_extract(obj.array, pat, flags=flags, expand=returns_df) + # not dispatching, so we have to reconstruct here. + result = pd_array(result_arr, dtype=result_dtype) + return self._wrap_result(result, name=name) @forbid_nonstring_types(["bytes"]) def extractall(self, pat, flags=0): @@ -3103,45 +3141,6 @@ def f(x): return np.array([f(val)[0] for val in np.asarray(arr)], dtype=object) -def str_extract(accessor: StringMethods, pat: str, flags: int = 0, expand: bool = True): - from pandas import ( - DataFrame, - array as pd_array, - ) - - obj = accessor._data - result_dtype = _result_dtype(obj) - regex = re.compile(pat, flags=flags) - returns_df = regex.groups > 1 or expand - - if returns_df: - name = None - columns = _get_group_names(regex) - - if obj.array.size == 0: - result = DataFrame(columns=columns, dtype=result_dtype) - - else: - result_list = _str_extract(obj.array, pat, flags=flags, expand=returns_df) - - result_index: Index | None - if isinstance(obj, ABCSeries): - result_index = obj.index - else: - result_index = None - - result = DataFrame( - result_list, columns=columns, index=result_index, dtype=result_dtype - ) - - else: - name = _get_single_group_name(regex) - result_arr = _str_extract(obj.array, pat, flags=flags, expand=returns_df) - # not dispatching, so we have to reconstruct here. - result = pd_array(result_arr, dtype=result_dtype) - return accessor._wrap_result(result, name=name) - - def str_extractall(arr, pat, flags=0): regex = re.compile(pat, flags=flags) # the regex must contain capture groups.
perf neutral refactor ~~draft as conflict with #41539~~
https://api.github.com/repos/pandas-dev/pandas/pulls/41541
2021-05-18T15:18:09Z
2021-05-25T13:42:18Z
2021-05-25T13:42:18Z
2021-05-25T14:37:22Z
REF: Grouper.grouper -> Grouper._gpr_index
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 877204f5bb2a2..b4f3dd7b942a6 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -252,6 +252,8 @@ class Grouper: axis: int sort: bool dropna: bool + _gpr_index: Index | None + _grouper: Index | None _attributes: tuple[str, ...] = ("key", "level", "freq", "axis", "sort") @@ -279,6 +281,7 @@ def __init__( self.sort = sort self.grouper = None + self._gpr_index = None self.obj = None self.indexer = None self.binner = None @@ -288,8 +291,11 @@ def __init__( @final @property - def ax(self): - return self.grouper + def ax(self) -> Index: + index = self._gpr_index + if index is None: + raise ValueError("_set_grouper must be called before ax is accessed") + return index def _get_grouper(self, obj: FrameOrSeries, validate: bool = True): """ @@ -317,6 +323,7 @@ def _get_grouper(self, obj: FrameOrSeries, validate: bool = True): validate=validate, dropna=self.dropna, ) + return self.binner, self.grouper, self.obj @final @@ -338,14 +345,17 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): # Keep self.grouper value before overriding if self._grouper is None: - self._grouper = self.grouper + # TODO: What are we assuming about subsequent calls? + self._grouper = self._gpr_index self._indexer = self.indexer # the key must be a valid info item if self.key is not None: key = self.key # The 'on' is already defined - if getattr(self.grouper, "name", None) == key and isinstance(obj, Series): + if getattr(self._gpr_index, "name", None) == key and isinstance( + obj, Series + ): # Sometimes self._grouper will have been resorted while # obj has not. In this case there is a mismatch when we # call self._grouper.take(obj.index) so we need to undo the sorting @@ -390,10 +400,8 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): # error: Incompatible types in assignment (expression has type # "FrameOrSeries", variable has type "None") self.obj = obj # type: ignore[assignment] - # error: Incompatible types in assignment (expression has type "Index", - # variable has type "None") - self.grouper = ax # type: ignore[assignment] - return self.grouper + self._gpr_index = ax + return self._gpr_index @final @property diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 1ab2b90d6564a..8195c18768eec 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -198,6 +198,8 @@ def obj(self) -> FrameOrSeries: # type: ignore[override] @property def ax(self): + # we can infer that this is a PeriodIndex/DatetimeIndex/TimedeltaIndex, + # but skipping annotating bc the overrides overwhelming return self.groupby.ax @property
ATM we set `self.grouper` in both _get_grouper and in _set_grouper, but to different types. This changes _set_grouper to set _gpr_index instead, which we can type as `Index | None`
https://api.github.com/repos/pandas-dev/pandas/pulls/41540
2021-05-18T15:17:41Z
2021-05-21T16:45:09Z
2021-05-21T16:45:09Z
2021-05-21T17:19:49Z
[ArrowStringArray] REF: str.extract - precusor to move from accessor to array
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 1461c52d5cb65..43df34a7ecbb2 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -3034,22 +3034,6 @@ def cat_core(list_of_columns: List, sep: str): return np.sum(arr_with_sep, axis=0) -def _groups_or_na_fun(regex): - """Used in both extract_noexpand and extract_frame""" - empty_row = [np.nan] * regex.groups - - def f(x): - if not isinstance(x, str): - return empty_row - m = regex.search(x) - if m: - return [np.nan if item is None else item for item in m.groups()] - else: - return empty_row - - return f - - def _result_dtype(arr): # workaround #27953 # ideally we just pass `dtype=arr.dtype` unconditionally, but this fails @@ -3087,41 +3071,31 @@ def _get_group_names(regex: Pattern) -> List[Hashable]: return [names.get(1 + i, i) for i in range(regex.groups)] -def _str_extract_noexpand(arr: ArrayLike, pat: str, flags=0): +def _str_extract(arr: ArrayLike, pat: str, flags=0, expand: bool = True): """ Find groups in each string in the array using passed regular expression. - This function is called from str_extract(expand=False) when there is a single group - in the regex. - Returns ------- - np.ndarray + np.ndarray or list of lists is expand is True """ regex = re.compile(pat, flags=flags) - groups_or_na = _groups_or_na_fun(regex) - - result = np.array([groups_or_na(val)[0] for val in np.asarray(arr)], dtype=object) - return result - -def _str_extract_expand(arr: ArrayLike, pat: str, flags: int = 0) -> List[List]: - """ - Find groups in each string in the array using passed regular expression. - - For each subject string in the array, extract groups from the first match of - regular expression pat. This function is called from str_extract(expand=True) or - str_extract(expand=False) when there is more than one group in the regex. + empty_row = [np.nan] * regex.groups - Returns - ------- - list of lists + def f(x): + if not isinstance(x, str): + return empty_row + m = regex.search(x) + if m: + return [np.nan if item is None else item for item in m.groups()] + else: + return empty_row - """ - regex = re.compile(pat, flags=flags) - groups_or_na = _groups_or_na_fun(regex) + if expand: + return [f(val) for val in np.asarray(arr)] - return [groups_or_na(val) for val in np.asarray(arr)] + return np.array([f(val)[0] for val in np.asarray(arr)], dtype=object) def str_extract(accessor: StringMethods, pat: str, flags: int = 0, expand: bool = True): @@ -3143,7 +3117,7 @@ def str_extract(accessor: StringMethods, pat: str, flags: int = 0, expand: bool result = DataFrame(columns=columns, dtype=result_dtype) else: - result_list = _str_extract_expand(obj.array, pat, flags=flags) + result_list = _str_extract(obj.array, pat, flags=flags, expand=returns_df) result_index: Optional["Index"] if isinstance(obj, ABCSeries): @@ -3157,7 +3131,7 @@ def str_extract(accessor: StringMethods, pat: str, flags: int = 0, expand: bool else: name = _get_single_group_name(regex) - result_arr = _str_extract_noexpand(obj.array, pat, flags=flags) + result_arr = _str_extract(obj.array, pat, flags=flags, expand=returns_df) # not dispatching, so we have to reconstruct here. result = pd_array(result_arr, dtype=result_dtype) return accessor._wrap_result(result, name=name)
perf neutral refactor combine `_str_extract_expand`, `_str_extract_noexpand` and `_groups_or_na_fun` into a single function `_str_extract` ready to move to array method.
https://api.github.com/repos/pandas-dev/pandas/pulls/41539
2021-05-18T14:52:52Z
2021-05-18T16:51:50Z
2021-05-18T16:51:50Z
2021-05-18T18:22:26Z
[ArrowStringArray] TST: parametrize /tests/strings/test_strings.py
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index f77a78b8c4c49..98f3fc859976e 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -47,8 +47,8 @@ def test_iter(): assert s.dropna().values.item() == "l" -def test_iter_empty(): - ser = Series([], dtype=object) +def test_iter_empty(any_string_dtype): + ser = Series([], dtype=any_string_dtype) i, s = 100, 1 @@ -62,8 +62,8 @@ def test_iter_empty(): assert s == 1 -def test_iter_single_element(): - ser = Series(["a"]) +def test_iter_single_element(any_string_dtype): + ser = Series(["a"], dtype=any_string_dtype) with tm.assert_produces_warning(FutureWarning): for i, s in enumerate(ser.str): @@ -94,10 +94,11 @@ def test_iter_object_try_string(): # test integer/float dtypes (inferred by constructor) and mixed -def test_count(): - ser = Series(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=np.object_) +def test_count(any_string_dtype): + ser = Series(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=any_string_dtype) result = ser.str.count("f[o]+") - expected = Series([1, 2, np.nan, 4]) + expected_dtype = np.float64 if any_string_dtype == "object" else "Int64" + expected = Series([1, 2, np.nan, 4], dtype=expected_dtype) tm.assert_series_equal(result, expected) @@ -111,15 +112,19 @@ def test_count_mixed_object(): tm.assert_series_equal(result, expected) -def test_repeat(): - ser = Series(["a", "b", np.nan, "c", np.nan, "d"]) +def test_repeat(any_string_dtype): + ser = Series(["a", "b", np.nan, "c", np.nan, "d"], dtype=any_string_dtype) result = ser.str.repeat(3) - expected = Series(["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"]) + expected = Series( + ["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"], dtype=any_string_dtype + ) tm.assert_series_equal(result, expected) result = ser.str.repeat([1, 2, 3, 4, 5, 6]) - expected = Series(["a", "bb", np.nan, "cccc", np.nan, "dddddd"]) + expected = Series( + ["a", "bb", np.nan, "cccc", np.nan, "dddddd"], dtype=any_string_dtype + ) tm.assert_series_equal(result, expected) @@ -132,16 +137,16 @@ def test_repeat_mixed_object(): tm.assert_series_equal(result, expected) -def test_repeat_with_null(nullable_string_dtype): +def test_repeat_with_null(any_string_dtype): # GH: 31632 - ser = Series(["a", None], dtype=nullable_string_dtype) + ser = Series(["a", None], dtype=any_string_dtype) result = ser.str.repeat([3, 4]) - expected = Series(["aaa", None], dtype=nullable_string_dtype) + expected = Series(["aaa", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) - ser = Series(["a", "b"], dtype=nullable_string_dtype) + ser = Series(["a", "b"], dtype=any_string_dtype) result = ser.str.repeat([3, None]) - expected = Series(["aaa", None], dtype=nullable_string_dtype) + expected = Series(["aaa", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected) @@ -155,6 +160,7 @@ def test_empty_str_methods(any_string_dtype): empty_bool = Series(dtype="boolean") empty_object = Series(dtype=object) empty_bytes = Series(dtype=object) + empty_df = DataFrame() # GH7241 # (extract) on empty series @@ -184,7 +190,7 @@ def test_empty_str_methods(any_string_dtype): DataFrame(columns=[0, 1], dtype=any_string_dtype), empty.str.extract("()()", expand=False), ) - tm.assert_frame_equal(DataFrame(), empty.str.get_dummies()) + tm.assert_frame_equal(empty_df, empty.str.get_dummies()) tm.assert_series_equal(empty_str, empty_str.str.join("")) tm.assert_series_equal(empty_int, empty.str.len()) tm.assert_series_equal(empty_object, empty_str.str.findall("a")) @@ -195,7 +201,9 @@ def test_empty_str_methods(any_string_dtype): tm.assert_series_equal(empty_object, empty.str.split("a")) tm.assert_series_equal(empty_object, empty.str.rsplit("a")) tm.assert_series_equal(empty_object, empty.str.partition("a", expand=False)) + tm.assert_frame_equal(empty_df, empty.str.partition("a")) tm.assert_series_equal(empty_object, empty.str.rpartition("a", expand=False)) + tm.assert_frame_equal(empty_df, empty.str.rpartition("a")) tm.assert_series_equal(empty_str, empty.str.slice(stop=1)) tm.assert_series_equal(empty_str, empty.str.slice(step=1)) tm.assert_series_equal(empty_str, empty.str.strip()) @@ -223,17 +231,6 @@ def test_empty_str_methods(any_string_dtype): tm.assert_series_equal(empty_str, empty.str.translate(table)) -def test_empty_str_methods_to_frame(): - ser = Series(dtype=str) - expected = DataFrame() - - result = ser.str.partition("a") - tm.assert_frame_equal(result, expected) - - result = ser.str.rpartition("a") - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( "method, expected", [ @@ -266,18 +263,17 @@ def test_empty_str_methods_to_frame(): ], ) def test_ismethods(method, expected, any_string_dtype): - values = ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "] - ser = Series(values, dtype=any_string_dtype) - + ser = Series( + ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "], dtype=any_string_dtype + ) expected_dtype = "bool" if any_string_dtype == "object" else "boolean" expected = Series(expected, dtype=expected_dtype) result = getattr(ser.str, method)() tm.assert_series_equal(result, expected) # compare with standard library - expected = [getattr(v, method)() for v in values] - result = result.tolist() - assert result == expected + expected = [getattr(item, method)() for item in ser] + assert list(result) == expected @pytest.mark.parametrize( @@ -292,17 +288,15 @@ def test_isnumeric_unicode(method, expected, any_string_dtype): # 0x2605: ★ not number # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY # 0xFF13: 3 Em 3 - values = ["A", "3", "¼", "★", "፸", "3", "four"] - ser = Series(values, dtype=any_string_dtype) + ser = Series(["A", "3", "¼", "★", "፸", "3", "four"], dtype=any_string_dtype) expected_dtype = "bool" if any_string_dtype == "object" else "boolean" expected = Series(expected, dtype=expected_dtype) result = getattr(ser.str, method)() tm.assert_series_equal(result, expected) # compare with standard library - expected = [getattr(v, method)() for v in values] - result = result.tolist() - assert result == expected + expected = [getattr(item, method)() for item in ser] + assert list(result) == expected @pytest.mark.parametrize( @@ -321,10 +315,11 @@ def test_isnumeric_unicode_missing(method, expected, any_string_dtype): tm.assert_series_equal(result, expected) -def test_spilt_join_roundtrip(): - ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"]) +def test_spilt_join_roundtrip(any_string_dtype): + ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype) result = ser.str.split("_").str.join("_") - tm.assert_series_equal(result, ser) + expected = ser.astype(object) + tm.assert_series_equal(result, expected) def test_spilt_join_roundtrip_mixed_object(): @@ -358,53 +353,49 @@ def test_len_mixed(): tm.assert_series_equal(result, expected) -def test_index(index_or_series): - if index_or_series is Series: - _check = tm.assert_series_equal - else: - _check = tm.assert_index_equal - - obj = index_or_series(["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"]) - - result = obj.str.index("EF") - _check(result, index_or_series([4, 3, 1, 0])) - expected = np.array([v.index("EF") for v in obj.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) - - result = obj.str.rindex("EF") - _check(result, index_or_series([4, 5, 7, 4])) - expected = np.array([v.rindex("EF") for v in obj.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) +@pytest.mark.parametrize( + "method,sub,start,end,expected", + [ + ("index", "EF", None, None, [4, 3, 1, 0]), + ("rindex", "EF", None, None, [4, 5, 7, 4]), + ("index", "EF", 3, None, [4, 3, 7, 4]), + ("rindex", "EF", 3, None, [4, 5, 7, 4]), + ("index", "E", 4, 8, [4, 5, 7, 4]), + ("rindex", "E", 0, 5, [4, 3, 1, 4]), + ], +) +def test_index(method, sub, start, end, index_or_series, any_string_dtype, expected): + if index_or_series is Index and not any_string_dtype == "object": + pytest.skip("Index cannot yet be backed by a StringArray/ArrowStringArray") - result = obj.str.index("EF", 3) - _check(result, index_or_series([4, 3, 7, 4])) - expected = np.array([v.index("EF", 3) for v in obj.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + obj = index_or_series( + ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype + ) + expected_dtype = np.int64 if any_string_dtype == "object" else "Int64" + expected = index_or_series(expected, dtype=expected_dtype) - result = obj.str.rindex("EF", 3) - _check(result, index_or_series([4, 5, 7, 4])) - expected = np.array([v.rindex("EF", 3) for v in obj.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + result = getattr(obj.str, method)(sub, start, end) - result = obj.str.index("E", 4, 8) - _check(result, index_or_series([4, 5, 7, 4])) - expected = np.array([v.index("E", 4, 8) for v in obj.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + if index_or_series is Series: + tm.assert_series_equal(result, expected) + else: + tm.assert_index_equal(result, expected) - result = obj.str.rindex("E", 0, 5) - _check(result, index_or_series([4, 3, 1, 4])) - expected = np.array([v.rindex("E", 0, 5) for v in obj.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + # compare with standard library + expected = [getattr(item, method)(sub, start, end) for item in obj] + assert list(result) == expected -def test_index_not_found(index_or_series): - obj = index_or_series(["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"]) +def test_index_not_found_raises(index_or_series, any_string_dtype): + obj = index_or_series( + ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype + ) with pytest.raises(ValueError, match="substring not found"): obj.str.index("DE") -def test_index_wrong_type_raises(index_or_series): - obj = index_or_series([], dtype=object) +def test_index_wrong_type_raises(index_or_series, any_string_dtype): + obj = index_or_series([], dtype=any_string_dtype) msg = "expected a string object, not int" with pytest.raises(TypeError, match=msg): @@ -414,28 +405,29 @@ def test_index_wrong_type_raises(index_or_series): obj.str.rindex(0) -def test_index_missing(): - ser = Series(["abcb", "ab", "bcbe", np.nan]) +def test_index_missing(any_string_dtype): + ser = Series(["abcb", "ab", "bcbe", np.nan], dtype=any_string_dtype) + expected_dtype = np.float64 if any_string_dtype == "object" else "Int64" result = ser.str.index("b") - expected = Series([1, 1, 0, np.nan]) + expected = Series([1, 1, 0, np.nan], dtype=expected_dtype) tm.assert_series_equal(result, expected) result = ser.str.rindex("b") - expected = Series([3, 1, 2, np.nan]) + expected = Series([3, 1, 2, np.nan], dtype=expected_dtype) tm.assert_series_equal(result, expected) -def test_pipe_failures(): +def test_pipe_failures(any_string_dtype): # #2119 - ser = Series(["A|B|C"]) + ser = Series(["A|B|C"], dtype=any_string_dtype) result = ser.str.split("|") - expected = Series([["A", "B", "C"]]) + expected = Series([["A", "B", "C"]], dtype=object) tm.assert_series_equal(result, expected) result = ser.str.replace("|", " ", regex=False) - expected = Series(["A B C"]) + expected = Series(["A B C"], dtype=any_string_dtype) tm.assert_series_equal(result, expected) @@ -449,10 +441,10 @@ def test_pipe_failures(): (3, 0, -1, ["ofa", "aba", np.nan, "aba"]), ], ) -def test_slice(start, stop, step, expected): - ser = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"]) +def test_slice(start, stop, step, expected, any_string_dtype): + ser = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"], dtype=any_string_dtype) result = ser.str.slice(start, stop, step) - expected = Series(expected) + expected = Series(expected, dtype=any_string_dtype) tm.assert_series_equal(result, expected) @@ -470,39 +462,26 @@ def test_slice_mixed_object(start, stop, step, expected): tm.assert_series_equal(result, expected) -def test_slice_replace(): - ser = Series(["short", "a bit longer", "evenlongerthanthat", "", np.nan]) - - expected = Series(["shrt", "a it longer", "evnlongerthanthat", "", np.nan]) - result = ser.str.slice_replace(2, 3) - tm.assert_series_equal(result, expected) - - expected = Series(["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]) - result = ser.str.slice_replace(2, 3, "z") - tm.assert_series_equal(result, expected) - - expected = Series(["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]) - result = ser.str.slice_replace(2, 2, "z") - tm.assert_series_equal(result, expected) - - expected = Series(["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]) - result = ser.str.slice_replace(2, 1, "z") - tm.assert_series_equal(result, expected) - - expected = Series(["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]) - result = ser.str.slice_replace(-1, None, "z") - tm.assert_series_equal(result, expected) - - expected = Series(["zrt", "zer", "zat", "z", np.nan]) - result = ser.str.slice_replace(None, -2, "z") - tm.assert_series_equal(result, expected) - - expected = Series(["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]) - result = ser.str.slice_replace(6, 8, "z") - tm.assert_series_equal(result, expected) - - expected = Series(["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]) - result = ser.str.slice_replace(-10, 3, "z") +@pytest.mark.parametrize( + "start,stop,repl,expected", + [ + (2, 3, None, ["shrt", "a it longer", "evnlongerthanthat", "", np.nan]), + (2, 3, "z", ["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]), + (2, 2, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]), + (2, 1, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]), + (-1, None, "z", ["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]), + (None, -2, "z", ["zrt", "zer", "zat", "z", np.nan]), + (6, 8, "z", ["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]), + (-10, 3, "z", ["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]), + ], +) +def test_slice_replace(start, stop, repl, expected, any_string_dtype): + ser = Series( + ["short", "a bit longer", "evenlongerthanthat", "", np.nan], + dtype=any_string_dtype, + ) + expected = Series(expected, dtype=any_string_dtype) + result = ser.str.slice_replace(start, stop, repl) tm.assert_series_equal(result, expected) @@ -556,9 +535,10 @@ def test_strip_lstrip_rstrip_args(any_string_dtype): tm.assert_series_equal(result, expected) -def test_string_slice_get_syntax(): +def test_string_slice_get_syntax(any_string_dtype): ser = Series( - ["YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", np.nan, "CYYYBYYY", "dog", "cYYYt"] + ["YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", np.nan, "CYYYBYYY", "dog", "cYYYt"], + dtype=any_string_dtype, ) result = ser.str[0] @@ -574,27 +554,29 @@ def test_string_slice_get_syntax(): tm.assert_series_equal(result, expected) -def test_string_slice_out_of_bounds(): +def test_string_slice_out_of_bounds_nested(): ser = Series([(1, 2), (1,), (3, 4, 5)]) result = ser.str[1] expected = Series([2, np.nan, 4]) tm.assert_series_equal(result, expected) - ser = Series(["foo", "b", "ba"]) + +def test_string_slice_out_of_bounds(any_string_dtype): + ser = Series(["foo", "b", "ba"], dtype=any_string_dtype) result = ser.str[1] - expected = Series(["o", np.nan, "a"]) + expected = Series(["o", np.nan, "a"], dtype=any_string_dtype) tm.assert_series_equal(result, expected) -def test_encode_decode(): - ser = Series(["a", "b", "a\xe4"]).str.encode("utf-8") +def test_encode_decode(any_string_dtype): + ser = Series(["a", "b", "a\xe4"], dtype=any_string_dtype).str.encode("utf-8") result = ser.str.decode("utf-8") expected = ser.map(lambda x: x.decode("utf-8")) tm.assert_series_equal(result, expected) -def test_encode_errors_kwarg(): - ser = Series(["a", "b", "a\x9d"]) +def test_encode_errors_kwarg(any_string_dtype): + ser = Series(["a", "b", "a\x9d"], dtype=any_string_dtype) msg = ( r"'charmap' codec can't encode character '\\x9d' in position 1: " @@ -630,15 +612,23 @@ def test_decode_errors_kwarg(): ("NFC", ["ABC", "ABC", "123", np.nan, "アイエ"]), ], ) -def test_normalize(form, expected): - ser = Series(["ABC", "ABC", "123", np.nan, "アイエ"], index=["a", "b", "c", "d", "e"]) - expected = Series(expected, index=["a", "b", "c", "d", "e"]) +def test_normalize(form, expected, any_string_dtype): + ser = Series( + ["ABC", "ABC", "123", np.nan, "アイエ"], + index=["a", "b", "c", "d", "e"], + dtype=any_string_dtype, + ) + expected = Series(expected, index=["a", "b", "c", "d", "e"], dtype=any_string_dtype) result = ser.str.normalize(form) tm.assert_series_equal(result, expected) -def test_normalize_bad_arg_raises(): - ser = Series(["ABC", "ABC", "123", np.nan, "アイエ"], index=["a", "b", "c", "d", "e"]) +def test_normalize_bad_arg_raises(any_string_dtype): + ser = Series( + ["ABC", "ABC", "123", np.nan, "アイエ"], + index=["a", "b", "c", "d", "e"], + dtype=any_string_dtype, + ) with pytest.raises(ValueError, match="invalid normalization form"): ser.str.normalize("xxx") @@ -700,9 +690,9 @@ def test_index_str_accessor_multiindex_raises(): idx.str -def test_str_accessor_no_new_attributes(): +def test_str_accessor_no_new_attributes(any_string_dtype): # https://github.com/pandas-dev/pandas/issues/10673 - ser = Series(list("aabbcde")) + ser = Series(list("aabbcde"), dtype=any_string_dtype) with pytest.raises(AttributeError, match="You cannot add any new attribute"): ser.str.xlabel = "a"
first followup to #41484
https://api.github.com/repos/pandas-dev/pandas/pulls/41538
2021-05-18T14:01:17Z
2021-05-18T16:52:48Z
2021-05-18T16:52:48Z
2021-05-18T18:16:28Z
[ArrowStringArray] REF: str.extract accessor method
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index e85da9f4b574d..1461c52d5cb65 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -15,7 +15,10 @@ import numpy as np import pandas._libs.lib as lib -from pandas._typing import FrameOrSeriesUnion +from pandas._typing import ( + ArrayLike, + FrameOrSeriesUnion, +) from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( @@ -3084,9 +3087,9 @@ def _get_group_names(regex: Pattern) -> List[Hashable]: return [names.get(1 + i, i) for i in range(regex.groups)] -def _str_extract_noexpand(arr, pat, flags=0): +def _str_extract_noexpand(arr: ArrayLike, pat: str, flags=0): """ - Find groups in each string in the Series/Index using passed regular expression. + Find groups in each string in the array using passed regular expression. This function is called from str_extract(expand=False) when there is a single group in the regex. @@ -3095,65 +3098,69 @@ def _str_extract_noexpand(arr, pat, flags=0): ------- np.ndarray """ - from pandas import array as pd_array - regex = re.compile(pat, flags=flags) groups_or_na = _groups_or_na_fun(regex) - result_dtype = _result_dtype(arr) result = np.array([groups_or_na(val)[0] for val in np.asarray(arr)], dtype=object) - # not dispatching, so we have to reconstruct here. - result = pd_array(result, dtype=result_dtype) return result -def _str_extract_frame(arr, pat, flags=0): +def _str_extract_expand(arr: ArrayLike, pat: str, flags: int = 0) -> List[List]: """ - Find groups in each string in the Series/Index using passed regular expression. + Find groups in each string in the array using passed regular expression. - For each subject string in the Series/Index, extract groups from the first match of + For each subject string in the array, extract groups from the first match of regular expression pat. This function is called from str_extract(expand=True) or str_extract(expand=False) when there is more than one group in the regex. Returns ------- - DataFrame + list of lists """ - from pandas import DataFrame - regex = re.compile(pat, flags=flags) groups_or_na = _groups_or_na_fun(regex) - columns = _get_group_names(regex) - result_dtype = _result_dtype(arr) - if arr.size == 0: - return DataFrame(columns=columns, dtype=result_dtype) + return [groups_or_na(val) for val in np.asarray(arr)] - result_index: Optional["Index"] - if isinstance(arr, ABCSeries): - result_index = arr.index - else: - result_index = None - return DataFrame( - [groups_or_na(val) for val in np.asarray(arr)], - columns=columns, - index=result_index, - dtype=result_dtype, - ) +def str_extract(accessor: StringMethods, pat: str, flags: int = 0, expand: bool = True): + from pandas import ( + DataFrame, + array as pd_array, + ) -def str_extract(arr, pat, flags=0, expand=True): + obj = accessor._data + result_dtype = _result_dtype(obj) regex = re.compile(pat, flags=flags) returns_df = regex.groups > 1 or expand if returns_df: name = None - result = _str_extract_frame(arr._orig, pat, flags=flags) + columns = _get_group_names(regex) + + if obj.array.size == 0: + result = DataFrame(columns=columns, dtype=result_dtype) + + else: + result_list = _str_extract_expand(obj.array, pat, flags=flags) + + result_index: Optional["Index"] + if isinstance(obj, ABCSeries): + result_index = obj.index + else: + result_index = None + + result = DataFrame( + result_list, columns=columns, index=result_index, dtype=result_dtype + ) + else: name = _get_single_group_name(regex) - result = _str_extract_noexpand(arr._orig, pat, flags=flags) - return arr._wrap_result(result, name=name) + result_arr = _str_extract_noexpand(obj.array, pat, flags=flags) + # not dispatching, so we have to reconstruct here. + result = pd_array(result_arr, dtype=result_dtype) + return accessor._wrap_result(result, name=name) def str_extractall(arr, pat, flags=0):
perf neutral refactor, another step towards #41372 next steps move code in `str_extract` into `extract` into StringMethods combine code in `_str_extract_noexpand` and `_str_extract_expand` into a `_str_extract` method on the array (not done here to keep diff simpler to review)
https://api.github.com/repos/pandas-dev/pandas/pulls/41535
2021-05-18T10:58:59Z
2021-05-18T12:48:41Z
2021-05-18T12:48:41Z
2021-05-18T14:12:08Z
REF: privatize Grouping attrs
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 877204f5bb2a2..62f75f52bb6ad 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -441,6 +441,9 @@ class Grouping: _codes: np.ndarray | None = None _group_index: Index | None = None + _passed_categorical: bool + _all_grouper: Categorical | None + _index: Index def __init__( self, @@ -456,13 +459,13 @@ def __init__( self.level = level self._orig_grouper = grouper self.grouping_vector = _convert_grouper(index, grouper) - self.all_grouper = None - self.index = index - self.sort = sort + self._all_grouper = None + self._index = index + self._sort = sort self.obj = obj - self.observed = observed + self._observed = observed self.in_axis = in_axis - self.dropna = dropna + self._dropna = dropna self._passed_categorical = False @@ -471,11 +474,15 @@ def __init__( ilevel = self._ilevel if ilevel is not None: + mapper = self.grouping_vector + # In extant tests, the new self.grouping_vector matches + # `index.get_level_values(ilevel)` whenever + # mapper is None and isinstance(index, MultiIndex) ( self.grouping_vector, # Index self._codes, self._group_index, - ) = index._get_grouper_for_level(self.grouping_vector, ilevel) + ) = index._get_grouper_for_level(mapper, ilevel) # a passed Grouper like, directly get the grouper in the same way # as single grouper groupby, use the group_info to get codes @@ -505,8 +512,8 @@ def __init__( # a passed Categorical self._passed_categorical = True - self.grouping_vector, self.all_grouper = recode_for_groupby( - self.grouping_vector, self.sort, observed + self.grouping_vector, self._all_grouper = recode_for_groupby( + self.grouping_vector, sort, observed ) elif not isinstance( @@ -517,11 +524,11 @@ def __init__( t = self.name or str(type(self.grouping_vector)) raise ValueError(f"Grouper for '{t}' not 1-dimensional") - self.grouping_vector = self.index.map(self.grouping_vector) + self.grouping_vector = index.map(self.grouping_vector) if not ( hasattr(self.grouping_vector, "__len__") - and len(self.grouping_vector) == len(self.index) + and len(self.grouping_vector) == len(index) ): grper = pprint_thing(self.grouping_vector) errmsg = ( @@ -546,7 +553,7 @@ def __iter__(self): def name(self) -> Hashable: ilevel = self._ilevel if ilevel is not None: - return self.index.names[ilevel] + return self._index.names[ilevel] if isinstance(self._orig_grouper, (Index, Series)): return self._orig_grouper.name @@ -569,7 +576,7 @@ def _ilevel(self) -> int | None: if level is None: return None if not isinstance(level, int): - index = self.index + index = self._index if level not in index.names: raise AssertionError(f"Level {level} not in index") return index.names.index(level) @@ -607,10 +614,10 @@ def group_arraylike(self) -> ArrayLike: @cache_readonly def result_index(self) -> Index: # TODO: what's the difference between result_index vs group_index? - if self.all_grouper is not None: + if self._all_grouper is not None: group_idx = self.group_index assert isinstance(group_idx, CategoricalIndex) - return recode_from_groupby(self.all_grouper, self.sort, group_idx) + return recode_from_groupby(self._all_grouper, self._sort, group_idx) return self.group_index @cache_readonly @@ -629,10 +636,10 @@ def _codes_and_uniques(self) -> tuple[np.ndarray, ArrayLike]: cat = self.grouping_vector categories = cat.categories - if self.observed: + if self._observed: ucodes = algorithms.unique1d(cat.codes) ucodes = ucodes[ucodes != -1] - if self.sort or cat.ordered: + if self._sort or cat.ordered: ucodes = np.sort(ucodes) else: ucodes = np.arange(len(categories)) @@ -648,18 +655,18 @@ def _codes_and_uniques(self) -> tuple[np.ndarray, ArrayLike]: uniques = self.grouping_vector.result_arraylike else: # GH35667, replace dropna=False with na_sentinel=None - if not self.dropna: + if not self._dropna: na_sentinel = None else: na_sentinel = -1 codes, uniques = algorithms.factorize( - self.grouping_vector, sort=self.sort, na_sentinel=na_sentinel + self.grouping_vector, sort=self._sort, na_sentinel=na_sentinel ) return codes, uniques @cache_readonly def groups(self) -> dict[Hashable, np.ndarray]: - return self.index.groupby(Categorical.from_codes(self.codes, self.group_index)) + return self._index.groupby(Categorical.from_codes(self.codes, self.group_index)) def get_grouper( diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index b995a74c20a40..2ff97bf535e0c 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -678,7 +678,7 @@ def __init__( self.axis = axis self._groupings: list[grouper.Grouping] = list(groupings) - self.sort = sort + self._sort = sort self.group_keys = group_keys self.mutated = mutated self.indexer = indexer @@ -891,7 +891,7 @@ def codes_info(self) -> np.ndarray: def _get_compressed_codes(self) -> tuple[np.ndarray, np.ndarray]: if len(self.groupings) > 1: group_index = get_group_index(self.codes, self.shape, sort=True, xnull=True) - return compress_group_index(group_index, sort=self.sort) + return compress_group_index(group_index, sort=self._sort) ping = self.groupings[0] return ping.codes, np.arange(len(ping.group_index))
Trying to move towards being less stateful.
https://api.github.com/repos/pandas-dev/pandas/pulls/41534
2021-05-18T02:11:23Z
2021-05-21T16:44:47Z
2021-05-21T16:44:47Z
2021-05-21T17:16:18Z
CLN/TYP: assorted cleanup and annotations
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 02c64fac0c009..6b1c0f851f8e7 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -235,7 +235,10 @@ def array_with_unit_to_datetime( if issubclass(values.dtype.type, (np.integer, np.float_)): result = values.astype("M8[ns]", copy=False) else: - result, tz = array_to_datetime(values.astype(object), errors=errors) + result, tz = array_to_datetime( + values.astype(object, copy=False), + errors=errors, + ) return result, tz m, p = precision_from_unit(unit) diff --git a/pandas/core/base.py b/pandas/core/base.py index e2720fcbc7ec4..55e776d2e6b73 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -196,6 +196,7 @@ def _selected_obj(self): else: return self.obj[self._selection] + @final @cache_readonly def ndim(self) -> int: return self._selected_obj.ndim diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 123b9e3350fda..c38c51d46f83e 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1105,8 +1105,8 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: else: # we get here in a number of test_multilevel tests for name in self.indices: - data = self.get_group(name, obj=obj) - fres = func(data, *args, **kwargs) + grp_df = self.get_group(name, obj=obj) + fres = func(grp_df, *args, **kwargs) result[name] = fres result_index = self.grouper.result_index diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 0b07668a9fea2..29a161676b2db 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -525,7 +525,7 @@ class GroupByPlot(PandasObject): Class implementing the .plot attribute for groupby objects. """ - def __init__(self, groupby): + def __init__(self, groupby: GroupBy): self._groupby = groupby def __call__(self, *args, **kwargs): @@ -727,7 +727,7 @@ def pipe( plot = property(GroupByPlot) @final - def get_group(self, name, obj=None): + def get_group(self, name, obj=None) -> FrameOrSeriesUnion: """ Construct DataFrame from group with provided name. @@ -960,10 +960,11 @@ def _set_group_selection(self) -> None: NOTE: this should be paired with a call to _reset_group_selection """ + # This is a no-op for SeriesGroupBy grp = self.grouper if not ( self.as_index - and getattr(grp, "groupings", None) is not None + and grp.groupings is not None and self.obj.ndim > 1 and self._group_selection is None ): diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 00efc695ff04a..f33cb104cef44 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -117,7 +117,7 @@ def arrays_to_mgr( if verify_integrity: # figure out the index, if necessary if index is None: - index = extract_index(arrays) + index = _extract_index(arrays) else: index = ensure_index(index) @@ -424,7 +424,7 @@ def dict_to_mgr( if index is None: # GH10856 # raise ValueError if only scalars in dict - index = extract_index(arrays[~missing]) + index = _extract_index(arrays[~missing]) else: index = ensure_index(index) @@ -603,7 +603,7 @@ def _homogenize(data, index: Index, dtype: DtypeObj | None): return homogenized -def extract_index(data) -> Index: +def _extract_index(data) -> Index: """ Try to infer an Index from the passed data, raise ValueError on failure. """ diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 4eb469f52fb19..014a702618bda 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -497,14 +497,12 @@ def _to_datetime_with_format( return _box_as_indexlike(result, utc=utc, name=name) # fallback - if result is None: - res = _array_strptime_with_fallback( - arg, name, tz, fmt, exact, errors, infer_datetime_format - ) - if res is not None: - return res + res = _array_strptime_with_fallback( + arg, name, tz, fmt, exact, errors, infer_datetime_format + ) + return res - except ValueError as e: + except ValueError as err: # Fallback to try to convert datetime objects if timezone-aware # datetime objects are found without passing `utc=True` try: @@ -512,11 +510,7 @@ def _to_datetime_with_format( dta = DatetimeArray(values, dtype=tz_to_dtype(tz)) return DatetimeIndex._simple_new(dta, name=name) except (ValueError, TypeError): - raise e - - # error: Incompatible return value type (got "Optional[ndarray]", expected - # "Optional[Index]") - return result # type: ignore[return-value] + raise err def _to_datetime_with_unit(arg, unit, name, tz, errors: str) -> Index: diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 5e038635305f1..0ef0896df8d44 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -111,6 +111,7 @@ class BaseWindow(SelectionMixin): _attributes: list[str] = [] exclusions: frozenset[Hashable] = frozenset() + _on: Index def __init__( self, @@ -169,7 +170,7 @@ def win_type(self): return self._win_type @property - def is_datetimelike(self): + def is_datetimelike(self) -> bool: warnings.warn( "is_datetimelike is deprecated and will be removed in a future version.", FutureWarning, @@ -329,7 +330,7 @@ def _prep_values(self, values: ArrayLike) -> np.ndarray: # expected "ndarray") return values # type: ignore[return-value] - def _insert_on_column(self, result: DataFrame, obj: DataFrame): + def _insert_on_column(self, result: DataFrame, obj: DataFrame) -> None: # if we have an 'on' column we want to put it back into # the results in the same location from pandas import Series diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index eb38f2f95d2d5..121ca99785831 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1079,7 +1079,7 @@ def test_iso8601_strings_mixed_offsets_with_naive(self): def test_mixed_offsets_with_native_datetime_raises(self): # GH 25978 - s = Series( + ser = Series( [ "nan", Timestamp("1990-01-01"), @@ -1089,7 +1089,7 @@ def test_mixed_offsets_with_native_datetime_raises(self): ] ) with pytest.raises(ValueError, match="Tz-aware datetime.datetime"): - to_datetime(s) + to_datetime(ser) def test_non_iso_strings_with_tz_offset(self): result = to_datetime(["March 1, 2018 12:00:00+0400"] * 2)
Things I find myself doing on multiple other in-progress branches
https://api.github.com/repos/pandas-dev/pandas/pulls/41533
2021-05-18T02:01:53Z
2021-05-18T16:47:03Z
2021-05-18T16:47:03Z
2021-05-18T17:26:19Z
REF: Grouping.grouper -> Grouping.grouping_vector
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 29a161676b2db..4310d849d66e8 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3064,7 +3064,7 @@ def _reindex_output( # reindexing only applies to a Categorical grouper elif not any( - isinstance(ping.grouper, (Categorical, CategoricalIndex)) + isinstance(ping.grouping_vector, (Categorical, CategoricalIndex)) for ping in groupings ): return output diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index e2855cbc90425..877204f5bb2a2 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -455,7 +455,7 @@ def __init__( ): self.level = level self._orig_grouper = grouper - self.grouper = _convert_grouper(index, grouper) + self.grouping_vector = _convert_grouper(index, grouper) self.all_grouper = None self.index = index self.sort = sort @@ -472,19 +472,19 @@ def __init__( ilevel = self._ilevel if ilevel is not None: ( - self.grouper, # Index + self.grouping_vector, # Index self._codes, self._group_index, - ) = index._get_grouper_for_level(self.grouper, ilevel) + ) = index._get_grouper_for_level(self.grouping_vector, ilevel) # a passed Grouper like, directly get the grouper in the same way # as single grouper groupby, use the group_info to get codes - elif isinstance(self.grouper, Grouper): + elif isinstance(self.grouping_vector, Grouper): # get the new grouper; we already have disambiguated # what key/level refer to exactly, don't need to # check again as we have by this point converted these # to an actual value (rather than a pd.Grouper) - _, newgrouper, newobj = self.grouper._get_grouper( + _, newgrouper, newobj = self.grouping_vector._get_grouper( # error: Value of type variable "FrameOrSeries" of "_get_grouper" # of "Grouper" cannot be "Optional[FrameOrSeries]" self.obj, # type: ignore[type-var] @@ -495,44 +495,46 @@ def __init__( ng = newgrouper._get_grouper() if isinstance(newgrouper, ops.BinGrouper): # in this case we have `ng is newgrouper` - self.grouper = ng + self.grouping_vector = ng else: # ops.BaseGrouper # use Index instead of ndarray so we can recover the name - self.grouper = Index(ng, name=newgrouper.result_index.name) + self.grouping_vector = Index(ng, name=newgrouper.result_index.name) - elif is_categorical_dtype(self.grouper): + elif is_categorical_dtype(self.grouping_vector): # a passed Categorical self._passed_categorical = True - self.grouper, self.all_grouper = recode_for_groupby( - self.grouper, self.sort, observed + self.grouping_vector, self.all_grouper = recode_for_groupby( + self.grouping_vector, self.sort, observed ) - elif not isinstance(self.grouper, (Series, Index, ExtensionArray, np.ndarray)): + elif not isinstance( + self.grouping_vector, (Series, Index, ExtensionArray, np.ndarray) + ): # no level passed - if getattr(self.grouper, "ndim", 1) != 1: - t = self.name or str(type(self.grouper)) + if getattr(self.grouping_vector, "ndim", 1) != 1: + t = self.name or str(type(self.grouping_vector)) raise ValueError(f"Grouper for '{t}' not 1-dimensional") - self.grouper = self.index.map(self.grouper) + self.grouping_vector = self.index.map(self.grouping_vector) if not ( - hasattr(self.grouper, "__len__") - and len(self.grouper) == len(self.index) + hasattr(self.grouping_vector, "__len__") + and len(self.grouping_vector) == len(self.index) ): - grper = pprint_thing(self.grouper) + grper = pprint_thing(self.grouping_vector) errmsg = ( "Grouper result violates len(labels) == " f"len(data)\nresult: {grper}" ) - self.grouper = None # Try for sanity + self.grouping_vector = None # Try for sanity raise AssertionError(errmsg) - if isinstance(self.grouper, np.ndarray): + if isinstance(self.grouping_vector, np.ndarray): # if we have a date/time-like grouper, make sure that we have # Timestamps like - self.grouper = sanitize_to_nanoseconds(self.grouper) + self.grouping_vector = sanitize_to_nanoseconds(self.grouping_vector) def __repr__(self) -> str: return f"Grouping({self.name})" @@ -549,11 +551,11 @@ def name(self) -> Hashable: if isinstance(self._orig_grouper, (Index, Series)): return self._orig_grouper.name - elif isinstance(self.grouper, ops.BaseGrouper): - return self.grouper.result_index.name + elif isinstance(self.grouping_vector, ops.BaseGrouper): + return self.grouping_vector.result_index.name - elif isinstance(self.grouper, Index): - return self.grouper.name + elif isinstance(self.grouping_vector, Index): + return self.grouping_vector.name # otherwise we have ndarray or ExtensionArray -> no name return None @@ -580,10 +582,10 @@ def ngroups(self) -> int: @cache_readonly def indices(self): # we have a list of groupers - if isinstance(self.grouper, ops.BaseGrouper): - return self.grouper.indices + if isinstance(self.grouping_vector, ops.BaseGrouper): + return self.grouping_vector.indices - values = Categorical(self.grouper) + values = Categorical(self.grouping_vector) return values._reverse_indexer() @property @@ -624,7 +626,7 @@ def _codes_and_uniques(self) -> tuple[np.ndarray, ArrayLike]: if self._passed_categorical: # we make a CategoricalIndex out of the cat grouper # preserving the categories / ordered attributes - cat = self.grouper + cat = self.grouping_vector categories = cat.categories if self.observed: @@ -640,10 +642,10 @@ def _codes_and_uniques(self) -> tuple[np.ndarray, ArrayLike]: ) return cat.codes, uniques - elif isinstance(self.grouper, ops.BaseGrouper): + elif isinstance(self.grouping_vector, ops.BaseGrouper): # we have a list of groupers - codes = self.grouper.codes_info - uniques = self.grouper.result_arraylike + codes = self.grouping_vector.codes_info + uniques = self.grouping_vector.result_arraylike else: # GH35667, replace dropna=False with na_sentinel=None if not self.dropna: @@ -651,7 +653,7 @@ def _codes_and_uniques(self) -> tuple[np.ndarray, ArrayLike]: else: na_sentinel = -1 codes, uniques = algorithms.factorize( - self.grouper, sort=self.sort, na_sentinel=na_sentinel + self.grouping_vector, sort=self.sort, na_sentinel=na_sentinel ) return codes, uniques diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 746c6e0056064..b995a74c20a40 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -734,7 +734,7 @@ def _get_grouper(self): We have a specific method of grouping, so cannot convert to a Index for our grouper. """ - return self.groupings[0].grouper + return self.groupings[0].grouping_vector @final def _get_group_keys(self): @@ -858,7 +858,7 @@ def groups(self) -> dict[Hashable, np.ndarray]: if len(self.groupings) == 1: return self.groupings[0].groups else: - to_groupby = zip(*(ping.grouper for ping in self.groupings)) + to_groupby = zip(*(ping.grouping_vector for ping in self.groupings)) index = Index(to_groupby) return self.axis.groupby(index) diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py index 30b115b9dba6f..9b2792f3b0aea 100644 --- a/pandas/tests/extension/base/groupby.py +++ b/pandas/tests/extension/base/groupby.py @@ -15,8 +15,8 @@ def test_grouping_grouper(self, data_for_grouping): gr1 = df.groupby("A").grouper.groupings[0] gr2 = df.groupby("B").grouper.groupings[0] - tm.assert_numpy_array_equal(gr1.grouper, df.A.values) - tm.assert_extension_array_equal(gr2.grouper, data_for_grouping) + tm.assert_numpy_array_equal(gr1.grouping_vector, df.A.values) + tm.assert_extension_array_equal(gr2.grouping_vector, data_for_grouping) @pytest.mark.parametrize("as_index", [True, False]) def test_groupby_extension_agg(self, as_index, data_for_grouping): diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index 33d82a1d64fb7..8a52734b27bc7 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -262,8 +262,8 @@ def test_grouping_grouper(self, data_for_grouping): gr1 = df.groupby("A").grouper.groupings[0] gr2 = df.groupby("B").grouper.groupings[0] - tm.assert_numpy_array_equal(gr1.grouper, df.A.values) - tm.assert_extension_array_equal(gr2.grouper, data_for_grouping) + tm.assert_numpy_array_equal(gr1.grouping_vector, df.A.values) + tm.assert_extension_array_equal(gr2.grouping_vector, data_for_grouping) @pytest.mark.parametrize("as_index", [True, False]) def test_groupby_extension_agg(self, as_index, data_for_grouping): diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index b601ba92886d9..0a33a2bbe1d0a 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -161,7 +161,7 @@ def test_agg_grouping_is_list_tuple(ts): df = tm.makeTimeDataFrame() grouped = df.groupby(lambda x: x.year) - grouper = grouped.grouper.groupings[0].grouper + grouper = grouped.grouper.groupings[0].grouping_vector grouped.grouper.groupings[0] = Grouping(ts.index, list(grouper)) result = grouped.agg(np.mean)
Too many things have a .grouper attribute which makes it really difficult to follow what type of object we're dealing with at different places in the stack. This changes the most-ambiguous attribute to grouping_vector. I'm open to other names.
https://api.github.com/repos/pandas-dev/pandas/pulls/41532
2021-05-18T01:11:05Z
2021-05-19T02:48:38Z
2021-05-19T02:48:38Z
2021-05-19T04:58:20Z
REF: DataFrame._values return DTA/TDA where appropriate
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index efefeb23445af..1fa149cd834b0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -857,26 +857,37 @@ def _can_fast_transpose(self) -> bool: # TODO(EA2D) special case would be unnecessary with 2D EAs return not is_1d_only_ea_dtype(dtype) + # error: Return type "Union[ndarray, DatetimeArray, TimedeltaArray]" of + # "_values" incompatible with return type "ndarray" in supertype "NDFrame" @property - def _values_compat(self) -> np.ndarray | DatetimeArray | TimedeltaArray: + def _values( # type: ignore[override] + self, + ) -> np.ndarray | DatetimeArray | TimedeltaArray: """ Analogue to ._values that may return a 2D ExtensionArray. """ + self._consolidate_inplace() + mgr = self._mgr + if isinstance(mgr, ArrayManager): - return self._values + if len(mgr.arrays) == 1 and not is_1d_only_ea_obj(mgr.arrays[0]): + # error: Item "ExtensionArray" of "Union[ndarray, ExtensionArray]" + # has no attribute "reshape" + return mgr.arrays[0].reshape(-1, 1) # type: ignore[union-attr] + return self.values blocks = mgr.blocks if len(blocks) != 1: - return self._values + return self.values arr = blocks[0].values if arr.ndim == 1: # non-2D ExtensionArray - return self._values + return self.values # more generally, whatever we allow in NDArrayBackedExtensionBlock - arr = cast("DatetimeArray | TimedeltaArray", arr) + arr = cast("np.ndarray | DatetimeArray | TimedeltaArray", arr) return arr.T # ---------------------------------------------------------------------- @@ -3322,7 +3333,7 @@ def transpose(self, *args, copy: bool = False) -> DataFrame: if self._can_fast_transpose: # Note: tests pass without this, but this improves perf quite a bit. - new_vals = self._values_compat.T + new_vals = self._values.T if copy: new_vals = new_vals.copy() @@ -10621,11 +10632,6 @@ def values(self) -> np.ndarray: self._consolidate_inplace() return self._mgr.as_array(transpose=True) - @property - def _values(self) -> np.ndarray: - """internal implementation""" - return self.values - DataFrame._add_numeric_operations() diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index ea31f9663cffe..323aa45874d96 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -759,7 +759,8 @@ def _slice_take_blocks_ax0( blk = self.blocks[blkno] # Otherwise, slicing along items axis is necessary. - if not blk._can_consolidate: + if not blk._can_consolidate and not blk._validate_ndim: + # i.e. we dont go through here for DatetimeTZBlock # A non-consolidatable block, it's easy, because there's # only one item and each mgr loc is a copy of that single # item. diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py index 548482b23ebc4..2ff991b62b67e 100644 --- a/pandas/tests/frame/methods/test_values.py +++ b/pandas/tests/frame/methods/test_values.py @@ -223,3 +223,54 @@ def test_values_lcd(self, mixed_float_frame, mixed_int_frame): values = mixed_int_frame[["C"]].values assert values.dtype == np.uint8 + + +class TestPrivateValues: + def test_private_values_dt64tz(self, using_array_manager, request): + if using_array_manager: + mark = pytest.mark.xfail(reason="doesn't share memory") + request.node.add_marker(mark) + + dta = date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1) + + df = DataFrame(dta, columns=["A"]) + tm.assert_equal(df._values, dta) + + # we have a view + assert np.shares_memory(df._values._ndarray, dta._ndarray) + + # TimedeltaArray + tda = dta - dta + df2 = df - df + tm.assert_equal(df2._values, tda) + + @td.skip_array_manager_invalid_test + def test_private_values_dt64tz_multicol(self): + dta = date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2) + + df = DataFrame(dta, columns=["A", "B"]) + tm.assert_equal(df._values, dta) + + # we have a view + assert np.shares_memory(df._values._ndarray, dta._ndarray) + + # TimedeltaArray + tda = dta - dta + df2 = df - df + tm.assert_equal(df2._values, tda) + + def test_private_values_dt64_multiblock(self, using_array_manager, request): + if using_array_manager: + mark = pytest.mark.xfail(reason="returns ndarray") + request.node.add_marker(mark) + + dta = date_range("2000", periods=8)._data + + df = DataFrame({"A": dta[:4]}, copy=False) + df["B"] = dta[4:] + + assert len(df._mgr.arrays) == 2 + + result = df._values + expected = dta.reshape(2, 4).T + tm.assert_equal(result, expected)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41531
2021-05-17T23:46:35Z
2021-05-19T02:55:06Z
2021-05-19T02:55:06Z
2021-05-19T04:56:39Z
REF: make Grouping less stateful
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 970e3c4ac80f4..e2855cbc90425 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -10,6 +10,7 @@ import numpy as np from pandas._typing import ( + ArrayLike, FrameOrSeries, final, ) @@ -587,20 +588,23 @@ def indices(self): @property def codes(self) -> np.ndarray: - if self._passed_categorical: - # we make a CategoricalIndex out of the cat grouper - # preserving the categories / ordered attributes - cat = self.grouper - return cat.codes + if self._codes is not None: + # _codes is set in __init__ for MultiIndex cases + return self._codes - if self._codes is None: - self._make_codes() - # error: Incompatible return value type (got "Optional[ndarray]", - # expected "ndarray") - return self._codes # type: ignore[return-value] + return self._codes_and_uniques[0] + + @cache_readonly + def group_arraylike(self) -> ArrayLike: + """ + Analogous to result_index, but holding an ArrayLike to ensure + we can can retain ExtensionDtypes. + """ + return self._codes_and_uniques[1] @cache_readonly def result_index(self) -> Index: + # TODO: what's the difference between result_index vs group_index? if self.all_grouper is not None: group_idx = self.group_index assert isinstance(group_idx, CategoricalIndex) @@ -609,6 +613,14 @@ def result_index(self) -> Index: @cache_readonly def group_index(self) -> Index: + if self._group_index is not None: + # _group_index is set in __init__ for MultiIndex cases + return self._group_index + uniques = self.group_arraylike + return Index(uniques, name=self.name) + + @cache_readonly + def _codes_and_uniques(self) -> tuple[np.ndarray, ArrayLike]: if self._passed_categorical: # we make a CategoricalIndex out of the cat grouper # preserving the categories / ordered attributes @@ -616,33 +628,22 @@ def group_index(self) -> Index: categories = cat.categories if self.observed: - codes = algorithms.unique1d(cat.codes) - codes = codes[codes != -1] + ucodes = algorithms.unique1d(cat.codes) + ucodes = ucodes[ucodes != -1] if self.sort or cat.ordered: - codes = np.sort(codes) + ucodes = np.sort(ucodes) else: - codes = np.arange(len(categories)) + ucodes = np.arange(len(categories)) - return CategoricalIndex( - Categorical.from_codes( - codes=codes, categories=categories, ordered=cat.ordered - ), - name=self.name, + uniques = Categorical.from_codes( + codes=ucodes, categories=categories, ordered=cat.ordered ) + return cat.codes, uniques - if self._group_index is None: - self._make_codes() - assert self._group_index is not None - return self._group_index - - def _make_codes(self) -> None: - if self._codes is not None and self._group_index is not None: - return - - # we have a list of groupers - if isinstance(self.grouper, ops.BaseGrouper): + elif isinstance(self.grouper, ops.BaseGrouper): + # we have a list of groupers codes = self.grouper.codes_info - uniques = self.grouper.result_index + uniques = self.grouper.result_arraylike else: # GH35667, replace dropna=False with na_sentinel=None if not self.dropna: @@ -652,9 +653,7 @@ def _make_codes(self) -> None: codes, uniques = algorithms.factorize( self.grouper, sort=self.sort, na_sentinel=na_sentinel ) - uniques = Index(uniques, name=self.name) - self._codes = codes - self._group_index = uniques + return codes, uniques @cache_readonly def groups(self) -> dict[Hashable, np.ndarray]: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index b37467fb8cf11..746c6e0056064 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -907,6 +907,19 @@ def reconstructed_codes(self) -> list[np.ndarray]: ids, obs_ids, _ = self.group_info return decons_obs_group_ids(ids, obs_ids, self.shape, codes, xnull=True) + @cache_readonly + def result_arraylike(self) -> ArrayLike: + """ + Analogous to result_index, but returning an ndarray/ExtensionArray + allowing us to retain ExtensionDtypes not supported by Index. + """ + # TODO: once Index supports arbitrary EAs, this can be removed in favor + # of result_index + if len(self.groupings) == 1: + return self.groupings[0].group_arraylike + + return self.result_index._values + @cache_readonly def result_index(self) -> Index: if len(self.groupings) == 1: @@ -919,7 +932,7 @@ def result_index(self) -> Index: ) @final - def get_group_levels(self) -> list[Index]: + def get_group_levels(self) -> list[ArrayLike]: # Note: only called from _insert_inaxis_grouper_inplace, which # is only called for BaseGrouper, never for BinGrouper if len(self.groupings) == 1:
This gets rid of _make_codes, which sets two state variables, in favor of a cache_readonly _codes_and_uniques
https://api.github.com/repos/pandas-dev/pandas/pulls/41529
2021-05-17T22:54:29Z
2021-05-18T22:35:50Z
2021-05-18T22:35:50Z
2021-05-18T22:43:40Z
REF: simplify Grouping.__init__
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 4aac2630feb2c..970e3c4ac80f4 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -500,34 +500,33 @@ def __init__( # use Index instead of ndarray so we can recover the name self.grouper = Index(ng, name=newgrouper.result_index.name) - else: + elif is_categorical_dtype(self.grouper): # a passed Categorical - if is_categorical_dtype(self.grouper): - self._passed_categorical = True + self._passed_categorical = True - self.grouper, self.all_grouper = recode_for_groupby( - self.grouper, self.sort, observed - ) + self.grouper, self.all_grouper = recode_for_groupby( + self.grouper, self.sort, observed + ) + elif not isinstance(self.grouper, (Series, Index, ExtensionArray, np.ndarray)): # no level passed - elif not isinstance( - self.grouper, (Series, Index, ExtensionArray, np.ndarray) + if getattr(self.grouper, "ndim", 1) != 1: + t = self.name or str(type(self.grouper)) + raise ValueError(f"Grouper for '{t}' not 1-dimensional") + + self.grouper = self.index.map(self.grouper) + + if not ( + hasattr(self.grouper, "__len__") + and len(self.grouper) == len(self.index) ): - if getattr(self.grouper, "ndim", 1) != 1: - t = self.name or str(type(self.grouper)) - raise ValueError(f"Grouper for '{t}' not 1-dimensional") - self.grouper = self.index.map(self.grouper) - if not ( - hasattr(self.grouper, "__len__") - and len(self.grouper) == len(self.index) - ): - grper = pprint_thing(self.grouper) - errmsg = ( - "Grouper result violates len(labels) == " - f"len(data)\nresult: {grper}" - ) - self.grouper = None # Try for sanity - raise AssertionError(errmsg) + grper = pprint_thing(self.grouper) + errmsg = ( + "Grouper result violates len(labels) == " + f"len(data)\nresult: {grper}" + ) + self.grouper = None # Try for sanity + raise AssertionError(errmsg) if isinstance(self.grouper, np.ndarray): # if we have a date/time-like grouper, make sure that we have @@ -555,6 +554,7 @@ def name(self) -> Hashable: elif isinstance(self.grouper, Index): return self.grouper.name + # otherwise we have ndarray or ExtensionArray -> no name return None @cache_readonly
just de-nesting conditions in `__init__`
https://api.github.com/repos/pandas-dev/pandas/pulls/41528
2021-05-17T22:53:23Z
2021-05-18T16:46:08Z
2021-05-18T16:46:08Z
2021-05-18T17:25:53Z
REF: tighten types on maybe_infer_to_datetimelike
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index f3133480108a6..9523c2e3e62e0 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -682,6 +682,13 @@ def _try_cast( subarr = construct_1d_object_array_from_listlike(arr) return subarr + if dtype is None and isinstance(arr, list): + # filter out cases that we _dont_ want to go through maybe_cast_to_datetime + varr = np.array(arr, copy=False) + if varr.dtype != object or varr.size == 0: + return varr + arr = varr + try: # GH#15832: Check if we are requesting a numeric dtype and # that we can convert the data to the requested dtype. diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 46dc97214e2f6..3cc54fb912014 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1475,7 +1475,9 @@ def maybe_castable(dtype: np.dtype) -> bool: return dtype.name not in POSSIBLY_CAST_DTYPES -def maybe_infer_to_datetimelike(value: np.ndarray | list): +def maybe_infer_to_datetimelike( + value: np.ndarray, +) -> np.ndarray | DatetimeArray | TimedeltaArray: """ we might have a array (or single object) that is datetime like, and no dtype is passed don't change the value unless we find a @@ -1486,18 +1488,19 @@ def maybe_infer_to_datetimelike(value: np.ndarray | list): Parameters ---------- - value : np.ndarray or list + value : np.ndarray[object] + + Returns + ------- + np.ndarray, DatetimeArray, or TimedeltaArray """ - if not isinstance(value, (np.ndarray, list)): + if not isinstance(value, np.ndarray) or value.dtype != object: + # Caller is responsible for passing only ndarray[object] raise TypeError(type(value)) # pragma: no cover v = np.array(value, copy=False) - # we only care about object dtypes - if not is_object_dtype(v.dtype): - return value - shape = v.shape if v.ndim != 1: v = v.ravel() @@ -1575,6 +1578,8 @@ def maybe_cast_to_datetime( """ try to cast the array/value to a datetimelike dtype, converting float nan to iNaT + + We allow a list *only* when dtype is not None. """ from pandas.core.arrays.datetimes import sequence_to_datetimes from pandas.core.arrays.timedeltas import sequence_to_td64ns @@ -1666,11 +1671,10 @@ def maybe_cast_to_datetime( value = maybe_infer_to_datetimelike(value) elif isinstance(value, list): - # only do this if we have an array and the dtype of the array is not - # setup already we are not an integer/object, so don't bother with this - # conversion - - value = maybe_infer_to_datetimelike(value) + # we only get here with dtype=None, which we do not allow + raise ValueError( + "maybe_cast_to_datetime allows a list *only* if dtype is not None" + ) return value diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 00efc695ff04a..ba9d36467844c 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -357,8 +357,8 @@ def ndarray_to_mgr( if values.ndim == 2 and values.shape[0] != 1: # transpose and separate blocks - dvals_list = [maybe_infer_to_datetimelike(row) for row in values] - dvals_list = [ensure_block_shape(dval, 2) for dval in dvals_list] + dtlike_vals = [maybe_infer_to_datetimelike(row) for row in values] + dvals_list = [ensure_block_shape(dval, 2) for dval in dtlike_vals] # TODO: What about re-joining object columns? block_values = [
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41527
2021-05-17T22:49:46Z
2021-05-19T02:53:12Z
2021-05-19T02:53:12Z
2021-05-19T04:56:57Z
BUG: lib.infer_dtype with mixed-freq Periods
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 9298bc6a61bae..25e482fea60ee 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -228,7 +228,7 @@ Other enhancements - Constructing a :class:`DataFrame` or :class:`Series` with the ``data`` argument being a Python iterable that is *not* a NumPy ``ndarray`` consisting of NumPy scalars will now result in a dtype with a precision the maximum of the NumPy scalars; this was already the case when ``data`` is a NumPy ``ndarray`` (:issue:`40908`) - Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`) - Add keyword ``dropna`` to :meth:`DataFrame.value_counts` to allow counting rows that include ``NA`` values (:issue:`41325`) -- +- :meth:`Series.replace` will now cast results to ``PeriodDtype`` where possible instead of ``object`` dtype (:issue:`41526`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index 9dbc47f1d40f7..5e1cc612bed57 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -40,7 +40,6 @@ def is_integer(val: object) -> bool: ... def is_float(val: object) -> bool: ... def is_interval_array(values: np.ndarray) -> bool: ... -def is_period_array(values: np.ndarray) -> bool: ... def is_datetime64_array(values: np.ndarray) -> bool: ... def is_timedelta_or_timedelta64_array(values: np.ndarray) -> bool: ... def is_datetime_with_singletz_array(values: np.ndarray) -> bool: ... @@ -67,50 +66,60 @@ def map_infer( @overload # both convert_datetime and convert_to_nullable_integer False -> np.ndarray def maybe_convert_objects( objects: np.ndarray, # np.ndarray[object] + *, try_float: bool = ..., safe: bool = ..., convert_datetime: Literal[False] = ..., convert_timedelta: bool = ..., + convert_period: Literal[False] = ..., convert_to_nullable_integer: Literal[False] = ..., ) -> np.ndarray: ... @overload def maybe_convert_objects( objects: np.ndarray, # np.ndarray[object] + *, try_float: bool = ..., safe: bool = ..., - convert_datetime: Literal[False] = False, + convert_datetime: bool = ..., convert_timedelta: bool = ..., + convert_period: bool = ..., convert_to_nullable_integer: Literal[True] = ..., ) -> ArrayLike: ... @overload def maybe_convert_objects( objects: np.ndarray, # np.ndarray[object] + *, try_float: bool = ..., safe: bool = ..., convert_datetime: Literal[True] = ..., convert_timedelta: bool = ..., - convert_to_nullable_integer: Literal[False] = ..., + convert_period: bool = ..., + convert_to_nullable_integer: bool = ..., ) -> ArrayLike: ... @overload def maybe_convert_objects( objects: np.ndarray, # np.ndarray[object] + *, try_float: bool = ..., safe: bool = ..., - convert_datetime: Literal[True] = ..., + convert_datetime: bool = ..., convert_timedelta: bool = ..., - convert_to_nullable_integer: Literal[True] = ..., + convert_period: Literal[True] = ..., + convert_to_nullable_integer: bool = ..., ) -> ArrayLike: ... @overload def maybe_convert_objects( objects: np.ndarray, # np.ndarray[object] + *, try_float: bool = ..., safe: bool = ..., convert_datetime: bool = ..., convert_timedelta: bool = ..., + convert_period: bool = ..., convert_to_nullable_integer: bool = ..., ) -> ArrayLike: ... diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index e1cb744c7033c..cbef4ed44dc06 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1186,6 +1186,7 @@ cdef class Seen: bint coerce_numeric # coerce data to numeric bint timedelta_ # seen_timedelta bint datetimetz_ # seen_datetimetz + bint period_ # seen_period def __cinit__(self, bint coerce_numeric=False): """ @@ -1210,6 +1211,7 @@ cdef class Seen: self.datetime_ = False self.timedelta_ = False self.datetimetz_ = False + self.period_ = False self.coerce_numeric = coerce_numeric cdef inline bint check_uint64_conflict(self) except -1: @@ -1996,18 +1998,35 @@ cpdef bint is_time_array(ndarray values, bint skipna=False): return validator.validate(values) -cdef class PeriodValidator(TemporalValidator): - cdef inline bint is_value_typed(self, object value) except -1: - return is_period_object(value) +cdef bint is_period_array(ndarray[object] values): + """ + Is this an ndarray of Period objects (or NaT) with a single `freq`? + """ + cdef: + Py_ssize_t i, n = len(values) + int dtype_code = -10000 # i.e. c_FreqGroup.FR_UND + object val - cdef inline bint is_valid_null(self, object value) except -1: - return checknull_with_nat(value) + if len(values) == 0: + return False + for val in values: + if is_period_object(val): + if dtype_code == -10000: + dtype_code = val._dtype._dtype_code + elif dtype_code != val._dtype._dtype_code: + # mismatched freqs + return False + elif checknull_with_nat(val): + pass + else: + # Not a Period or NaT-like + return False -cpdef bint is_period_array(ndarray values): - cdef: - PeriodValidator validator = PeriodValidator(len(values), skipna=True) - return validator.validate(values) + if dtype_code == -10000: + # we saw all-NaTs, no actual Periods + return False + return True cdef class IntervalValidator(Validator): @@ -2249,9 +2268,13 @@ def maybe_convert_numeric( @cython.boundscheck(False) @cython.wraparound(False) -def maybe_convert_objects(ndarray[object] objects, bint try_float=False, - bint safe=False, bint convert_datetime=False, +def maybe_convert_objects(ndarray[object] objects, + *, + bint try_float=False, + bint safe=False, + bint convert_datetime=False, bint convert_timedelta=False, + bint convert_period=False, bint convert_to_nullable_integer=False) -> "ArrayLike": """ Type inference function-- convert object array to proper dtype @@ -2272,6 +2295,9 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, convert_timedelta : bool, default False If an array-like object contains only timedelta values or NaT is encountered, whether to convert and return an array of m8[ns] dtype. + convert_period : bool, default False + If an array-like object contains only (homogeneous-freq) Period values + or NaT, whether to convert and return a PeriodArray. convert_to_nullable_integer : bool, default False If an array-like object contains only integer values (and NaN) is encountered, whether to convert and return an IntegerArray. @@ -2292,7 +2318,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, int64_t[:] itimedeltas Seen seen = Seen() object val - float64_t fval, fnan + float64_t fval, fnan = np.nan n = len(objects) @@ -2311,8 +2337,6 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, timedeltas = np.empty(n, dtype='m8[ns]') itimedeltas = timedeltas.view(np.int64) - fnan = np.nan - for i in range(n): val = objects[i] if itemsize_max != -1: @@ -2330,7 +2354,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, idatetimes[i] = NPY_NAT if convert_timedelta: itimedeltas[i] = NPY_NAT - if not (convert_datetime or convert_timedelta): + if not (convert_datetime or convert_timedelta or convert_period): seen.object_ = True break elif val is np.nan: @@ -2343,14 +2367,6 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, elif util.is_float_object(val): floats[i] = complexes[i] = val seen.float_ = True - elif util.is_datetime64_object(val): - if convert_datetime: - idatetimes[i] = convert_to_tsobject( - val, None, None, 0, 0).value - seen.datetime_ = True - else: - seen.object_ = True - break elif is_timedelta(val): if convert_timedelta: itimedeltas[i] = convert_to_timedelta64(val, "ns").view("i8") @@ -2396,6 +2412,13 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, else: seen.object_ = True break + elif is_period_object(val): + if convert_period: + seen.period_ = True + break + else: + seen.object_ = True + break elif try_float and not isinstance(val, str): # this will convert Decimal objects try: @@ -2419,6 +2442,14 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, return dti._data seen.object_ = True + if seen.period_: + if is_period_array(objects): + from pandas import PeriodIndex + pi = PeriodIndex(objects) + + # unbox to PeriodArray + return pi._data + if not seen.object_: result = None if not safe: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 286fd8bf8ba4a..a3c58b6c6ae15 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -261,7 +261,7 @@ def _box_values(self, values) -> np.ndarray: """ apply box func to passed values """ - return lib.map_infer(values, self._box_func) + return lib.map_infer(values, self._box_func, convert=False) def __iter__(self): if self.ndim > 1: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 46dc97214e2f6..783474c53f304 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1315,6 +1315,7 @@ def soft_convert_objects( datetime: bool = True, numeric: bool = True, timedelta: bool = True, + period: bool = True, copy: bool = True, ) -> ArrayLike: """ @@ -1327,6 +1328,7 @@ def soft_convert_objects( datetime : bool, default True numeric: bool, default True timedelta : bool, default True + period : bool, default True copy : bool, default True Returns @@ -1348,7 +1350,10 @@ def soft_convert_objects( # bound of nanosecond-resolution 64-bit integers. try: converted = lib.maybe_convert_objects( - values, convert_datetime=datetime, convert_timedelta=timedelta + values, + convert_datetime=datetime, + convert_timedelta=timedelta, + convert_period=period, ) except (OutOfBoundsDatetime, ValueError): return values diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index d16dda370c498..09efa97871fae 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1105,8 +1105,9 @@ def test_infer_dtype_period(self): arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="D")]) assert lib.infer_dtype(arr, skipna=True) == "period" + # non-homogeneous freqs -> mixed arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="M")]) - assert lib.infer_dtype(arr, skipna=True) == "period" + assert lib.infer_dtype(arr, skipna=True) == "mixed" @pytest.mark.parametrize("klass", [pd.array, Series, Index]) @pytest.mark.parametrize("skipna", [True, False]) @@ -1121,6 +1122,18 @@ def test_infer_dtype_period_array(self, klass, skipna): ) assert lib.infer_dtype(values, skipna=skipna) == "period" + # periods but mixed freq + values = klass( + [ + Period("2011-01-01", freq="D"), + Period("2011-01-02", freq="M"), + pd.NaT, + ] + ) + # with pd.array this becomes PandasArray which ends up as "unknown-array" + exp = "unknown-array" if klass is pd.array else "mixed" + assert lib.infer_dtype(values, skipna=skipna) == exp + def test_infer_dtype_period_mixed(self): arr = np.array( [Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object @@ -1319,7 +1332,6 @@ def test_is_datetimelike_array_all_nan_nat_like(self): "is_date_array", "is_time_array", "is_interval_array", - "is_period_array", ], ) def test_other_dtypes_for_array(self, func): diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index e6e992d37fd5d..645de6f193750 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1021,11 +1021,9 @@ def test_replace_period(self): columns=["fname"], ) assert set(df.fname.values) == set(d["fname"].keys()) - # We don't support converting object -> specialized EA in - # replace yet. - expected = DataFrame( - {"fname": [d["fname"][k] for k in df.fname.values]}, dtype=object - ) + + expected = DataFrame({"fname": [d["fname"][k] for k in df.fname.values]}) + assert expected.dtypes[0] == "Period[M]" result = df.replace(d) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_describe.py b/pandas/tests/series/methods/test_describe.py index bdb308ddbfd58..e6c6016d2b3a1 100644 --- a/pandas/tests/series/methods/test_describe.py +++ b/pandas/tests/series/methods/test_describe.py @@ -11,31 +11,35 @@ class TestSeriesDescribe: - def test_describe(self): - s = Series([0, 1, 2, 3, 4], name="int_data") - result = s.describe() + def test_describe_ints(self): + ser = Series([0, 1, 2, 3, 4], name="int_data") + result = ser.describe() expected = Series( - [5, 2, s.std(), 0, 1, 2, 3, 4], + [5, 2, ser.std(), 0, 1, 2, 3, 4], name="int_data", index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], ) tm.assert_series_equal(result, expected) - s = Series([True, True, False, False, False], name="bool_data") - result = s.describe() + def test_describe_bools(self): + ser = Series([True, True, False, False, False], name="bool_data") + result = ser.describe() expected = Series( [5, 2, False, 3], name="bool_data", index=["count", "unique", "top", "freq"] ) tm.assert_series_equal(result, expected) - s = Series(["a", "a", "b", "c", "d"], name="str_data") - result = s.describe() + def test_describe_strs(self): + + ser = Series(["a", "a", "b", "c", "d"], name="str_data") + result = ser.describe() expected = Series( [5, 4, "a", 2], name="str_data", index=["count", "unique", "top", "freq"] ) tm.assert_series_equal(result, expected) - s = Series( + def test_describe_timedelta64(self): + ser = Series( [ Timedelta("1 days"), Timedelta("2 days"), @@ -45,21 +49,22 @@ def test_describe(self): ], name="timedelta_data", ) - result = s.describe() + result = ser.describe() expected = Series( - [5, s[2], s.std(), s[0], s[1], s[2], s[3], s[4]], + [5, ser[2], ser.std(), ser[0], ser[1], ser[2], ser[3], ser[4]], name="timedelta_data", index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], ) tm.assert_series_equal(result, expected) - s = Series( + def test_describe_period(self): + ser = Series( [Period("2020-01", "M"), Period("2020-01", "M"), Period("2019-12", "M")], name="period_data", ) - result = s.describe() + result = ser.describe() expected = Series( - [3, 2, s[0], 2], + [3, 2, ser[0], 2], name="period_data", index=["count", "unique", "top", "freq"], )
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry Also adds a convert_period option to lib.maybe_infer_objects
https://api.github.com/repos/pandas-dev/pandas/pulls/41526
2021-05-17T20:22:52Z
2021-05-18T22:23:22Z
2021-05-18T22:23:22Z
2021-05-18T22:27:21Z
Allow deprecate_nonkeyword_arguments to not specify version, show class name
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 4b81b69976c62..cf2246f917bbe 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -329,7 +329,7 @@ ) -@deprecate_nonkeyword_arguments(allowed_args=2, version="2.0") +@deprecate_nonkeyword_arguments(allowed_args=["io", "sheet_name"], version="2.0") @Appender(_read_excel_doc) def read_excel( io, diff --git a/pandas/tests/util/test_deprecate_nonkeyword_arguments.py b/pandas/tests/util/test_deprecate_nonkeyword_arguments.py index 05bc617232bdd..a20264ac6fbb0 100644 --- a/pandas/tests/util/test_deprecate_nonkeyword_arguments.py +++ b/pandas/tests/util/test_deprecate_nonkeyword_arguments.py @@ -68,7 +68,7 @@ def test_three_positional_argument_with_warning_message_analysis(): for actual_warning in w: assert actual_warning.category == FutureWarning assert str(actual_warning.message) == ( - "Starting with Pandas version 1.1 all arguments of g " + "Starting with pandas version 1.1 all arguments of g " "except for the argument 'a' will be keyword-only" ) @@ -96,6 +96,21 @@ def test_one_positional_argument_with_warning_message_analysis(): for actual_warning in w: assert actual_warning.category == FutureWarning assert str(actual_warning.message) == ( - "Starting with Pandas version 1.1 all arguments " + "Starting with pandas version 1.1 all arguments " "of h will be keyword-only" ) + + +class Foo: + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "bar"]) + def baz(self, bar=None, foobar=None): + ... + + +def test_class(): + msg = ( + r"In a future version of pandas all arguments of Foo\.baz " + r"except for the argument \'bar\' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + Foo().baz("qux", "quox") diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index 835001b3e1829..f4c360f476514 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -211,7 +211,7 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]: return _deprecate_kwarg -def _format_argument_list(allow_args: list[str] | int): +def _format_argument_list(allow_args: list[str]): """ Convert the allow_args argument (either string or integer) of `deprecate_nonkeyword_arguments` function to a string describing @@ -231,21 +231,16 @@ def _format_argument_list(allow_args: list[str] | int): Examples -------- - `format_argument_list(0)` -> '' - `format_argument_list(1)` -> 'except for the first argument' - `format_argument_list(2)` -> 'except for the first 2 arguments' `format_argument_list([])` -> '' `format_argument_list(['a'])` -> "except for the arguments 'a'" `format_argument_list(['a', 'b'])` -> "except for the arguments 'a' and 'b'" `format_argument_list(['a', 'b', 'c'])` -> "except for the arguments 'a', 'b' and 'c'" """ + if "self" in allow_args: + allow_args.remove("self") if not allow_args: return "" - elif allow_args == 1: - return " except for the first argument" - elif isinstance(allow_args, int): - return f" except for the first {allow_args} arguments" elif len(allow_args) == 1: return f" except for the argument '{allow_args[0]}'" else: @@ -254,9 +249,17 @@ def _format_argument_list(allow_args: list[str] | int): return f" except for the arguments {args} and '{last}'" +def future_version_msg(version: str | None) -> str: + """Specify which version of pandas the deprecation will take place in.""" + if version is None: + return "In a future version of pandas" + else: + return f"Starting with pandas version {version}" + + def deprecate_nonkeyword_arguments( - version: str, - allowed_args: list[str] | int | None = None, + version: str | None, + allowed_args: list[str] | None = None, stacklevel: int = 2, ) -> Callable: """ @@ -266,14 +269,13 @@ def deprecate_nonkeyword_arguments( ---------- version : str The version in which positional arguments will become - keyword-only. + keyword-only. If None, then the warning message won't + specify any particular version. - allowed_args : list or int, optional + allowed_args : list, optional In case of list, it must be the list of names of some first arguments of the decorated functions that are - OK to be given as positional arguments. In case of an - integer, this is the number of positional arguments - that will stay positional. In case of None value, + OK to be given as positional arguments. In case of None value, defaults to list of all arguments not having the default value. @@ -291,19 +293,21 @@ def decorate(func): assert spec.defaults is not None # for mypy allow_args = spec.args[: -len(spec.defaults)] + num_allow_args = len(allow_args) + msg = ( + f"{future_version_msg(version)} all arguments of " + f"{func.__qualname__}{{arguments}} will be keyword-only" + ) + @wraps(func) def wrapper(*args, **kwargs): arguments = _format_argument_list(allow_args) - if isinstance(allow_args, (list, tuple)): - num_allow_args = len(allow_args) - else: - num_allow_args = allow_args if len(args) > num_allow_args: - msg = ( - f"Starting with Pandas version {version} all arguments of " - f"{func.__name__}{arguments} will be keyword-only" + warnings.warn( + msg.format(arguments=arguments), + FutureWarning, + stacklevel=stacklevel, ) - warnings.warn(msg, FutureWarning, stacklevel=stacklevel) return func(*args, **kwargs) return wrapper
xref https://github.com/pandas-dev/pandas/pull/41511#discussion_r633386611 as request, ping @jreback @simonjayhawkins I've removed the ability to pass an integer to `allowed_arguments` as it added complexity, was only used once in the codebase anyway, and wasn't even covered by tests Now, if `version` is None, then it'll just print "In a future version of pandas", it'll show the class name (e.g. `Series.drop_duplicates` instead of just `drop_duplicates`) and won't print `'self'` in the warning message
https://api.github.com/repos/pandas-dev/pandas/pulls/41524
2021-05-17T19:15:42Z
2021-05-18T12:50:37Z
2021-05-18T12:50:37Z
2021-05-19T08:43:22Z
added deprecate_nonkeyword_arguments to function where
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 258e391b9220c..ce20006a8d3db 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -681,6 +681,7 @@ Deprecations - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) +- Deprecated passing arguments as positional in :meth:`DataFrame.where` and :meth:`Series.where` (other than ``"cond"`` and ``"other"``) (:issue:`41485`) .. _whatsnew_130.deprecations.nuisance_columns: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7b564d55a342c..a24585b68a9ea 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10688,6 +10688,21 @@ def interpolate( **kwargs, ) + @deprecate_nonkeyword_arguments( + version=None, allowed_args=["self", "cond", "other"] + ) + def where( + self, + cond, + other=np.nan, + inplace=False, + axis=None, + level=None, + errors="raise", + try_cast=lib.no_default, + ): + return super().where(cond, other, inplace, axis, level, errors, try_cast) + DataFrame._add_numeric_operations() diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6d7c803685255..ffebb30cda8db 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9073,7 +9073,6 @@ def _where( result = self._constructor(new_data) return result.__finalize__(self) - @final @doc( klass=_shared_doc_kwargs["klass"], cond="True", @@ -9221,7 +9220,7 @@ def where( "try_cast keyword is deprecated and will be removed in a " "future version", FutureWarning, - stacklevel=2, + stacklevel=4, ) return self._where(cond, other, inplace, axis, level, errors=errors) diff --git a/pandas/core/series.py b/pandas/core/series.py index 4eba0db7e98ec..2da98e5dfd020 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5310,6 +5310,21 @@ def interpolate( **kwargs, ) + @deprecate_nonkeyword_arguments( + version=None, allowed_args=["self", "cond", "other"] + ) + def where( + self, + cond, + other=np.nan, + inplace=False, + axis=None, + level=None, + errors="raise", + try_cast=lib.no_default, + ): + return super().where(cond, other, inplace, axis, level, errors, try_cast) + # ---------------------------------------------------------------------- # Add index _AXIS_ORDERS = ["index"] diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 32a499f6e9168..0405d150c0c04 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -757,3 +757,17 @@ def test_where_none_nan_coerce(): ) result = expected.where(expected.notnull(), None) tm.assert_frame_equal(result, expected) + + +def test_where_non_keyword_deprecation(): + # GH 41485 + s = DataFrame(range(5)) + msg = ( + "In a future version of pandas all arguments of " + "DataFrame.where except for the arguments 'cond' " + "and 'other' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.where(s > 1, 10, False) + expected = DataFrame([10, 10, 2, 3, 4]) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index b13fd18405839..0c6b9bd924759 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -141,6 +141,20 @@ def test_where(): tm.assert_series_equal(rs, expected) +def test_where_non_keyword_deprecation(): + # GH 41485 + s = Series(range(5)) + msg = ( + "In a future version of pandas all arguments of " + "Series.where except for the arguments 'cond' " + "and 'other' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.where(s > 1, 10, False) + expected = Series([10, 10, 2, 3, 4]) + tm.assert_series_equal(expected, result) + + def test_where_error(): s = Series(np.random.randn(5)) cond = s > 0
- xref #41486 - generic.where. tests added / passed - Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them. - whatsnew entry. -- added.
https://api.github.com/repos/pandas-dev/pandas/pulls/41523
2021-05-17T17:47:23Z
2021-05-26T01:47:34Z
2021-05-26T01:47:34Z
2021-05-26T06:04:51Z
TST: split pd.merge test with indicator=True
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index edd100219143c..77b155f01a2ea 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -102,6 +102,19 @@ def series_of_dtype_all_na(request): return request.param +@pytest.fixture +def dfs_for_indicator(): + df1 = DataFrame({"col1": [0, 1], "col_conflict": [1, 2], "col_left": ["a", "b"]}) + df2 = DataFrame( + { + "col1": [1, 2, 3, 4, 5], + "col_conflict": [1, 2, 3, 4, 5], + "col_right": [2, 2, 2, 2, 2], + } + ) + return df1, df2 + + class TestMerge: def setup_method(self, method): # aggregate multiple columns @@ -543,6 +556,7 @@ def check2(exp, kwarg): result = merge(left, right, how="outer", **kwarg) tm.assert_frame_equal(result, exp) + # TODO: should the next loop be un-indented? doing so breaks this test for kwarg in [ {"left_index": True, "right_index": True}, {"left_index": True, "right_on": "x"}, @@ -652,6 +666,7 @@ def test_merge_nan_right(self): ) tm.assert_frame_equal(result, expected, check_dtype=False) + def test_merge_nan_right2(self): df1 = DataFrame({"i1": [0, 1], "i2": [0.5, 1.5]}) df2 = DataFrame({"i1": [0], "i3": [0.7]}) result = df1.join(df2, rsuffix="_", on="i1") @@ -695,6 +710,9 @@ def test_join_append_timedeltas(self, using_array_manager): expected = expected.astype(object) tm.assert_frame_equal(result, expected) + def test_join_append_timedeltas2(self): + # timedelta64 issues with join/merge + # GH 5695 td = np.timedelta64(300000000) lhs = DataFrame(Series([td, td], index=["A", "B"])) rhs = DataFrame(Series([td], index=["A"])) @@ -806,6 +824,7 @@ def test_merge_on_datetime64tz(self): result = merge(left, right, on="key", how="outer") tm.assert_frame_equal(result, expected) + def test_merge_datetime64tz_values(self): left = DataFrame( { "key": [1, 2], @@ -923,6 +942,7 @@ def test_merge_on_periods(self): result = merge(left, right, on="key", how="outer") tm.assert_frame_equal(result, expected) + def test_merge_period_values(self): left = DataFrame( {"key": [1, 2], "value": pd.period_range("20151010", periods=2, freq="D")} ) @@ -944,20 +964,11 @@ def test_merge_on_periods(self): assert result["value_x"].dtype == "Period[D]" assert result["value_y"].dtype == "Period[D]" - def test_indicator(self): + def test_indicator(self, dfs_for_indicator): # PR #10054. xref #7412 and closes #8790. - df1 = DataFrame( - {"col1": [0, 1], "col_conflict": [1, 2], "col_left": ["a", "b"]} - ) + df1, df2 = dfs_for_indicator df1_copy = df1.copy() - df2 = DataFrame( - { - "col1": [1, 2, 3, 4, 5], - "col_conflict": [1, 2, 3, 4, 5], - "col_right": [2, 2, 2, 2, 2], - } - ) df2_copy = df2.copy() df_result = DataFrame( @@ -1016,14 +1027,19 @@ def test_indicator(self): ) tm.assert_frame_equal(test_custom_name, df_result_custom_name) + def test_merge_indicator_arg_validation(self, dfs_for_indicator): # Check only accepts strings and booleans + df1, df2 = dfs_for_indicator + msg = "indicator option can only accept boolean or string arguments" with pytest.raises(ValueError, match=msg): merge(df1, df2, on="col1", how="outer", indicator=5) with pytest.raises(ValueError, match=msg): df1.merge(df2, on="col1", how="outer", indicator=5) + def test_merge_indicator_result_integrity(self, dfs_for_indicator): # Check result integrity + df1, df2 = dfs_for_indicator test2 = merge(df1, df2, on="col1", how="left", indicator=True) assert (test2._merge != "right_only").all() @@ -1040,7 +1056,10 @@ def test_indicator(self): test4 = df1.merge(df2, on="col1", how="inner", indicator=True) assert (test4._merge == "both").all() + def test_merge_indicator_invalid(self, dfs_for_indicator): # Check if working name in df + df1, _ = dfs_for_indicator + for i in ["_right_indicator", "_left_indicator", "_merge"]: df_badcolumn = DataFrame({"col1": [1, 2], i: [2, 2]}) @@ -1071,6 +1090,7 @@ def test_indicator(self): df_badcolumn, on="col1", how="outer", indicator="custom_column_name" ) + def test_merge_indicator_multiple_columns(self): # Merge on multiple columns df3 = DataFrame({"col1": [0, 1], "col2": ["a", "b"]}) @@ -1538,6 +1558,8 @@ def test_merge_incompat_infer_boolean_object(self): result = merge(df2, df1, on="key") tm.assert_frame_equal(result, expected) + def test_merge_incompat_infer_boolean_object_with_missing(self): + # GH21119: bool + object bool merge OK # with missing value df1 = DataFrame({"key": Series([True, False, np.nan], dtype=object)}) df2 = DataFrame({"key": [True, False]})
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41520
2021-05-17T14:32:07Z
2021-05-17T20:49:44Z
2021-05-17T20:49:44Z
2021-05-17T21:54:17Z
CLN: remove try/except in _prep_ndarray
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 884a2cec171de..00efc695ff04a 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -57,6 +57,7 @@ ) from pandas.core.arrays import ( Categorical, + DatetimeArray, ExtensionArray, TimedeltaArray, ) @@ -515,7 +516,9 @@ def treat_as_nested(data) -> bool: def _prep_ndarray(values, copy: bool = True) -> np.ndarray: - if isinstance(values, TimedeltaArray): + if isinstance(values, TimedeltaArray) or ( + isinstance(values, DatetimeArray) and values.tz is None + ): # On older numpy, np.asarray below apparently does not call __array__, # so nanoseconds get dropped. values = values._ndarray @@ -541,15 +544,12 @@ def convert(v): # we could have a 1-dim or 2-dim list here # this is equiv of np.asarray, but does object conversion # and platform dtype preservation - try: - if is_list_like(values[0]): - values = np.array([convert(v) for v in values]) - elif isinstance(values[0], np.ndarray) and values[0].ndim == 0: - # GH#21861 - values = np.array([convert(v) for v in values]) - else: - values = convert(values) - except (ValueError, TypeError): + if is_list_like(values[0]): + values = np.array([convert(v) for v in values]) + elif isinstance(values[0], np.ndarray) and values[0].ndim == 0: + # GH#21861 + values = np.array([convert(v) for v in values]) + else: values = convert(values) else:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Recent-ish edits to the `convert` function make the fallback unnecessary.
https://api.github.com/repos/pandas-dev/pandas/pulls/41519
2021-05-17T14:29:06Z
2021-05-17T19:00:07Z
2021-05-17T19:00:07Z
2021-05-17T19:03:11Z
DOC: Add clearer info when copy is False but memory shared only for certain objects
diff --git a/pandas/core/series.py b/pandas/core/series.py index d0ff50cca5355..530750f8bd27f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -223,7 +223,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): name : str, optional The name to give to the Series. copy : bool, default False - Copy input data. + Copy input data. Only affects Series or 1d ndarray input. See examples. Examples -------- @@ -251,6 +251,38 @@ class Series(base.IndexOpsMixin, generic.NDFrame): Note that the Index is first build with the keys from the dictionary. After this the Series is reindexed with the given Index values, hence we get all NaN as a result. + + Constructing Series from a list with `copy=False`. + + >>> r = [1, 2] + >>> ser = pd.Series(r, copy=False) + >>> ser.iloc[0] = 999 + >>> r + [1, 2] + >>> ser + 0 999 + 1 2 + dtype: int64 + + Due to input data type the Series has a `copy` of + the original data even though `copy=False`, so + the data is unchanged. + + Constructing Series from a 1d ndarray with `copy=False`. + + >>> r = np.array([1, 2]) + >>> ser = pd.Series(r, copy=False) + >>> ser.iloc[0] = 999 + >>> r + array([999, 2]) + >>> ser + 0 999 + 1 2 + dtype: int64 + + Due to input data type the Series has a `view` on + the original data, so + the data is changed as well. """ _typ = "series"
- [ ] closes #41423 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Added to Series section more info in `copy` constructor parameter and 2 examples. Ran validation script: ``` python scripts/validate_docstrings.py pandas.Series ``` Output: ``` ################################################################################ ########################## Docstring (pandas.Series) ########################## ################################################################################ One-dimensional ndarray with axis labels (including time series). Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN). Operations between Series (+, -, /, *, **) align values based on their associated index values-- they need not be the same length. The result index will be the sorted union of the two indexes. Parameters ---------- data : array-like, Iterable, dict, or scalar value Contains data stored in Series. If data is a dict, argument order is maintained. index : array-like or Index (1d) Values must be hashable and have the same length as `data`. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, ..., n) if not provided. If data is dict-like and index is None, then the keys in the data are used as the index. If the index is not None, the resulting Series is reindexed with the index values. dtype : str, numpy.dtype, or ExtensionDtype, optional Data type for the output Series. If not specified, this will be inferred from `data`. See the :ref:`user guide <basics.dtypes>` for more usages. name : str, optional The name to give to the Series. copy : bool, default False Copy input data. If False and the Series returns a `copy` of the data, the memory location for the values is not shared. If False and the Series returns a `view` on the data, the memory location for the values is shared. Examples -------- Constructing Series from a dictionary with an Index specified >>> d = {'a': 1, 'b': 2, 'c': 3} >>> ser = pd.Series(data=d, index=['a', 'b', 'c']) >>> ser a 1 b 2 c 3 dtype: int64 The keys of the dictionary match with the Index values, hence the Index values have no effect. >>> d = {'a': 1, 'b': 2, 'c': 3} >>> ser = pd.Series(data=d, index=['x', 'y', 'z']) >>> ser x NaN y NaN z NaN dtype: float64 Note that the Index is first build with the keys from the dictionary. After this the Series is reindexed with the given Index values, hence we get all NaN as a result. Constructing Series from an array with `copy=False`. >>> r = [1,2] >>> ser = pd.Series(r, copy=False) >>> ser.iloc[0] = 999 >>> r [1, 2] >>> ser 0 999 1 2 dtype: int64 The Series returns a `copy` of the original data, so the original data is unchanged. Constructing Series from a `numpy.array` with `copy=False`. >>> r = np.array([1,2]) >>> ser = pd.Series(r, copy=False) >>> ser.iloc[0] = 999 >>> r array([999, 2]) >>> ser 0 999 1 2 dtype: int32 The Series returns a `view` on the original data, so the original data is changed as well. ################################################################################ ################################## Validation ################################## ################################################################################ 3 Errors found: Parameters {'fastpath'} not documented See Also section not found flake8 error: E902 PermissionError: [Errno 13] Permission denied: 'C:\\Users\\mdhsi\\AppData\\Local\\Temp\\tmpxz50buet' ```
https://api.github.com/repos/pandas-dev/pandas/pulls/41514
2021-05-16T23:07:46Z
2021-05-21T16:12:05Z
2021-05-21T16:12:04Z
2021-05-21T16:12:09Z
TYP: ExtensionArray delete() and searchsorted()
diff --git a/pandas/_typing.py b/pandas/_typing.py index ef9f38bbf5168..433f8645d35a8 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -69,6 +69,11 @@ from pandas.io.formats.format import EngFormatter from pandas.tseries.offsets import DateOffset + + # numpy compatible types + NumpyValueArrayLike = Union[npt._ScalarLike_co, npt.ArrayLike] + NumpySorter = Optional[npt._ArrayLikeInt_co] + else: npt: Any = None @@ -85,6 +90,7 @@ PandasScalar = Union["Period", "Timestamp", "Timedelta", "Interval"] Scalar = Union[PythonScalar, PandasScalar] + # timestamp and timedelta convertible types TimestampConvertibleTypes = Union[ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 3ba18b525a1e8..029daa2a0893e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -82,6 +82,11 @@ if TYPE_CHECKING: + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + from pandas import ( Categorical, DataFrame, @@ -1517,7 +1522,12 @@ def take( # ------------ # -def searchsorted(arr, value, side="left", sorter=None) -> np.ndarray: +def searchsorted( + arr: ArrayLike, + value: NumpyValueArrayLike, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, +) -> npt.NDArray[np.intp] | np.intp: """ Find indices where elements should be inserted to maintain order. @@ -1554,8 +1564,9 @@ def searchsorted(arr, value, side="left", sorter=None) -> np.ndarray: Returns ------- - array of ints - Array of insertion points with the same shape as `value`. + array of ints or int + If value is array-like, array of insertion points. + If value is scalar, a single integer. See Also -------- @@ -1583,9 +1594,10 @@ def searchsorted(arr, value, side="left", sorter=None) -> np.ndarray: dtype = value_arr.dtype if is_scalar(value): - value = dtype.type(value) + # We know that value is int + value = cast(int, dtype.type(value)) else: - value = pd_array(value, dtype=dtype) + value = pd_array(cast(ArrayLike, value), dtype=dtype) elif not ( is_object_dtype(arr) or is_numeric_dtype(arr) or is_categorical_dtype(arr) ): diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 0e8097cf1fc78..f13f1a418c2e9 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -2,6 +2,7 @@ from functools import wraps from typing import ( + TYPE_CHECKING, Any, Sequence, TypeVar, @@ -16,6 +17,7 @@ F, PositionalIndexer2D, Shape, + npt, type_t, ) from pandas.errors import AbstractMethodError @@ -45,6 +47,14 @@ "NDArrayBackedExtensionArrayT", bound="NDArrayBackedExtensionArray" ) +if TYPE_CHECKING: + from typing import Literal + + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + def ravel_compat(meth: F) -> F: """ @@ -157,12 +167,22 @@ def _concat_same_type( return to_concat[0]._from_backing_data(new_values) # type: ignore[arg-type] @doc(ExtensionArray.searchsorted) - def searchsorted(self, value, side="left", sorter=None): - value = self._validate_searchsorted_value(value) - return self._ndarray.searchsorted(value, side=side, sorter=sorter) - - def _validate_searchsorted_value(self, value): - return value + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: + npvalue = self._validate_searchsorted_value(value) + return self._ndarray.searchsorted(npvalue, side=side, sorter=sorter) + + def _validate_searchsorted_value( + self, value: NumpyValueArrayLike | ExtensionArray + ) -> NumpyValueArrayLike: + if isinstance(value, ExtensionArray): + return value.to_numpy() + else: + return value @doc(ExtensionArray.shift) def shift(self, periods=1, fill_value=None, axis=0): diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index b362769f50fa8..4cc0d4185b22c 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -29,6 +29,7 @@ FillnaOptions, PositionalIndexer, Shape, + npt, ) from pandas.compat import set_function_name from pandas.compat.numpy import function as nv @@ -81,6 +82,11 @@ def any(self, *, skipna: bool = True) -> bool: def all(self, *, skipna: bool = True) -> bool: pass + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + _extension_array_shared_docs: dict[str, str] = {} @@ -807,7 +813,12 @@ def unique(self: ExtensionArrayT) -> ExtensionArrayT: uniques = unique(self.astype(object)) return self._from_sequence(uniques, dtype=self.dtype) - def searchsorted(self, value, side="left", sorter=None): + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: """ Find indices where elements should be inserted to maintain order. @@ -838,8 +849,9 @@ def searchsorted(self, value, side="left", sorter=None): Returns ------- - array of ints - Array of insertion points with the same shape as `value`. + array of ints or int + If value is array-like, array of insertion points. + If value is scalar, a single integer. See Also -------- @@ -1304,7 +1316,7 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs): # ------------------------------------------------------------------------ # Non-Optimized Default Methods - def delete(self: ExtensionArrayT, loc) -> ExtensionArrayT: + def delete(self: ExtensionArrayT, loc: PositionalIndexer) -> ExtensionArrayT: indexer = np.delete(np.arange(len(self)), loc) return self.take(indexer) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 471ee295ebd2f..488981bcc9687 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -41,6 +41,7 @@ AnyArrayLike, Dtype, NpDtype, + npt, ) from pandas.util._decorators import ( cache_readonly, @@ -71,11 +72,20 @@ import pandas.core.algorithms as algos from pandas.core.arrays import datetimelike as dtl +from pandas.core.arrays.base import ExtensionArray import pandas.core.common as com if TYPE_CHECKING: + from typing import Literal + + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + from pandas.core.arrays import DatetimeArray + _shared_doc_kwargs = { "klass": "PeriodArray", } @@ -644,12 +654,17 @@ def astype(self, dtype, copy: bool = True): return self.asfreq(dtype.freq) return super().astype(dtype, copy=copy) - def searchsorted(self, value, side="left", sorter=None) -> np.ndarray: - value = self._validate_searchsorted_value(value).view("M8[ns]") + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: + npvalue = self._validate_searchsorted_value(value).view("M8[ns]") # Cast to M8 to get datetime-like NaT placement m8arr = self._ndarray.view("M8[ns]") - return m8arr.searchsorted(value, side=side, sorter=sorter) + return m8arr.searchsorted(npvalue, side=side, sorter=sorter) def fillna(self, value=None, method=None, limit=None) -> PeriodArray: if method is not None: diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 68c9e42ef8e08..b1c794ac03b31 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -7,6 +7,7 @@ import numbers import operator from typing import ( + TYPE_CHECKING, Any, Callable, Sequence, @@ -25,9 +26,11 @@ ) from pandas._libs.tslibs import NaT from pandas._typing import ( + ArrayLike, Dtype, NpDtype, Scalar, + npt, ) from pandas.compat.numpy import function as nv from pandas.errors import PerformanceWarning @@ -77,6 +80,11 @@ import pandas.io.formats.printing as printing +if TYPE_CHECKING: + from typing import Literal + + from pandas._typing import NumpySorter + # ---------------------------------------------------------------------------- # Array @@ -992,7 +1000,13 @@ def _take_without_fill(self, indices) -> np.ndarray | SparseArray: return taken - def searchsorted(self, v, side="left", sorter=None): + def searchsorted( + self, + v: ArrayLike | object, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: + msg = "searchsorted requires high memory usage." warnings.warn(msg, PerformanceWarning, stacklevel=2) if not is_scalar(v): diff --git a/pandas/core/base.py b/pandas/core/base.py index 57e015dc378c8..c7a707fd5cd6e 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -66,8 +66,14 @@ if TYPE_CHECKING: + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + from pandas import Categorical + _shared_docs: dict[str, str] = {} _indexops_doc_kwargs = { "klass": "IndexOpsMixin", @@ -1222,7 +1228,12 @@ def factorize(self, sort: bool = False, na_sentinel: int | None = -1): """ @doc(_shared_docs["searchsorted"], klass="Index") - def searchsorted(self, value, side="left", sorter=None) -> npt.NDArray[np.intp]: + def searchsorted( + self, + value: NumpyValueArrayLike, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: return algorithms.searchsorted(self._values, value, side=side, sorter=sorter) def drop_duplicates(self, keep="first"): diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index ad76a76a954b1..3e041c088f566 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -11,6 +11,7 @@ Timedelta, Timestamp, ) +from pandas._typing import npt from pandas.compat.chainmap import DeepChainMap from pandas.core.dtypes.common import is_list_like @@ -223,6 +224,7 @@ def stringify(value): return TermValue(int(v), v, kind) elif meta == "category": metadata = extract_array(self.metadata, extract_numpy=True) + result: npt.NDArray[np.intp] | np.intp | int if v not in metadata: result = -1 else: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 1f51576cc6e90..48daf7c89fe64 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8251,8 +8251,7 @@ def last(self: FrameOrSeries, offset) -> FrameOrSeries: start_date = self.index[-1] - offset start = self.index.searchsorted(start_date, side="right") - # error: Slice index must be an integer or None - return self.iloc[start:] # type: ignore[misc] + return self.iloc[start:] @final def rank( diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 87e19ce6ef670..645fab0d76a73 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3730,7 +3730,7 @@ def _get_fill_indexer_searchsorted( "if index and target are monotonic" ) - side = "left" if method == "pad" else "right" + side: Literal["left", "right"] = "left" if method == "pad" else "right" # find exact matches first (this simplifies the algorithm) indexer = self.get_indexer(target) @@ -6063,7 +6063,7 @@ def _maybe_cast_slice_bound(self, label, side: str_t, kind=no_default): return label - def _searchsorted_monotonic(self, label, side: str_t = "left"): + def _searchsorted_monotonic(self, label, side: Literal["left", "right"] = "left"): if self.is_monotonic_increasing: return self.searchsorted(label, side=side) elif self.is_monotonic_decreasing: @@ -6077,7 +6077,9 @@ def _searchsorted_monotonic(self, label, side: str_t = "left"): raise ValueError("index must be monotonic increasing or decreasing") - def get_slice_bound(self, label, side: str_t, kind=no_default) -> int: + def get_slice_bound( + self, label, side: Literal["left", "right"], kind=no_default + ) -> int: """ Calculate slice bound that corresponds to given label. diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 5d778af954eef..d2f598261a776 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -674,8 +674,7 @@ def _fast_union(self: _T, other: _T, sort=None) -> _T: left, right = self, other left_start = left[0] loc = right.searchsorted(left_start, side="left") - # error: Slice index must be an integer or None - right_chunk = right._values[:loc] # type: ignore[misc] + right_chunk = right._values[:loc] dates = concat_compat((left._values, right_chunk)) # With sort being False, we can't infer that result.freq == self.freq # TODO: no tests rely on the _with_freq("infer"); needed? @@ -691,8 +690,7 @@ def _fast_union(self: _T, other: _T, sort=None) -> _T: # concatenate if left_end < right_end: loc = right.searchsorted(left_end, side="right") - # error: Slice index must be an integer or None - right_chunk = right._values[loc:] # type: ignore[misc] + right_chunk = right._values[loc:] dates = concat_compat([left._values, right_chunk]) # The can_fast_union check ensures that the result.freq # should match self.freq diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 8a5811da4dd5a..fbbe6606ba522 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -11,6 +11,7 @@ from typing import ( TYPE_CHECKING, Hashable, + Literal, ) import warnings @@ -765,7 +766,9 @@ def check_str_or_none(point): return indexer @doc(Index.get_slice_bound) - def get_slice_bound(self, label, side: str, kind=lib.no_default) -> int: + def get_slice_bound( + self, label, side: Literal["left", "right"], kind=lib.no_default + ) -> int: # GH#42855 handle date here instead of _maybe_cast_slice_bound if isinstance(label, date) and not isinstance(label, datetime): label = Timestamp(label).to_pydatetime() diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 25f2378511dc4..920af5a13baba 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -4,8 +4,10 @@ from __future__ import annotations from typing import ( + TYPE_CHECKING, Hashable, TypeVar, + overload, ) import numpy as np @@ -39,10 +41,19 @@ TimedeltaArray, ) from pandas.core.arrays._mixins import NDArrayBackedExtensionArray +from pandas.core.arrays.base import ExtensionArray from pandas.core.indexers import deprecate_ndim_indexing from pandas.core.indexes.base import Index from pandas.core.ops import get_op_result_name +if TYPE_CHECKING: + from typing import Literal + + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + _T = TypeVar("_T", bound="NDArrayBackedExtensionIndex") @@ -318,7 +329,37 @@ def __getitem__(self, key): deprecate_ndim_indexing(result) return result - def searchsorted(self, value, side="left", sorter=None) -> np.ndarray: + # This overload is needed so that the call to searchsorted in + # pandas.core.resample.TimeGrouper._get_period_bins picks the correct result + + @overload + # The following ignore is also present in numpy/__init__.pyi + # Possibly a mypy bug?? + # error: Overloaded function signatures 1 and 2 overlap with incompatible + # return types [misc] + def searchsorted( # type: ignore[misc] + self, + value: npt._ScalarLike_co, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> np.intp: + ... + + @overload + def searchsorted( + self, + value: npt.ArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp]: + ... + + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: # overriding IndexOpsMixin improves performance GH#38083 return self._data.searchsorted(value, side=side, sorter=sorter) diff --git a/pandas/core/series.py b/pandas/core/series.py index a5ec4125f54a4..6f964ab09e978 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -144,6 +144,11 @@ if TYPE_CHECKING: + from pandas._typing import ( + NumpySorter, + NumpyValueArrayLike, + ) + from pandas.core.frame import DataFrame from pandas.core.groupby.generic import SeriesGroupBy from pandas.core.resample import Resampler @@ -2778,7 +2783,12 @@ def __rmatmul__(self, other): return self.dot(np.transpose(other)) @doc(base.IndexOpsMixin.searchsorted, klass="Series") - def searchsorted(self, value, side="left", sorter=None) -> np.ndarray: + def searchsorted( + self, + value: NumpyValueArrayLike, + side: Literal["left", "right"] = "left", + sorter: NumpySorter = None, + ) -> npt.NDArray[np.intp] | np.intp: return algorithms.searchsorted(self._values, value, side=side, sorter=sorter) # -------------------------------------------------------------------
Additional typing for `ExtensionArray` `delete()` and `searchsorted()`
https://api.github.com/repos/pandas-dev/pandas/pulls/41513
2021-05-16T14:30:46Z
2021-09-06T17:10:09Z
2021-09-06T17:10:09Z
2021-09-06T17:35:11Z
ENH: add `styler` option context for sparsification of columns and index separately
diff --git a/asv_bench/benchmarks/io/style.py b/asv_bench/benchmarks/io/style.py index a01610a69278b..82166a2a95c76 100644 --- a/asv_bench/benchmarks/io/style.py +++ b/asv_bench/benchmarks/io/style.py @@ -20,19 +20,19 @@ def setup(self, cols, rows): def time_apply_render(self, cols, rows): self._style_apply() - self.st._render_html() + self.st._render_html(True, True) def peakmem_apply_render(self, cols, rows): self._style_apply() - self.st._render_html() + self.st._render_html(True, True) def time_classes_render(self, cols, rows): self._style_classes() - self.st._render_html() + self.st._render_html(True, True) def peakmem_classes_render(self, cols, rows): self._style_classes() - self.st._render_html() + self.st._render_html(True, True) def time_format_render(self, cols, rows): self._style_format() diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst index 278eb907102ed..aa8a8fae417be 100644 --- a/doc/source/user_guide/options.rst +++ b/doc/source/user_guide/options.rst @@ -482,6 +482,11 @@ plotting.backend matplotlib Change the plotting backend like Bokeh, Altair, etc. plotting.matplotlib.register_converters True Register custom converters with matplotlib. Set to False to de-register. +styler.sparse.index True "Sparsify" MultiIndex display for rows + in Styler output (don't display repeated + elements in outer levels within groups). +styler.sparse.columns True "Sparsify" MultiIndex display for columns + in Styler output. ======================================= ============ ================================== diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1eb22436204a8..cf41cee3f194a 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -139,6 +139,7 @@ precision, and perform HTML escaping (:issue:`40437` :issue:`40134`). There have properly format HTML and eliminate some inconsistencies (:issue:`39942` :issue:`40356` :issue:`39807` :issue:`39889` :issue:`39627`) :class:`.Styler` has also been compatible with non-unique index or columns, at least for as many features as are fully compatible, others made only partially compatible (:issue:`41269`). +One also has greater control of the display through separate sparsification of the index or columns, using the new 'styler' options context (:issue:`41142`). Documentation has also seen major revisions in light of new features (:issue:`39720` :issue:`39317` :issue:`40493`) diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index baac872a6a466..a88bc8900ccdd 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -726,3 +726,26 @@ def register_converter_cb(key): validator=is_one_of_factory(["auto", True, False]), cb=register_converter_cb, ) + +# ------ +# Styler +# ------ + +styler_sparse_index_doc = """ +: bool + Whether to sparsify the display of a hierarchical index. Setting to False will + display each explicit level element in a hierarchical key for each row. +""" + +styler_sparse_columns_doc = """ +: bool + Whether to sparsify the display of hierarchical columns. Setting to False will + display each explicit level element in a hierarchical key for each column. +""" + +with cf.config_prefix("styler"): + cf.register_option("sparse.index", True, styler_sparse_index_doc, validator=bool) + + cf.register_option( + "sparse.columns", True, styler_sparse_columns_doc, validator=bool + ) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index a96196a698f43..c8726d9008e7d 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -17,6 +17,8 @@ import numpy as np +from pandas._config import get_option + from pandas._typing import ( Axis, FrameOrSeries, @@ -201,14 +203,27 @@ def _repr_html_(self) -> str: """ Hooks into Jupyter notebook rich display system. """ - return self._render_html() + return self.render() - def render(self, **kwargs) -> str: + def render( + self, + sparse_index: bool | None = None, + sparse_columns: bool | None = None, + **kwargs, + ) -> str: """ Render the ``Styler`` including all applied styles to HTML. Parameters ---------- + sparse_index : bool, optional + Whether to sparsify the display of a hierarchical index. Setting to False + will display each explicit level element in a hierarchical key for each row. + Defaults to ``pandas.options.styler.sparse.index`` value. + sparse_columns : bool, optional + Whether to sparsify the display of a hierarchical index. Setting to False + will display each explicit level element in a hierarchical key for each row. + Defaults to ``pandas.options.styler.sparse.columns`` value. **kwargs Any additional keyword arguments are passed through to ``self.template.render``. @@ -240,7 +255,11 @@ def render(self, **kwargs) -> str: * caption * table_attributes """ - return self._render_html(**kwargs) + if sparse_index is None: + sparse_index = get_option("styler.sparse.index") + if sparse_columns is None: + sparse_columns = get_option("styler.sparse.columns") + return self._render_html(sparse_index, sparse_columns, **kwargs) def set_tooltips( self, diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 6f7d298c7dec0..e5fcf024c2805 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -107,14 +107,14 @@ def __init__( tuple[int, int], Callable[[Any], str] ] = defaultdict(lambda: partial(_default_formatter, precision=def_precision)) - def _render_html(self, **kwargs) -> str: + def _render_html(self, sparse_index: bool, sparse_columns: bool, **kwargs) -> str: """ Renders the ``Styler`` including all applied styles to HTML. Generates a dict with necessary kwargs passed to jinja2 template. """ self._compute() # TODO: namespace all the pandas keys - d = self._translate() + d = self._translate(sparse_index, sparse_columns) d.update(kwargs) return self.template_html.render(**d) @@ -133,9 +133,7 @@ def _compute(self): r = func(self)(*args, **kwargs) return r - def _translate( - self, sparsify_index: bool | None = None, sparsify_cols: bool | None = None - ): + def _translate(self, sparse_index: bool, sparse_cols: bool): """ Process Styler data and settings into a dict for template rendering. @@ -144,10 +142,12 @@ def _translate( Parameters ---------- - sparsify_index : bool, optional - Whether to sparsify the index or print all hierarchical index elements - sparsify_cols : bool, optional - Whether to sparsify the columns or print all hierarchical column elements + sparse_index : bool + Whether to sparsify the index or print all hierarchical index elements. + Upstream defaults are typically to `pandas.options.styler.sparse.index`. + sparse_cols : bool + Whether to sparsify the columns or print all hierarchical column elements. + Upstream defaults are typically to `pandas.options.styler.sparse.columns`. Returns ------- @@ -155,11 +155,6 @@ def _translate( The following structure: {uuid, table_styles, caption, head, body, cellstyle, table_attributes} """ - if sparsify_index is None: - sparsify_index = get_option("display.multi_sparse") - if sparsify_cols is None: - sparsify_cols = get_option("display.multi_sparse") - ROW_HEADING_CLASS = "row_heading" COL_HEADING_CLASS = "col_heading" INDEX_NAME_CLASS = "index_name" @@ -176,14 +171,14 @@ def _translate( } head = self._translate_header( - BLANK_CLASS, BLANK_VALUE, INDEX_NAME_CLASS, COL_HEADING_CLASS, sparsify_cols + BLANK_CLASS, BLANK_VALUE, INDEX_NAME_CLASS, COL_HEADING_CLASS, sparse_cols ) d.update({"head": head}) self.cellstyle_map: DefaultDict[tuple[CSSPair, ...], list[str]] = defaultdict( list ) - body = self._translate_body(DATA_CLASS, ROW_HEADING_CLASS, sparsify_index) + body = self._translate_body(DATA_CLASS, ROW_HEADING_CLASS, sparse_index) d.update({"body": body}) cellstyle: list[dict[str, CSSList | list[str]]] = [ diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py index 0f3e5863a4a99..9db27689a53f5 100644 --- a/pandas/tests/io/formats/style/test_format.py +++ b/pandas/tests/io/formats/style/test_format.py @@ -28,20 +28,20 @@ def styler(df): def test_display_format(styler): - ctx = styler.format("{:0.1f}")._translate() + ctx = styler.format("{:0.1f}")._translate(True, True) assert all(["display_value" in c for c in row] for row in ctx["body"]) assert all([len(c["display_value"]) <= 3 for c in row[1:]] for row in ctx["body"]) assert len(ctx["body"][0][1]["display_value"].lstrip("-")) <= 3 def test_format_dict(styler): - ctx = styler.format({"A": "{:0.1f}", "B": "{0:.2%}"})._translate() + ctx = styler.format({"A": "{:0.1f}", "B": "{0:.2%}"})._translate(True, True) assert ctx["body"][0][1]["display_value"] == "0.0" assert ctx["body"][0][2]["display_value"] == "-60.90%" def test_format_string(styler): - ctx = styler.format("{:.2f}")._translate() + ctx = styler.format("{:.2f}")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "0.00" assert ctx["body"][0][2]["display_value"] == "-0.61" assert ctx["body"][1][1]["display_value"] == "1.00" @@ -49,7 +49,7 @@ def test_format_string(styler): def test_format_callable(styler): - ctx = styler.format(lambda v: "neg" if v < 0 else "pos")._translate() + ctx = styler.format(lambda v: "neg" if v < 0 else "pos")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "pos" assert ctx["body"][0][2]["display_value"] == "neg" assert ctx["body"][1][1]["display_value"] == "pos" @@ -60,17 +60,17 @@ def test_format_with_na_rep(): # GH 21527 28358 df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) - ctx = df.style.format(None, na_rep="-")._translate() + ctx = df.style.format(None, na_rep="-")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "-" assert ctx["body"][0][2]["display_value"] == "-" - ctx = df.style.format("{:.2%}", na_rep="-")._translate() + ctx = df.style.format("{:.2%}", na_rep="-")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "-" assert ctx["body"][0][2]["display_value"] == "-" assert ctx["body"][1][1]["display_value"] == "110.00%" assert ctx["body"][1][2]["display_value"] == "120.00%" - ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate() + ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate(True, True) assert ctx["body"][0][2]["display_value"] == "-" assert ctx["body"][1][2]["display_value"] == "120.00%" @@ -85,13 +85,13 @@ def test_format_non_numeric_na(): ) with tm.assert_produces_warning(FutureWarning): - ctx = df.style.set_na_rep("NA")._translate() + ctx = df.style.set_na_rep("NA")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "NA" assert ctx["body"][0][2]["display_value"] == "NA" assert ctx["body"][1][1]["display_value"] == "NA" assert ctx["body"][1][2]["display_value"] == "NA" - ctx = df.style.format(None, na_rep="-")._translate() + ctx = df.style.format(None, na_rep="-")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "-" assert ctx["body"][0][2]["display_value"] == "-" assert ctx["body"][1][1]["display_value"] == "-" @@ -150,19 +150,19 @@ def test_format_with_precision(): df = DataFrame(data=[[1.0, 2.0090], [3.2121, 4.566]], columns=["a", "b"]) s = Styler(df) - ctx = s.format(precision=1)._translate() + ctx = s.format(precision=1)._translate(True, True) assert ctx["body"][0][1]["display_value"] == "1.0" assert ctx["body"][0][2]["display_value"] == "2.0" assert ctx["body"][1][1]["display_value"] == "3.2" assert ctx["body"][1][2]["display_value"] == "4.6" - ctx = s.format(precision=2)._translate() + ctx = s.format(precision=2)._translate(True, True) assert ctx["body"][0][1]["display_value"] == "1.00" assert ctx["body"][0][2]["display_value"] == "2.01" assert ctx["body"][1][1]["display_value"] == "3.21" assert ctx["body"][1][2]["display_value"] == "4.57" - ctx = s.format(precision=3)._translate() + ctx = s.format(precision=3)._translate(True, True) assert ctx["body"][0][1]["display_value"] == "1.000" assert ctx["body"][0][2]["display_value"] == "2.009" assert ctx["body"][1][1]["display_value"] == "3.212" @@ -173,26 +173,28 @@ def test_format_subset(): df = DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"]) ctx = df.style.format( {"a": "{:0.1f}", "b": "{0:.2%}"}, subset=IndexSlice[0, :] - )._translate() + )._translate(True, True) expected = "0.1" raw_11 = "1.123400" assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][1][1]["display_value"] == raw_11 assert ctx["body"][0][2]["display_value"] == "12.34%" - ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, :])._translate() + ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, :])._translate(True, True) assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][1][1]["display_value"] == raw_11 - ctx = df.style.format("{:0.1f}", subset=IndexSlice["a"])._translate() + ctx = df.style.format("{:0.1f}", subset=IndexSlice["a"])._translate(True, True) assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][0][2]["display_value"] == "0.123400" - ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, "a"])._translate() + ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, "a"])._translate(True, True) assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][1][1]["display_value"] == raw_11 - ctx = df.style.format("{:0.1f}", subset=IndexSlice[[0, 1], ["a"]])._translate() + ctx = df.style.format("{:0.1f}", subset=IndexSlice[[0, 1], ["a"]])._translate( + True, True + ) assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][1][1]["display_value"] == "1.1" assert ctx["body"][0][2]["display_value"] == "0.123400" @@ -206,19 +208,19 @@ def test_format_thousands(formatter, decimal, precision): s = DataFrame([[1000000.123456789]]).style # test float result = s.format( thousands="_", formatter=formatter, decimal=decimal, precision=precision - )._translate() + )._translate(True, True) assert "1_000_000" in result["body"][0][1]["display_value"] s = DataFrame([[1000000]]).style # test int result = s.format( thousands="_", formatter=formatter, decimal=decimal, precision=precision - )._translate() + )._translate(True, True) assert "1_000_000" in result["body"][0][1]["display_value"] s = DataFrame([[1 + 1000000.123456789j]]).style # test complex result = s.format( thousands="_", formatter=formatter, decimal=decimal, precision=precision - )._translate() + )._translate(True, True) assert "1_000_000" in result["body"][0][1]["display_value"] @@ -229,11 +231,11 @@ def test_format_decimal(formatter, thousands, precision): s = DataFrame([[1000000.123456789]]).style # test float result = s.format( decimal="_", formatter=formatter, thousands=thousands, precision=precision - )._translate() + )._translate(True, True) assert "000_123" in result["body"][0][1]["display_value"] s = DataFrame([[1 + 1000000.123456789j]]).style # test complex result = s.format( decimal="_", formatter=formatter, thousands=thousands, precision=precision - )._translate() + )._translate(True, True) assert "000_123" in result["body"][0][1]["display_value"] diff --git a/pandas/tests/io/formats/style/test_non_unique.py b/pandas/tests/io/formats/style/test_non_unique.py index 2dc7433009368..9cbc2db87fbde 100644 --- a/pandas/tests/io/formats/style/test_non_unique.py +++ b/pandas/tests/io/formats/style/test_non_unique.py @@ -108,7 +108,7 @@ def test_set_td_classes_non_unique_raises(styler): def test_hide_columns_non_unique(styler): - ctx = styler.hide_columns(["d"])._translate() + ctx = styler.hide_columns(["d"])._translate(True, True) assert ctx["head"][0][1]["display_value"] == "c" assert ctx["head"][0][1]["is_visible"] is True diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 31877b3f33482..c556081b5f562 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -6,7 +6,10 @@ import pytest import pandas as pd -from pandas import DataFrame +from pandas import ( + DataFrame, + MultiIndex, +) import pandas._testing as tm jinja2 = pytest.importorskip("jinja2") @@ -20,6 +23,99 @@ ) +@pytest.fixture +def mi_df(): + return DataFrame( + [[1, 2], [3, 4]], + index=MultiIndex.from_product([["i0"], ["i1_a", "i1_b"]]), + columns=MultiIndex.from_product([["c0"], ["c1_a", "c1_b"]]), + dtype=int, + ) + + +@pytest.fixture +def mi_styler(mi_df): + return Styler(mi_df, uuid_len=0) + + +@pytest.mark.parametrize( + "sparse_columns, exp_cols", + [ + ( + True, + [ + {"is_visible": True, "attributes": 'colspan="2"', "value": "c0"}, + {"is_visible": False, "attributes": "", "value": "c0"}, + ], + ), + ( + False, + [ + {"is_visible": True, "attributes": "", "value": "c0"}, + {"is_visible": True, "attributes": "", "value": "c0"}, + ], + ), + ], +) +def test_mi_styler_sparsify_columns(mi_styler, sparse_columns, exp_cols): + exp_l1_c0 = {"is_visible": True, "attributes": "", "display_value": "c1_a"} + exp_l1_c1 = {"is_visible": True, "attributes": "", "display_value": "c1_b"} + + ctx = mi_styler._translate(True, sparse_columns) + + assert exp_cols[0].items() <= ctx["head"][0][2].items() + assert exp_cols[1].items() <= ctx["head"][0][3].items() + assert exp_l1_c0.items() <= ctx["head"][1][2].items() + assert exp_l1_c1.items() <= ctx["head"][1][3].items() + + +@pytest.mark.parametrize( + "sparse_index, exp_rows", + [ + ( + True, + [ + {"is_visible": True, "attributes": 'rowspan="2"', "value": "i0"}, + {"is_visible": False, "attributes": "", "value": "i0"}, + ], + ), + ( + False, + [ + {"is_visible": True, "attributes": "", "value": "i0"}, + {"is_visible": True, "attributes": "", "value": "i0"}, + ], + ), + ], +) +def test_mi_styler_sparsify_index(mi_styler, sparse_index, exp_rows): + exp_l1_r0 = {"is_visible": True, "attributes": "", "display_value": "i1_a"} + exp_l1_r1 = {"is_visible": True, "attributes": "", "display_value": "i1_b"} + + ctx = mi_styler._translate(sparse_index, True) + + assert exp_rows[0].items() <= ctx["body"][0][0].items() + assert exp_rows[1].items() <= ctx["body"][1][0].items() + assert exp_l1_r0.items() <= ctx["body"][0][1].items() + assert exp_l1_r1.items() <= ctx["body"][1][1].items() + + +def test_mi_styler_sparsify_options(mi_styler): + with pd.option_context("styler.sparse.index", False): + html1 = mi_styler.render() + with pd.option_context("styler.sparse.index", True): + html2 = mi_styler.render() + + assert html1 != html2 + + with pd.option_context("styler.sparse.columns", False): + html1 = mi_styler.render() + with pd.option_context("styler.sparse.columns", True): + html2 = mi_styler.render() + + assert html1 != html2 + + class TestStyler: def setup_method(self, method): np.random.seed(24) @@ -256,7 +352,7 @@ def test_set_properties_subset(self): def test_empty_index_name_doesnt_display(self): # https://github.com/pandas-dev/pandas/pull/12090#issuecomment-180695902 df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}) - result = df.style._translate() + result = df.style._translate(True, True) expected = [ [ @@ -300,7 +396,7 @@ def test_index_name(self): # https://github.com/pandas-dev/pandas/issues/11655 # TODO: this test can be minimised to address the test more directly df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}) - result = df.set_index("A").style._translate() + result = df.set_index("A").style._translate(True, True) expected = [ [ @@ -359,7 +455,7 @@ def test_multiindex_name(self): # https://github.com/pandas-dev/pandas/issues/11655 # TODO: this test can be minimised to address the test more directly df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}) - result = df.set_index(["A", "B"]).style._translate() + result = df.set_index(["A", "B"]).style._translate(True, True) expected = [ [ @@ -417,7 +513,7 @@ def test_numeric_columns(self): # https://github.com/pandas-dev/pandas/issues/12125 # smoke test for _translate df = DataFrame({0: [1, 2, 3]}) - df.style._translate() + df.style._translate(True, True) def test_apply_axis(self): df = DataFrame({"A": [0, 0], "B": [1, 1]}) @@ -510,8 +606,8 @@ def test_applymap_subset(self, slice_): def test_applymap_subset_multiindex(self, slice_): # GH 19861 # edited for GH 33562 - idx = pd.MultiIndex.from_product([["a", "b"], [1, 2]]) - col = pd.MultiIndex.from_product([["x", "y"], ["A", "B"]]) + idx = MultiIndex.from_product([["a", "b"], [1, 2]]) + col = MultiIndex.from_product([["x", "y"], ["A", "B"]]) df = DataFrame(np.random.rand(4, 4), columns=col, index=idx) df.style.applymap(lambda x: "color: red;", subset=slice_).render() @@ -519,7 +615,7 @@ def test_applymap_subset_multiindex_code(self): # https://github.com/pandas-dev/pandas/issues/25858 # Checks styler.applymap works with multindex when codes are provided codes = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) - columns = pd.MultiIndex( + columns = MultiIndex( levels=[["a", "b"], ["%", "#"]], codes=codes, names=["", ""] ) df = DataFrame( @@ -627,7 +723,7 @@ def test_empty(self): s = df.style s.ctx = {(0, 0): [("color", "red")], (1, 0): [("", "")]} - result = s._translate()["cellstyle"] + result = s._translate(True, True)["cellstyle"] expected = [ {"props": [("color", "red")], "selectors": ["row0_col0"]}, {"props": [("", "")], "selectors": ["row1_col0"]}, @@ -639,7 +735,7 @@ def test_duplicate(self): s = df.style s.ctx = {(0, 0): [("color", "red")], (1, 0): [("color", "red")]} - result = s._translate()["cellstyle"] + result = s._translate(True, True)["cellstyle"] expected = [ {"props": [("color", "red")], "selectors": ["row0_col0", "row1_col0"]} ] @@ -649,7 +745,7 @@ def test_init_with_na_rep(self): # GH 21527 28358 df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) - ctx = Styler(df, na_rep="NA")._translate() + ctx = Styler(df, na_rep="NA")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "NA" assert ctx["body"][0][2]["display_value"] == "NA" @@ -658,7 +754,7 @@ def test_set_na_rep(self): df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) with tm.assert_produces_warning(FutureWarning): - ctx = df.style.set_na_rep("NA")._translate() + ctx = df.style.set_na_rep("NA")._translate(True, True) assert ctx["body"][0][1]["display_value"] == "NA" assert ctx["body"][0][2]["display_value"] == "NA" @@ -666,7 +762,7 @@ def test_set_na_rep(self): ctx = ( df.style.set_na_rep("NA") .format(None, na_rep="-", subset=["B"]) - ._translate() + ._translate(True, True) ) assert ctx["body"][0][1]["display_value"] == "NA" assert ctx["body"][0][2]["display_value"] == "-" @@ -722,7 +818,7 @@ def test_table_styles_multiple(self): {"selector": "th,td", "props": "color:red;"}, {"selector": "tr", "props": "color:green;"}, ] - )._translate()["table_styles"] + )._translate(True, True)["table_styles"] assert ctx == [ {"selector": "th", "props": [("color", "red")]}, {"selector": "td", "props": [("color", "red")]}, @@ -833,7 +929,7 @@ def f(x): df.style._apply(f, axis=None) def test_get_level_lengths(self): - index = pd.MultiIndex.from_product([["a", "b"], [0, 1, 2]]) + index = MultiIndex.from_product([["a", "b"], [0, 1, 2]]) expected = { (0, 0): 3, (0, 3): 3, @@ -865,7 +961,7 @@ def test_get_level_lengths(self): tm.assert_dict_equal(result, expected) def test_get_level_lengths_un_sorted(self): - index = pd.MultiIndex.from_arrays([[1, 1, 2, 1], ["a", "b", "b", "d"]]) + index = MultiIndex.from_arrays([[1, 1, 2, 1], ["a", "b", "b", "d"]]) expected = { (0, 0): 2, (0, 2): 1, @@ -891,97 +987,15 @@ def test_get_level_lengths_un_sorted(self): result = _get_level_lengths(index, sparsify=False) tm.assert_dict_equal(result, expected) - def test_mi_sparse(self): - df = DataFrame( - {"A": [1, 2]}, index=pd.MultiIndex.from_arrays([["a", "a"], [0, 1]]) - ) - - result = df.style._translate() - body_0 = result["body"][0][0] - expected_0 = { - "value": "a", - "display_value": "a", - "is_visible": True, - "type": "th", - "attributes": 'rowspan="2"', - "class": "row_heading level0 row0", - "id": "level0_row0", - } - assert body_0 == expected_0 - - body_1 = result["body"][0][1] - expected_1 = { - "value": 0, - "display_value": 0, - "is_visible": True, - "type": "th", - "class": "row_heading level1 row0", - "id": "level1_row0", - "attributes": "", - } - assert body_1 == expected_1 - - body_10 = result["body"][1][0] - expected_10 = { - "value": "a", - "display_value": "a", - "is_visible": False, - "type": "th", - "class": "row_heading level0 row1", - "id": "level0_row1", - "attributes": "", - } - assert body_10 == expected_10 - - head = result["head"][0] - expected = [ - { - "type": "th", - "class": "blank", - "value": self.blank_value, - "is_visible": True, - "display_value": self.blank_value, - }, - { - "type": "th", - "class": "blank level0", - "value": self.blank_value, - "is_visible": True, - "display_value": self.blank_value, - }, - { - "type": "th", - "class": "col_heading level0 col0", - "value": "A", - "is_visible": True, - "display_value": "A", - "attributes": "", - }, - ] - assert head == expected - - def test_mi_sparse_disabled(self): - df = DataFrame( - {"A": [1, 2]}, index=pd.MultiIndex.from_arrays([["a", "a"], [0, 1]]) - ) - result = df.style._translate()["body"] - assert 'rowspan="2"' in result[0][0]["attributes"] - assert result[1][0]["is_visible"] is False - - with pd.option_context("display.multi_sparse", False): - result = df.style._translate()["body"] - assert 'rowspan="2"' not in result[0][0]["attributes"] - assert result[1][0]["is_visible"] is True - def test_mi_sparse_index_names(self): # TODO this test is verbose can be minimised to more directly target test df = DataFrame( {"A": [1, 2]}, - index=pd.MultiIndex.from_arrays( + index=MultiIndex.from_arrays( [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"] ), ) - result = df.style._translate() + result = df.style._translate(True, True) head = result["head"][1] expected = [ { @@ -1013,15 +1027,15 @@ def test_mi_sparse_column_names(self): # TODO this test is verbose - could be minimised df = DataFrame( np.arange(16).reshape(4, 4), - index=pd.MultiIndex.from_arrays( + index=MultiIndex.from_arrays( [["a", "a", "b", "a"], [0, 1, 1, 2]], names=["idx_level_0", "idx_level_1"], ), - columns=pd.MultiIndex.from_arrays( + columns=MultiIndex.from_arrays( [["C1", "C1", "C2", "C2"], [1, 0, 1, 0]], names=["col_0", "col_1"] ), ) - result = df.style._translate() + result = df.style._translate(True, True) head = result["head"][1] expected = [ { @@ -1076,20 +1090,20 @@ def test_mi_sparse_column_names(self): def test_hide_single_index(self): # GH 14194 # single unnamed index - ctx = self.df.style._translate() + ctx = self.df.style._translate(True, True) assert ctx["body"][0][0]["is_visible"] assert ctx["head"][0][0]["is_visible"] - ctx2 = self.df.style.hide_index()._translate() + ctx2 = self.df.style.hide_index()._translate(True, True) assert not ctx2["body"][0][0]["is_visible"] assert not ctx2["head"][0][0]["is_visible"] # single named index - ctx3 = self.df.set_index("A").style._translate() + ctx3 = self.df.set_index("A").style._translate(True, True) assert ctx3["body"][0][0]["is_visible"] assert len(ctx3["head"]) == 2 # 2 header levels assert ctx3["head"][0][0]["is_visible"] - ctx4 = self.df.set_index("A").style.hide_index()._translate() + ctx4 = self.df.set_index("A").style.hide_index()._translate(True, True) assert not ctx4["body"][0][0]["is_visible"] assert len(ctx4["head"]) == 1 # only 1 header levels assert not ctx4["head"][0][0]["is_visible"] @@ -1098,11 +1112,11 @@ def test_hide_multiindex(self): # GH 14194 df = DataFrame( {"A": [1, 2]}, - index=pd.MultiIndex.from_arrays( + index=MultiIndex.from_arrays( [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"] ), ) - ctx1 = df.style._translate() + ctx1 = df.style._translate(True, True) # tests for 'a' and '0' assert ctx1["body"][0][0]["is_visible"] assert ctx1["body"][0][1]["is_visible"] @@ -1110,7 +1124,7 @@ def test_hide_multiindex(self): assert ctx1["head"][0][0]["is_visible"] assert ctx1["head"][0][1]["is_visible"] - ctx2 = df.style.hide_index()._translate() + ctx2 = df.style.hide_index()._translate(True, True) # tests for 'a' and '0' assert not ctx2["body"][0][0]["is_visible"] assert not ctx2["body"][0][1]["is_visible"] @@ -1121,7 +1135,7 @@ def test_hide_multiindex(self): def test_hide_columns_single_level(self): # GH 14194 # test hiding single column - ctx = self.df.style._translate() + ctx = self.df.style._translate(True, True) assert ctx["head"][0][1]["is_visible"] assert ctx["head"][0][1]["display_value"] == "A" assert ctx["head"][0][2]["is_visible"] @@ -1129,13 +1143,13 @@ def test_hide_columns_single_level(self): assert ctx["body"][0][1]["is_visible"] # col A, row 1 assert ctx["body"][1][2]["is_visible"] # col B, row 1 - ctx = self.df.style.hide_columns("A")._translate() + ctx = self.df.style.hide_columns("A")._translate(True, True) assert not ctx["head"][0][1]["is_visible"] assert not ctx["body"][0][1]["is_visible"] # col A, row 1 assert ctx["body"][1][2]["is_visible"] # col B, row 1 # test hiding mulitiple columns - ctx = self.df.style.hide_columns(["A", "B"])._translate() + ctx = self.df.style.hide_columns(["A", "B"])._translate(True, True) assert not ctx["head"][0][1]["is_visible"] assert not ctx["head"][0][2]["is_visible"] assert not ctx["body"][0][1]["is_visible"] # col A, row 1 @@ -1144,14 +1158,14 @@ def test_hide_columns_single_level(self): def test_hide_columns_mult_levels(self): # GH 14194 # setup dataframe with multiple column levels and indices - i1 = pd.MultiIndex.from_arrays( + i1 = MultiIndex.from_arrays( [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"] ) - i2 = pd.MultiIndex.from_arrays( + i2 = MultiIndex.from_arrays( [["b", "b"], [0, 1]], names=["col_level_0", "col_level_1"] ) df = DataFrame([[1, 2], [3, 4]], index=i1, columns=i2) - ctx = df.style._translate() + ctx = df.style._translate(True, True) # column headers assert ctx["head"][0][2]["is_visible"] assert ctx["head"][1][2]["is_visible"] @@ -1165,14 +1179,14 @@ def test_hide_columns_mult_levels(self): assert ctx["body"][1][3]["display_value"] == 4 # hide top column level, which hides both columns - ctx = df.style.hide_columns("b")._translate() + ctx = df.style.hide_columns("b")._translate(True, True) assert not ctx["head"][0][2]["is_visible"] # b assert not ctx["head"][1][2]["is_visible"] # 0 assert not ctx["body"][1][2]["is_visible"] # 3 assert ctx["body"][0][0]["is_visible"] # index # hide first column only - ctx = df.style.hide_columns([("b", 0)])._translate() + ctx = df.style.hide_columns([("b", 0)])._translate(True, True) assert ctx["head"][0][2]["is_visible"] # b assert not ctx["head"][1][2]["is_visible"] # 0 assert not ctx["body"][1][2]["is_visible"] # 3 @@ -1180,7 +1194,7 @@ def test_hide_columns_mult_levels(self): assert ctx["body"][1][3]["display_value"] == 4 # hide second column and index - ctx = df.style.hide_columns([("b", 1)]).hide_index()._translate() + ctx = df.style.hide_columns([("b", 1)]).hide_index()._translate(True, True) assert not ctx["body"][0][0]["is_visible"] # index assert ctx["head"][0][2]["is_visible"] # b assert ctx["head"][1][2]["is_visible"] # 0 @@ -1436,8 +1450,8 @@ def test_non_reducing_slice_on_multiindex(self): ) def test_non_reducing_multi_slice_on_multiindex(self, slice_): # GH 33562 - cols = pd.MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]) - idxs = pd.MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]]) + cols = MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]) + idxs = MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]]) df = DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs) expected = df.loc[slice_]
This PR closes #41142. It adds a new `pandas.options` context for Styler (see #41395), and create the `sparse.index` and `sparse.columns` options, defaulting to True. It also allows a keyword application for sparsification via the `.render` method, (this might not really be necessary: opinion welcome) - [x] tests added for kwarg application and option context
https://api.github.com/repos/pandas-dev/pandas/pulls/41512
2021-05-16T14:17:32Z
2021-05-21T16:20:32Z
2021-05-21T16:20:32Z
2021-05-22T06:28:03Z
Deprecate passing args as positional in DataFrame/Series.clip
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d357e4a633347..36457be9b2c46 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -674,6 +674,7 @@ Deprecations - Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`) - Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`) - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) +- Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 18ee1ad9bcd96..6a97a1e7b544d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10663,6 +10663,20 @@ def values(self) -> np.ndarray: self._consolidate_inplace() return self._mgr.as_array(transpose=True) + @deprecate_nonkeyword_arguments( + version=None, allowed_args=["self", "lower", "upper"] + ) + def clip( + self: DataFrame, + lower=None, + upper=None, + axis: Axis | None = None, + inplace: bool = False, + *args, + **kwargs, + ) -> DataFrame | None: + return super().clip(lower, upper, axis, inplace, *args, **kwargs) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"]) def interpolate( self: DataFrame, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6d7c803685255..0cf31f9aa7586 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7365,115 +7365,6 @@ def _clip_with_one_bound(self, threshold, method, axis, inplace): # GH 40420 return self.where(subset, threshold, axis=axis, inplace=inplace) - @overload - def clip( - self: FrameOrSeries, - lower=..., - upper=..., - axis: Axis | None = ..., - inplace: Literal[False] = ..., - *args, - **kwargs, - ) -> FrameOrSeries: - ... - - @overload - def clip( - self: FrameOrSeries, - lower, - *, - axis: Axis | None, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - lower, - *, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - *, - upper, - axis: Axis | None, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - *, - upper, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - *, - axis: Axis | None, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - lower, - upper, - axis: Axis | None, - inplace: Literal[True], - *args, - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - lower, - upper, - *, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - *, - inplace: Literal[True], - **kwargs, - ) -> None: - ... - - @overload - def clip( - self: FrameOrSeries, - lower=..., - upper=..., - axis: Axis | None = ..., - inplace: bool_t = ..., - *args, - **kwargs, - ) -> FrameOrSeries | None: - ... - - @final def clip( self: FrameOrSeries, lower=None, diff --git a/pandas/core/series.py b/pandas/core/series.py index d8b7876028839..e4d1705e1d04c 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5290,6 +5290,20 @@ def to_period(self, freq=None, copy=True) -> Series: self, method="to_period" ) + @deprecate_nonkeyword_arguments( + version=None, allowed_args=["self", "lower", "upper"] + ) + def clip( + self: Series, + lower=None, + upper=None, + axis: Axis | None = None, + inplace: bool = False, + *args, + **kwargs, + ) -> Series | None: + return super().clip(lower, upper, axis, inplace, *args, **kwargs) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"]) def interpolate( self: Series, diff --git a/pandas/tests/frame/methods/test_clip.py b/pandas/tests/frame/methods/test_clip.py index 6525109da4394..09b33831ed5ec 100644 --- a/pandas/tests/frame/methods/test_clip.py +++ b/pandas/tests/frame/methods/test_clip.py @@ -166,3 +166,15 @@ def test_clip_with_na_args(self, float_frame): result = df.clip(lower=t, axis=0) expected = DataFrame({"col_0": [9, -3, 0, 6, 5], "col_1": [2, -4, 6, 8, 3]}) tm.assert_frame_equal(result, expected) + + def test_clip_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame.clip except " + r"for the arguments 'lower' and 'upper' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.clip(0, 1, 0) + expected = DataFrame({"a": [1, 1, 1]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_clip.py b/pandas/tests/series/methods/test_clip.py index 6185fe6c54fa4..7dbc194669a62 100644 --- a/pandas/tests/series/methods/test_clip.py +++ b/pandas/tests/series/methods/test_clip.py @@ -127,3 +127,15 @@ def test_clip_with_datetimes(self): ] ) tm.assert_series_equal(result, expected) + + def test_clip_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series.clip except " + r"for the arguments 'lower' and 'upper' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.clip(0, 1, 0) + expected = Series([1, 1, 1]) + tm.assert_series_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41511
2021-05-16T14:00:39Z
2021-05-26T02:05:29Z
2021-05-26T02:05:29Z
2021-05-26T08:05:35Z
Deprecate passing args as positional in DataFrame/Series.interpolate
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 25e482fea60ee..1eb22436204a8 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -648,6 +648,7 @@ Deprecations - Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`) - Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`) - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) +- Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1fa149cd834b0..6aa537d37aea2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -77,6 +77,7 @@ Appender, Substitution, deprecate_kwarg, + deprecate_nonkeyword_arguments, doc, rewrite_axis_style_signature, ) @@ -10632,6 +10633,29 @@ def values(self) -> np.ndarray: self._consolidate_inplace() return self._mgr.as_array(transpose=True) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"]) + def interpolate( + self: DataFrame, + method: str = "linear", + axis: Axis = 0, + limit: int | None = None, + inplace: bool = False, + limit_direction: str | None = None, + limit_area: str | None = None, + downcast: str | None = None, + **kwargs, + ) -> DataFrame | None: + return super().interpolate( + method, + axis, + limit, + inplace, + limit_direction, + limit_area, + downcast, + **kwargs, + ) + DataFrame._add_numeric_operations() diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a09cc0a6324c0..3c69ba4e6bdf0 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6696,7 +6696,6 @@ def replace( else: return result.__finalize__(self, method="replace") - @final def interpolate( self: FrameOrSeries, method: str = "linear", diff --git a/pandas/core/series.py b/pandas/core/series.py index d0ff50cca5355..aaf37ad191e87 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -51,6 +51,7 @@ from pandas.util._decorators import ( Appender, Substitution, + deprecate_nonkeyword_arguments, doc, ) from pandas.util._validators import ( @@ -5256,6 +5257,29 @@ def to_period(self, freq=None, copy=True) -> Series: self, method="to_period" ) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"]) + def interpolate( + self: Series, + method: str = "linear", + axis: Axis = 0, + limit: int | None = None, + inplace: bool = False, + limit_direction: str | None = None, + limit_area: str | None = None, + downcast: str | None = None, + **kwargs, + ) -> Series | None: + return super().interpolate( + method, + axis, + limit, + inplace, + limit_direction, + limit_area, + downcast, + **kwargs, + ) + # ---------------------------------------------------------------------- # Add index _AXIS_ORDERS = ["index"] diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index 5c6fcec887dfb..d0551ffd5cffe 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -342,3 +342,15 @@ def test_interp_fillna_methods(self, axis, method): expected = df.fillna(axis=axis, method=method) result = df.interpolate(method=method, axis=axis) tm.assert_frame_equal(result, expected) + + def test_interpolate_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame.interpolate " + r"except for the argument 'method' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.interpolate("pad", 0) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index 5686e6478772d..8ca2d37016691 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -811,3 +811,15 @@ def test_interpolate_unsorted_index(self, ascending, expected_values): result = ts.sort_index(ascending=ascending).interpolate(method="index") expected = Series(data=expected_values, index=expected_values, dtype=float) tm.assert_series_equal(result, expected) + + def test_interpolate_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series.interpolate except " + r"for the argument 'method' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.interpolate("pad", 0) + expected = Series([1, 2, 3]) + tm.assert_series_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41510
2021-05-16T13:51:00Z
2021-05-19T12:49:29Z
2021-05-19T12:49:29Z
2021-05-23T20:39:37Z
Deprecate passing args as positional DataFrame/Series.ffill
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 939b3c191c4a1..24cd41383e9d7 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -682,6 +682,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, and :meth:`Series.bfill` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.sort_values` (other than ``"by"``) and :meth:`Series.sort_values` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.dropna` and :meth:`Series.dropna` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.set_index` (other than ``"keys"``) (:issue:`41485`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index bc27244c63954..75d2f4c591053 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10646,6 +10646,26 @@ def values(self) -> np.ndarray: self._consolidate_inplace() return self._mgr.as_array(transpose=True) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) + def ffill( + self: DataFrame, + axis: None | Axis = None, + inplace: bool = False, + limit: None | int = None, + downcast=None, + ) -> DataFrame | None: + return super().ffill(axis, inplace, limit, downcast) + + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) + def bfill( + self: DataFrame, + axis: None | Axis = None, + inplace: bool = False, + limit: None | int = None, + downcast=None, + ) -> DataFrame | None: + return super().bfill(axis, inplace, limit, downcast) + @deprecate_nonkeyword_arguments( version=None, allowed_args=["self", "lower", "upper"] ) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 32ecb9f8f76f5..8bbfa1f1db680 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6392,47 +6392,6 @@ def fillna( else: return result.__finalize__(self, method="fillna") - @overload - def ffill( - self: FrameOrSeries, - axis: None | Axis = ..., - inplace: Literal[False] = ..., - limit: None | int = ..., - downcast=..., - ) -> FrameOrSeries: - ... - - @overload - def ffill( - self: FrameOrSeries, - axis: None | Axis, - inplace: Literal[True], - limit: None | int = ..., - downcast=..., - ) -> None: - ... - - @overload - def ffill( - self: FrameOrSeries, - *, - inplace: Literal[True], - limit: None | int = ..., - downcast=..., - ) -> None: - ... - - @overload - def ffill( - self: FrameOrSeries, - axis: None | Axis = ..., - inplace: bool_t = ..., - limit: None | int = ..., - downcast=..., - ) -> FrameOrSeries | None: - ... - - @final @doc(klass=_shared_doc_kwargs["klass"]) def ffill( self: FrameOrSeries, @@ -6455,47 +6414,6 @@ def ffill( pad = ffill - @overload - def bfill( - self: FrameOrSeries, - axis: None | Axis = ..., - inplace: Literal[False] = ..., - limit: None | int = ..., - downcast=..., - ) -> FrameOrSeries: - ... - - @overload - def bfill( - self: FrameOrSeries, - axis: None | Axis, - inplace: Literal[True], - limit: None | int = ..., - downcast=..., - ) -> None: - ... - - @overload - def bfill( - self: FrameOrSeries, - *, - inplace: Literal[True], - limit: None | int = ..., - downcast=..., - ) -> None: - ... - - @overload - def bfill( - self: FrameOrSeries, - axis: None | Axis = ..., - inplace: bool_t = ..., - limit: None | int = ..., - downcast=..., - ) -> FrameOrSeries | None: - ... - - @final @doc(klass=_shared_doc_kwargs["klass"]) def bfill( self: FrameOrSeries, diff --git a/pandas/core/series.py b/pandas/core/series.py index ac514e6ad787c..686e6966d8e24 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5292,6 +5292,26 @@ def to_period(self, freq=None, copy=True) -> Series: self, method="to_period" ) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) + def ffill( + self: Series, + axis: None | Axis = None, + inplace: bool = False, + limit: None | int = None, + downcast=None, + ) -> Series | None: + return super().ffill(axis, inplace, limit, downcast) + + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) + def bfill( + self: Series, + axis: None | Axis = None, + inplace: bool = False, + limit: None | int = None, + downcast=None, + ) -> Series | None: + return super().bfill(axis, inplace, limit, downcast) + @deprecate_nonkeyword_arguments( version=None, allowed_args=["self", "lower", "upper"] ) diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index cb01de11a4be9..065d074eef6e8 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -326,6 +326,18 @@ def test_ffill(self, datetime_frame): datetime_frame.ffill(), datetime_frame.fillna(method="ffill") ) + def test_ffill_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame.ffill " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.ffill(0) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) + def test_bfill(self, datetime_frame): datetime_frame["A"][:5] = np.nan datetime_frame["A"][-5:] = np.nan @@ -334,6 +346,18 @@ def test_bfill(self, datetime_frame): datetime_frame.bfill(), datetime_frame.fillna(method="bfill") ) + def test_bfill_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame.bfill " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.bfill(0) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) + def test_frame_pad_backfill_limit(self): index = np.arange(10) df = DataFrame(np.random.randn(10, 4), index=index) diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 97804e0fef8b9..82c52bdaa29d7 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -777,6 +777,18 @@ def test_ffill(self): ts[2] = np.NaN tm.assert_series_equal(ts.ffill(), ts.fillna(method="ffill")) + def test_ffill_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series.ffill " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.ffill(0) + expected = Series([1, 2, 3]) + tm.assert_series_equal(result, expected) + def test_ffill_mixed_dtypes_without_missing_data(self): # GH#14956 series = Series([datetime(2015, 1, 1, tzinfo=pytz.utc), 1]) @@ -788,6 +800,18 @@ def test_bfill(self): ts[2] = np.NaN tm.assert_series_equal(ts.bfill(), ts.fillna(method="bfill")) + def test_bfill_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series.bfill " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.bfill(0) + expected = Series([1, 2, 3]) + tm.assert_series_equal(result, expected) + def test_pad_nan(self): x = Series( [np.nan, 1.0, np.nan, 3.0, np.nan], ["z", "a", "b", "c", "d"], dtype=float
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41508
2021-05-16T13:38:17Z
2021-05-27T01:12:48Z
2021-05-27T01:12:48Z
2021-05-27T08:17:54Z
Deprecate passing args as positional in sort_index
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index d26e511202f9c..953046a3a2a10 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -1897,7 +1897,7 @@ Writing in ISO date format: dfd = pd.DataFrame(np.random.randn(5, 2), columns=list("AB")) dfd["date"] = pd.Timestamp("20130101") - dfd = dfd.sort_index(1, ascending=False) + dfd = dfd.sort_index(axis=1, ascending=False) json = dfd.to_json(date_format="iso") json diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 3d3161f112327..8b1d92d28776f 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -680,6 +680,7 @@ Deprecations - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.sort_index` and :meth:`Series.sort_index` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`(:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2ad0b28f370da..6d830a7271ff1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6292,6 +6292,7 @@ def sort_values( # type: ignore[override] else: return result.__finalize__(self, method="sort_values") + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def sort_index( self, axis: Axis = 0, diff --git a/pandas/core/series.py b/pandas/core/series.py index 74ba534986592..9f804985a2288 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3468,6 +3468,7 @@ def sort_values( else: return result.__finalize__(self, method="sort_values") + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def sort_index( self, axis=0, diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index a04ed7e92478f..dbb6bb116828a 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -867,3 +867,15 @@ def test_sort_index_multiindex_sparse_column(self): result = expected.sort_index(level=0) tm.assert_frame_equal(result, expected) + + def test_sort_index_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame.sort_index " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.sort_index(1) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index b8e7b83c97ddb..8c79bafa2f888 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1352,9 +1352,9 @@ def test_loc_setitem_unsorted_multiindex_columns(self, key): expected = DataFrame([[0, 2, 0], [0, 5, 0]], columns=mi) tm.assert_frame_equal(obj, expected) - df = df.sort_index(1) + df = df.sort_index(axis=1) df.loc[:, key] = np.zeros((2, 2), dtype=int) - expected = expected.sort_index(1) + expected = expected.sort_index(axis=1) tm.assert_frame_equal(df, expected) def test_loc_setitem_uint_drop(self, any_int_dtype): diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index 4df6f52e0fff4..d7bd92c673e69 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -320,3 +320,15 @@ def test_sort_values_key_type(self): result = s.sort_index(key=lambda x: x.month_name()) expected = s.iloc[[2, 1, 0]] tm.assert_series_equal(result, expected) + + def test_sort_index_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series.sort_index " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.sort_index(0) + expected = Series([1, 2, 3]) + tm.assert_series_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41506
2021-05-16T12:34:53Z
2021-05-26T01:59:18Z
2021-05-26T01:59:17Z
2021-05-26T08:05:28Z
Deprecate passing args as positional in sort_values
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index fe88cf93886ce..939b3c191c4a1 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -682,6 +682,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.sort_values` (other than ``"by"``) and :meth:`Series.sort_values` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.dropna` and :meth:`Series.dropna` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.set_index` (other than ``"keys"``) (:issue:`41485`) - Deprecated passing arguments as positional (except for ``"levels"``) in :meth:`MultiIndex.set_levels` (:issue:`41485`) @@ -691,6 +692,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.reset_index` (other than ``"level"``) and :meth:`Series.reset_index` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) - Deprecated passing arguments as positional in :meth:`DataFrame.where` and :meth:`Series.where` (other than ``"cond"`` and ``"other"``) (:issue:`41485`) +- .. _whatsnew_130.deprecations.nuisance_columns: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 748a103a89965..bc27244c63954 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6221,6 +6221,7 @@ def f(vals) -> tuple[np.ndarray, int]: # ---------------------------------------------------------------------- # Sorting # TODO: Just move the sort_values doc here. + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "by"]) @Substitution(**_shared_doc_kwargs) @Appender(NDFrame.sort_values.__doc__) # error: Signature of "sort_values" incompatible with supertype "NDFrame" diff --git a/pandas/core/series.py b/pandas/core/series.py index ce38e1ccb2613..ac514e6ad787c 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3259,6 +3259,7 @@ def update(self, other) -> None: # ---------------------------------------------------------------------- # Reindexing, sorting + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def sort_values( self, axis=0, diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 2ca5f6aa72241..d46796bcd978b 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -856,3 +856,15 @@ def test_sort_column_level_and_index_label( tm.assert_frame_equal(result, expected) else: tm.assert_frame_equal(result, expected) + + def test_sort_values_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame\.sort_values " + r"except for the argument 'by' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.sort_values("a", 0) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py index fe2046401f657..28332a94207fe 100644 --- a/pandas/tests/series/methods/test_sort_values.py +++ b/pandas/tests/series/methods/test_sort_values.py @@ -187,30 +187,42 @@ def test_sort_values_ignore_index( tm.assert_series_equal(result_ser, expected) tm.assert_series_equal(ser, Series(original_list)) + def test_sort_values_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series\.sort_values " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.sort_values(0) + expected = Series([1, 2, 3]) + tm.assert_series_equal(result, expected) + class TestSeriesSortingKey: def test_sort_values_key(self): series = Series(np.array(["Hello", "goodbye"])) - result = series.sort_values(0) + result = series.sort_values(axis=0) expected = series tm.assert_series_equal(result, expected) - result = series.sort_values(0, key=lambda x: x.str.lower()) + result = series.sort_values(axis=0, key=lambda x: x.str.lower()) expected = series[::-1] tm.assert_series_equal(result, expected) def test_sort_values_key_nan(self): series = Series(np.array([0, 5, np.nan, 3, 2, np.nan])) - result = series.sort_values(0) + result = series.sort_values(axis=0) expected = series.iloc[[0, 4, 3, 1, 2, 5]] tm.assert_series_equal(result, expected) - result = series.sort_values(0, key=lambda x: x + 5) + result = series.sort_values(axis=0, key=lambda x: x + 5) expected = series.iloc[[0, 4, 3, 1, 2, 5]] tm.assert_series_equal(result, expected) - result = series.sort_values(0, key=lambda x: -x, ascending=False) + result = series.sort_values(axis=0, key=lambda x: -x, ascending=False) expected = series.iloc[[0, 4, 3, 1, 2, 5]] tm.assert_series_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41505
2021-05-16T12:25:28Z
2021-05-26T20:50:23Z
2021-05-26T20:50:23Z
2021-05-26T20:51:22Z
Deprecate passing args as positional in dropna
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index bbcb49cb6f129..fe88cf93886ce 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -682,6 +682,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.dropna` and :meth:`Series.dropna` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.set_index` (other than ``"keys"``) (:issue:`41485`) - Deprecated passing arguments as positional (except for ``"levels"``) in :meth:`MultiIndex.set_levels` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.sort_index` and :meth:`Series.sort_index` (:issue:`41485`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 35b55f68d0240..748a103a89965 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5835,6 +5835,7 @@ def notna(self) -> DataFrame: def notnull(self) -> DataFrame: return ~self.isna() + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def dropna( self, axis: Axis = 0, diff --git a/pandas/core/series.py b/pandas/core/series.py index 0975b1013e8d2..ce38e1ccb2613 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5093,6 +5093,7 @@ def notna(self) -> Series: def notnull(self) -> Series: return super().notnull() + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def dropna(self, axis=0, inplace=False, how=None): """ Return a new Series with missing values removed. diff --git a/pandas/tests/frame/methods/test_dropna.py b/pandas/tests/frame/methods/test_dropna.py index b671bb1afb27a..76a6f3aa25362 100644 --- a/pandas/tests/frame/methods/test_dropna.py +++ b/pandas/tests/frame/methods/test_dropna.py @@ -231,3 +231,15 @@ def test_dropna_with_duplicate_columns(self): result = df.dropna(subset=["A", "C"], how="all") tm.assert_frame_equal(result, expected) + + def test_dropna_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame\.dropna " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.dropna(1) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_dropna.py b/pandas/tests/series/methods/test_dropna.py index 5bff7306fac33..0dab9271bfee5 100644 --- a/pandas/tests/series/methods/test_dropna.py +++ b/pandas/tests/series/methods/test_dropna.py @@ -101,3 +101,15 @@ def test_datetime64_tz_dropna(self): ) assert result.dtype == "datetime64[ns, Asia/Tokyo]" tm.assert_series_equal(result, expected) + + def test_dropna_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series\.dropna " + r"will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.dropna(0) + expected = Series([1, 2, 3]) + tm.assert_series_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41504
2021-05-16T12:14:46Z
2021-05-26T15:30:23Z
2021-05-26T15:30:23Z
2021-05-26T20:52:16Z
PERF: load plotting entrypoint only when necessary
diff --git a/asv_bench/benchmarks/plotting.py b/asv_bench/benchmarks/plotting.py index 11e43401f9395..249a8f3f556a1 100644 --- a/asv_bench/benchmarks/plotting.py +++ b/asv_bench/benchmarks/plotting.py @@ -1,5 +1,9 @@ +import importlib +import sys + import matplotlib import numpy as np +import pkg_resources from pandas import ( DataFrame, @@ -13,6 +17,8 @@ except ImportError: from pandas.tools.plotting import andrews_curves +from pandas.plotting._core import _get_plot_backend + matplotlib.use("Agg") @@ -99,4 +105,28 @@ def time_plot_andrews_curves(self): andrews_curves(self.df, "Name") +class BackendLoading: + repeat = 1 + number = 1 + warmup_time = 0 + + def setup(self): + dist = pkg_resources.get_distribution("pandas") + spec = importlib.machinery.ModuleSpec("my_backend", None) + mod = importlib.util.module_from_spec(spec) + mod.plot = lambda *args, **kwargs: 1 + + backends = pkg_resources.get_entry_map("pandas") + my_entrypoint = pkg_resources.EntryPoint( + "pandas_plotting_backend", mod.__name__, dist=dist + ) + backends["pandas_plotting_backends"][mod.__name__] = my_entrypoint + for i in range(10): + backends["pandas_plotting_backends"][str(i)] = my_entrypoint + sys.modules["my_backend"] = mod + + def time_get_plot_backend(self): + _get_plot_backend("my_backend") + + from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 409125b6d6691..a8ae36a1b17db 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -812,6 +812,7 @@ Performance improvements - Performance improvement in :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` with nullable data types (:issue:`37493`) - Performance improvement in :meth:`Series.nunique` with nan values (:issue:`40865`) - Performance improvement in :meth:`DataFrame.transpose`, :meth:`Series.unstack` with ``DatetimeTZDtype`` (:issue:`40149`) +- Performance improvement in :meth:`Series.plot` and :meth:`DataFrame.plot` with entry point lazy loading (:issue:`41492`) .. --------------------------------------------------------------------------- diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 27f8835968b54..5d3db13610845 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1,11 +1,14 @@ from __future__ import annotations import importlib +import types from typing import ( TYPE_CHECKING, Sequence, ) +import pkg_resources + from pandas._config import get_option from pandas._typing import IndexLabel @@ -865,7 +868,7 @@ def _get_call_args(backend_name, data, args, kwargs): if args and isinstance(data, ABCSeries): positional_args = str(args)[1:-1] keyword_args = ", ".join( - f"{name}={repr(value)}" for (name, default), value in zip(arg_def, args) + f"{name}={repr(value)}" for (name, _), value in zip(arg_def, args) ) msg = ( "`Series.plot()` should not be called with positional " @@ -876,7 +879,7 @@ def _get_call_args(backend_name, data, args, kwargs): ) raise TypeError(msg) - pos_args = {name: value for value, (name, _) in zip(args, arg_def)} + pos_args = {name: value for (name, _), value in zip(arg_def, args)} if backend_name == "pandas.plotting._matplotlib": kwargs = dict(arg_def, **pos_args, **kwargs) else: @@ -1724,91 +1727,90 @@ def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwargs): return self(kind="hexbin", x=x, y=y, C=C, **kwargs) -_backends = {} +_backends: dict[str, types.ModuleType] = {} -def _find_backend(backend: str): +def _load_backend(backend: str) -> types.ModuleType: """ - Find a pandas plotting backend> + Load a pandas plotting backend. Parameters ---------- backend : str The identifier for the backend. Either an entrypoint item registered - with pkg_resources, or a module name. - - Notes - ----- - Modifies _backends with imported backends as a side effect. + with pkg_resources, "matplotlib", or a module name. Returns ------- types.ModuleType The imported backend. """ - import pkg_resources # Delay import for performance. + if backend == "matplotlib": + # Because matplotlib is an optional dependency and first-party backend, + # we need to attempt an import here to raise an ImportError if needed. + try: + module = importlib.import_module("pandas.plotting._matplotlib") + except ImportError: + raise ImportError( + "matplotlib is required for plotting when the " + 'default backend "matplotlib" is selected.' + ) from None + return module + + found_backend = False for entry_point in pkg_resources.iter_entry_points("pandas_plotting_backends"): - if entry_point.name == "matplotlib": - # matplotlib is an optional dependency. When - # missing, this would raise. - continue - _backends[entry_point.name] = entry_point.load() + found_backend = entry_point.name == backend + if found_backend: + module = entry_point.load() + break - try: - return _backends[backend] - except KeyError: + if not found_backend: # Fall back to unregistered, module name approach. try: module = importlib.import_module(backend) + found_backend = True except ImportError: # We re-raise later on. pass - else: - if hasattr(module, "plot"): - # Validate that the interface is implemented when the option - # is set, rather than at plot time. - _backends[backend] = module - return module + + if found_backend: + if hasattr(module, "plot"): + # Validate that the interface is implemented when the option is set, + # rather than at plot time. + return module raise ValueError( - f"Could not find plotting backend '{backend}'. Ensure that you've installed " - f"the package providing the '{backend}' entrypoint, or that the package has a " - "top-level `.plot` method." + f"Could not find plotting backend '{backend}'. Ensure that you've " + f"installed the package providing the '{backend}' entrypoint, or that " + "the package has a top-level `.plot` method." ) -def _get_plot_backend(backend=None): +def _get_plot_backend(backend: str | None = None): """ Return the plotting backend to use (e.g. `pandas.plotting._matplotlib`). - The plotting system of pandas has been using matplotlib, but the idea here - is that it can also work with other third-party backends. In the future, - this function will return the backend from a pandas option, and all the - rest of the code in this file will use the backend specified there for the - plotting. + The plotting system of pandas uses matplotlib by default, but the idea here + is that it can also work with other third-party backends. This function + returns the module which provides a top-level `.plot` method that will + actually do the plotting. The backend is specified from a string, which + either comes from the keyword argument `backend`, or, if not specified, from + the option `pandas.options.plotting.backend`. All the rest of the code in + this file uses the backend specified there for the plotting. The backend is imported lazily, as matplotlib is a soft dependency, and pandas can be used without it being installed. + + Notes + ----- + Modifies `_backends` with imported backend as a side effect. """ backend = backend or get_option("plotting.backend") - if backend == "matplotlib": - # Because matplotlib is an optional dependency and first-party backend, - # we need to attempt an import here to raise an ImportError if needed. - try: - import pandas.plotting._matplotlib as module - except ImportError: - raise ImportError( - "matplotlib is required for plotting when the " - 'default backend "matplotlib" is selected.' - ) from None - - _backends["matplotlib"] = module - if backend in _backends: return _backends[backend] - module = _find_backend(backend) + module = _load_backend(backend) _backends[backend] = module return module
- [x] closes #41492 - [x] tests added / passed (I only ran plotting/test_backend.py, which seemed appropriate) - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41503
2021-05-16T12:02:14Z
2021-06-04T14:40:53Z
2021-06-04T14:40:53Z
2021-06-04T15:25:07Z
[ArrowStringArray] REF: dedup df creation in str.extract
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 15fc2d9e6d3c5..5606380908f38 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -3086,52 +3086,38 @@ def _get_group_names(regex: Pattern) -> List[Hashable]: def _str_extract_noexpand(arr, pat, flags=0): """ - Find groups in each string in the Series using passed regular - expression. This function is called from - str_extract(expand=False), and can return Series, DataFrame, or - Index. + Find groups in each string in the Series/Index using passed regular expression. + This function is called from str_extract(expand=False) when there is a single group + in the regex. + + Returns + ------- + np.ndarray """ - from pandas import ( - DataFrame, - array as pd_array, - ) + from pandas import array as pd_array regex = re.compile(pat, flags=flags) groups_or_na = _groups_or_na_fun(regex) result_dtype = _result_dtype(arr) - if regex.groups == 1: - result = np.array([groups_or_na(val)[0] for val in arr], dtype=object) - name = _get_single_group_name(regex) - # not dispatching, so we have to reconstruct here. - result = pd_array(result, dtype=result_dtype) - else: - name = None - columns = _get_group_names(regex) - if arr.size == 0: - # error: Incompatible types in assignment (expression has type - # "DataFrame", variable has type "ndarray") - result = DataFrame( # type: ignore[assignment] - columns=columns, dtype=result_dtype - ) - else: - # error: Incompatible types in assignment (expression has type - # "DataFrame", variable has type "ndarray") - result = DataFrame( # type:ignore[assignment] - [groups_or_na(val) for val in arr], - columns=columns, - index=arr.index, - dtype=result_dtype, - ) - return result, name + result = np.array([groups_or_na(val)[0] for val in arr], dtype=object) + # not dispatching, so we have to reconstruct here. + result = pd_array(result, dtype=result_dtype) + return result def _str_extract_frame(arr, pat, flags=0): """ - For each subject string in the Series, extract groups from the - first match of regular expression pat. This function is called from - str_extract(expand=True), and always returns a DataFrame. + Find groups in each string in the Series/Index using passed regular expression. + + For each subject string in the Series/Index, extract groups from the first match of + regular expression pat. This function is called from str_extract(expand=True) or + str_extract(expand=False) when there is more than one group in the regex. + + Returns + ------- + DataFrame """ from pandas import DataFrame @@ -3141,11 +3127,13 @@ def _str_extract_frame(arr, pat, flags=0): columns = _get_group_names(regex) result_dtype = _result_dtype(arr) - if len(arr) == 0: + if arr.size == 0: return DataFrame(columns=columns, dtype=result_dtype) - try: + + result_index: Optional["Index"] + if isinstance(arr, ABCSeries): result_index = arr.index - except AttributeError: + else: result_index = None return DataFrame( [groups_or_na(val) for val in arr], @@ -3156,12 +3144,16 @@ def _str_extract_frame(arr, pat, flags=0): def str_extract(arr, pat, flags=0, expand=True): - if expand: + regex = re.compile(pat, flags=flags) + returns_df = regex.groups > 1 or expand + + if returns_df: + name = None result = _str_extract_frame(arr._orig, pat, flags=flags) - return result.__finalize__(arr._orig, method="str_extract") else: - result, name = _str_extract_noexpand(arr._orig, pat, flags=flags) - return arr._wrap_result(result, name=name, expand=expand) + name = _get_single_group_name(regex) + result = _str_extract_noexpand(arr._orig, pat, flags=flags) + return arr._wrap_result(result, name=name) def str_extractall(arr, pat, flags=0):
step towards #41372
https://api.github.com/repos/pandas-dev/pandas/pulls/41502
2021-05-16T09:40:36Z
2021-05-17T15:00:57Z
2021-05-17T15:00:57Z
2021-05-17T15:47:41Z
TST/CLN: parameterize/dedup replace test2
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index e6e992d37fd5d..c5bc15effa99a 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1432,213 +1432,44 @@ def test_replace_bytes(self, frame_or_series): class TestDataFrameReplaceRegex: - def test_regex_replace_scalar(self, mix_ab): - obj = {"a": list("ab.."), "b": list("efgh")} - dfobj = DataFrame(obj) - dfmix = DataFrame(mix_ab) - - # simplest cases - # regex -> value - # obj frame - res = dfobj.replace(r"\s*\.\s*", np.nan, regex=True) - tm.assert_frame_equal(dfobj, res.fillna(".")) - - # mixed - res = dfmix.replace(r"\s*\.\s*", np.nan, regex=True) - tm.assert_frame_equal(dfmix, res.fillna(".")) - - # regex -> regex - # obj frame - res = dfobj.replace(r"\s*(\.)\s*", r"\1\1\1", regex=True) - objc = obj.copy() - objc["a"] = ["a", "b", "...", "..."] - expec = DataFrame(objc) - tm.assert_frame_equal(res, expec) - - # with mixed - res = dfmix.replace(r"\s*(\.)\s*", r"\1\1\1", regex=True) - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) - - # everything with compiled regexs as well - res = dfobj.replace(re.compile(r"\s*\.\s*"), np.nan, regex=True) - tm.assert_frame_equal(dfobj, res.fillna(".")) - - # mixed - res = dfmix.replace(re.compile(r"\s*\.\s*"), np.nan, regex=True) - tm.assert_frame_equal(dfmix, res.fillna(".")) - - # regex -> regex - # obj frame - res = dfobj.replace(re.compile(r"\s*(\.)\s*"), r"\1\1\1") - objc = obj.copy() - objc["a"] = ["a", "b", "...", "..."] - expec = DataFrame(objc) - tm.assert_frame_equal(res, expec) - - # with mixed - res = dfmix.replace(re.compile(r"\s*(\.)\s*"), r"\1\1\1") - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) - - res = dfmix.replace(regex=re.compile(r"\s*(\.)\s*"), value=r"\1\1\1") - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) - - res = dfmix.replace(regex=r"\s*(\.)\s*", value=r"\1\1\1") - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) - - def test_regex_replace_scalar_inplace(self, mix_ab): - obj = {"a": list("ab.."), "b": list("efgh")} - dfobj = DataFrame(obj) - dfmix = DataFrame(mix_ab) - - # simplest cases - # regex -> value - # obj frame - res = dfobj.copy() - return_value = res.replace(r"\s*\.\s*", np.nan, regex=True, inplace=True) - assert return_value is None - tm.assert_frame_equal(dfobj, res.fillna(".")) - - # mixed - res = dfmix.copy() - return_value = res.replace(r"\s*\.\s*", np.nan, regex=True, inplace=True) - assert return_value is None - tm.assert_frame_equal(dfmix, res.fillna(".")) - - # regex -> regex - # obj frame - res = dfobj.copy() - return_value = res.replace(r"\s*(\.)\s*", r"\1\1\1", regex=True, inplace=True) - assert return_value is None - objc = obj.copy() - objc["a"] = ["a", "b", "...", "..."] - expec = DataFrame(objc) - tm.assert_frame_equal(res, expec) - - # with mixed - res = dfmix.copy() - return_value = res.replace(r"\s*(\.)\s*", r"\1\1\1", regex=True, inplace=True) - assert return_value is None - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) - - # everything with compiled regexs as well - res = dfobj.copy() - return_value = res.replace( - re.compile(r"\s*\.\s*"), np.nan, regex=True, inplace=True - ) - assert return_value is None - tm.assert_frame_equal(dfobj, res.fillna(".")) - - # mixed - res = dfmix.copy() - return_value = res.replace( - re.compile(r"\s*\.\s*"), np.nan, regex=True, inplace=True - ) - assert return_value is None - tm.assert_frame_equal(dfmix, res.fillna(".")) - - # regex -> regex - # obj frame - res = dfobj.copy() - return_value = res.replace( - re.compile(r"\s*(\.)\s*"), r"\1\1\1", regex=True, inplace=True - ) - assert return_value is None - objc = obj.copy() - objc["a"] = ["a", "b", "...", "..."] - expec = DataFrame(objc) - tm.assert_frame_equal(res, expec) - - # with mixed - res = dfmix.copy() - return_value = res.replace( - re.compile(r"\s*(\.)\s*"), r"\1\1\1", regex=True, inplace=True - ) - assert return_value is None - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) - - res = dfobj.copy() - return_value = res.replace(regex=r"\s*\.\s*", value=np.nan, inplace=True) - assert return_value is None - tm.assert_frame_equal(dfobj, res.fillna(".")) - - # mixed - res = dfmix.copy() - return_value = res.replace(regex=r"\s*\.\s*", value=np.nan, inplace=True) - assert return_value is None - tm.assert_frame_equal(dfmix, res.fillna(".")) + @pytest.mark.parametrize( + "data", + [ + {"a": list("ab.."), "b": list("efgh")}, + {"a": list("ab.."), "b": list(range(4))}, + ], + ) + @pytest.mark.parametrize( + "to_replace,value", [(r"\s*\.\s*", np.nan), (r"\s*(\.)\s*", r"\1\1\1")] + ) + @pytest.mark.parametrize("compile_regex", [True, False]) + @pytest.mark.parametrize("regex_kwarg", [True, False]) + @pytest.mark.parametrize("inplace", [True, False]) + def test_regex_replace_scalar( + self, data, to_replace, value, compile_regex, regex_kwarg, inplace + ): + df = DataFrame(data) + expected = df.copy() - # regex -> regex - # obj frame - res = dfobj.copy() - return_value = res.replace(regex=r"\s*(\.)\s*", value=r"\1\1\1", inplace=True) - assert return_value is None - objc = obj.copy() - objc["a"] = ["a", "b", "...", "..."] - expec = DataFrame(objc) - tm.assert_frame_equal(res, expec) + if compile_regex: + to_replace = re.compile(to_replace) - # with mixed - res = dfmix.copy() - return_value = res.replace(regex=r"\s*(\.)\s*", value=r"\1\1\1", inplace=True) - assert return_value is None - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) + if regex_kwarg: + regex = to_replace + to_replace = None + else: + regex = True - # everything with compiled regexs as well - res = dfobj.copy() - return_value = res.replace( - regex=re.compile(r"\s*\.\s*"), value=np.nan, inplace=True - ) - assert return_value is None - tm.assert_frame_equal(dfobj, res.fillna(".")) + result = df.replace(to_replace, value, inplace=inplace, regex=regex) - # mixed - res = dfmix.copy() - return_value = res.replace( - regex=re.compile(r"\s*\.\s*"), value=np.nan, inplace=True - ) - assert return_value is None - tm.assert_frame_equal(dfmix, res.fillna(".")) + if inplace: + assert result is None + result = df - # regex -> regex - # obj frame - res = dfobj.copy() - return_value = res.replace( - regex=re.compile(r"\s*(\.)\s*"), value=r"\1\1\1", inplace=True - ) - assert return_value is None - objc = obj.copy() - objc["a"] = ["a", "b", "...", "..."] - expec = DataFrame(objc) - tm.assert_frame_equal(res, expec) + if value is np.nan: + expected_replace_val = np.nan + else: + expected_replace_val = "..." - # with mixed - res = dfmix.copy() - return_value = res.replace( - regex=re.compile(r"\s*(\.)\s*"), value=r"\1\1\1", inplace=True - ) - assert return_value is None - mixc = mix_ab.copy() - mixc["b"] = ["a", "b", "...", "..."] - expec = DataFrame(mixc) - tm.assert_frame_equal(res, expec) + expected.loc[expected["a"] == ".", "a"] = expected_replace_val + tm.assert_frame_equal(result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/41501
2021-05-16T01:44:16Z
2021-05-19T03:01:16Z
2021-05-19T03:01:16Z
2021-05-19T03:01:20Z
Deprecate non-keyword arguments for drop_duplicates.
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d357e4a633347..5ad6369c12ecf 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -676,6 +676,7 @@ Deprecations - Deprecated using ``usecols`` with out of bounds indices for ``read_csv`` with ``engine="c"`` (:issue:`25623`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`(:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 18ee1ad9bcd96..c98722261a519 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6005,6 +6005,7 @@ def dropna( else: return result + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "subset"]) def drop_duplicates( self, subset: Hashable | Sequence[Hashable] | None = None, diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 8fb88e625d948..9c8094df4da8e 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -54,6 +54,7 @@ from pandas.util._decorators import ( Appender, cache_readonly, + deprecate_nonkeyword_arguments, doc, ) @@ -2636,7 +2637,7 @@ def unique(self: _IndexT, level: Hashable | None = None) -> _IndexT: result = super().unique() return self._shallow_copy(result) - @final + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def drop_duplicates(self: _IndexT, keep: str_t | bool = "first") -> _IndexT: """ Return Index with duplicate values removed. diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 1a3719233a1da..2a03b5696fcc2 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -41,6 +41,7 @@ from pandas.util._decorators import ( Appender, cache_readonly, + deprecate_nonkeyword_arguments, doc, ) @@ -3793,6 +3794,10 @@ def isin(self, values, level=None) -> np.ndarray: return np.zeros(len(levs), dtype=np.bool_) return levs.isin(values) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) + def drop_duplicates(self, keep: str | bool = "first") -> MultiIndex: + return super().drop_duplicates(keep=keep) + # --------------------------------------------------------------- # Arithmetic/Numeric Methods - Disabled diff --git a/pandas/core/series.py b/pandas/core/series.py index d8b7876028839..db319e9db3c60 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2057,6 +2057,7 @@ def drop_duplicates(self, *, inplace: Literal[True]) -> None: def drop_duplicates(self, keep=..., inplace: bool = ...) -> Series | None: ... + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def drop_duplicates(self, keep="first", inplace=False) -> Series | None: """ Return Series with duplicate values removed. diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index 10c1f37f4c9ba..8cbf7bbfe0368 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -471,3 +471,17 @@ def test_drop_duplicates_non_boolean_ignore_index(arg): msg = '^For argument "ignore_index" expected type bool, received type .*.$' with pytest.raises(ValueError, match=msg): df.drop_duplicates(ignore_index=arg) + + +def test_drop_duplicates_pos_args_deprecation(): + # GH#41485 + df = DataFrame({"a": [1, 1, 2], "b": [1, 1, 3], "c": [1, 1, 3]}) + msg = ( + "In a future version of pandas all arguments of " + "DataFrame.drop_duplicates except for the argument 'subset' " + "will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.drop_duplicates(["b", "c"], "last") + expected = DataFrame({"a": [1, 2], "b": [1, 3], "c": [1, 3]}, index=[1, 2]) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py index ea59d55989f8b..c2b3647379234 100644 --- a/pandas/tests/indexes/multi/test_duplicates.py +++ b/pandas/tests/indexes/multi/test_duplicates.py @@ -306,3 +306,16 @@ def test_duplicated_drop_duplicates(): assert duplicated.dtype == bool expected = MultiIndex.from_arrays(([2, 3, 2, 3], [1, 1, 2, 2])) tm.assert_index_equal(idx.drop_duplicates(keep=False), expected) + + +def test_multi_drop_duplicates_pos_args_deprecation(): + # GH#41485 + idx = MultiIndex.from_arrays([[1, 2, 3, 1], [1, 2, 3, 1]]) + msg = ( + "In a future version of pandas all arguments of " + "MultiIndex.drop_duplicates will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = idx.drop_duplicates("last") + expected = MultiIndex.from_arrays([[2, 3, 1], [2, 3, 1]]) + tm.assert_index_equal(expected, result) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 47657fff56ceb..f41c79bd09f67 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1738,3 +1738,17 @@ def test_construct_from_memoryview(klass, extra_kwargs): result = klass(memoryview(np.arange(2000, 2005)), **extra_kwargs) expected = klass(range(2000, 2005), **extra_kwargs) tm.assert_index_equal(result, expected) + + +def test_drop_duplicates_pos_args_deprecation(): + # GH#41485 + idx = Index([1, 2, 3, 1]) + msg = ( + "In a future version of pandas all arguments of " + "Index.drop_duplicates will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + idx.drop_duplicates("last") + result = idx.drop_duplicates("last") + expected = Index([2, 3, 1]) + tm.assert_index_equal(expected, result) diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py index dae1bbcd86e81..7eb51f8037792 100644 --- a/pandas/tests/series/methods/test_drop_duplicates.py +++ b/pandas/tests/series/methods/test_drop_duplicates.py @@ -223,3 +223,16 @@ def test_drop_duplicates_categorical_bool(self, ordered): return_value = sc.drop_duplicates(keep=False, inplace=True) assert return_value is None tm.assert_series_equal(sc, tc[~expected]) + + +def test_drop_duplicates_pos_args_deprecation(): + # GH#41485 + s = Series(["a", "b", "c", "b"]) + msg = ( + "In a future version of pandas all arguments of " + "Series.drop_duplicates will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.drop_duplicates("last") + expected = Series(["a", "c", "b"], index=[0, 2, 3]) + tm.assert_series_equal(expected, result)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41500
2021-05-16T01:11:37Z
2021-05-25T19:39:27Z
2021-05-25T19:39:27Z
2021-05-25T19:39:27Z
TST/CLN: parameterize/dedup replace test
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index fc25d3847867f..e6e992d37fd5d 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -57,129 +57,61 @@ def test_replace_inplace(self, datetime_frame, float_string_frame): assert return_value is None tm.assert_frame_equal(tsframe, datetime_frame.fillna(0)) - def test_regex_replace_list_obj(self): - obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")} - dfobj = DataFrame(obj) - - # lists of regexes and values - # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] - to_replace_res = [r"\s*\.\s*", r"e|f|g"] - values = [np.nan, "crap"] - res = dfobj.replace(to_replace_res, values, regex=True) - expec = DataFrame( - { - "a": ["a", "b", np.nan, np.nan], - "b": ["crap"] * 3 + ["h"], - "c": ["h", "crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) - - # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] - to_replace_res = [r"\s*(\.)\s*", r"(e|f|g)"] - values = [r"\1\1", r"\1_crap"] - res = dfobj.replace(to_replace_res, values, regex=True) - expec = DataFrame( - { - "a": ["a", "b", "..", ".."], - "b": ["e_crap", "f_crap", "g_crap", "h"], - "c": ["h", "e_crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) - - # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN - # or vN)] - to_replace_res = [r"\s*(\.)\s*", r"e"] - values = [r"\1\1", r"crap"] - res = dfobj.replace(to_replace_res, values, regex=True) - expec = DataFrame( - { - "a": ["a", "b", "..", ".."], - "b": ["crap", "f", "g", "h"], - "c": ["h", "crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) - - to_replace_res = [r"\s*(\.)\s*", r"e"] - values = [r"\1\1", r"crap"] - res = dfobj.replace(value=values, regex=to_replace_res) - expec = DataFrame( - { - "a": ["a", "b", "..", ".."], - "b": ["crap", "f", "g", "h"], - "c": ["h", "crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) - - def test_regex_replace_list_obj_inplace(self): - # same as above with inplace=True - # lists of regexes and values - obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")} - dfobj = DataFrame(obj) - - # lists of regexes and values - # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] - to_replace_res = [r"\s*\.\s*", r"e|f|g"] - values = [np.nan, "crap"] - res = dfobj.copy() - return_value = res.replace(to_replace_res, values, inplace=True, regex=True) - assert return_value is None - expec = DataFrame( - { - "a": ["a", "b", np.nan, np.nan], - "b": ["crap"] * 3 + ["h"], - "c": ["h", "crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) + @pytest.mark.parametrize( + "to_replace,values,expected", + [ + # lists of regexes and values + # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] + ( + [r"\s*\.\s*", r"e|f|g"], + [np.nan, "crap"], + { + "a": ["a", "b", np.nan, np.nan], + "b": ["crap"] * 3 + ["h"], + "c": ["h", "crap", "l", "o"], + }, + ), + # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] + ( + [r"\s*(\.)\s*", r"(e|f|g)"], + [r"\1\1", r"\1_crap"], + { + "a": ["a", "b", "..", ".."], + "b": ["e_crap", "f_crap", "g_crap", "h"], + "c": ["h", "e_crap", "l", "o"], + }, + ), + # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN + # or vN)] + ( + [r"\s*(\.)\s*", r"e"], + [r"\1\1", r"crap"], + { + "a": ["a", "b", "..", ".."], + "b": ["crap", "f", "g", "h"], + "c": ["h", "crap", "l", "o"], + }, + ), + ], + ) + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize("use_value_regex_args", [True, False]) + def test_regex_replace_list_obj( + self, to_replace, values, expected, inplace, use_value_regex_args + ): + df = DataFrame({"a": list("ab.."), "b": list("efgh"), "c": list("helo")}) - # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] - to_replace_res = [r"\s*(\.)\s*", r"(e|f|g)"] - values = [r"\1\1", r"\1_crap"] - res = dfobj.copy() - return_value = res.replace(to_replace_res, values, inplace=True, regex=True) - assert return_value is None - expec = DataFrame( - { - "a": ["a", "b", "..", ".."], - "b": ["e_crap", "f_crap", "g_crap", "h"], - "c": ["h", "e_crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) + if use_value_regex_args: + result = df.replace(value=values, regex=to_replace, inplace=inplace) + else: + result = df.replace(to_replace, values, regex=True, inplace=inplace) - # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN - # or vN)] - to_replace_res = [r"\s*(\.)\s*", r"e"] - values = [r"\1\1", r"crap"] - res = dfobj.copy() - return_value = res.replace(to_replace_res, values, inplace=True, regex=True) - assert return_value is None - expec = DataFrame( - { - "a": ["a", "b", "..", ".."], - "b": ["crap", "f", "g", "h"], - "c": ["h", "crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) + if inplace: + assert result is None + result = df - to_replace_res = [r"\s*(\.)\s*", r"e"] - values = [r"\1\1", r"crap"] - res = dfobj.copy() - return_value = res.replace(value=values, regex=to_replace_res, inplace=True) - assert return_value is None - expec = DataFrame( - { - "a": ["a", "b", "..", ".."], - "b": ["crap", "f", "g", "h"], - "c": ["h", "crap", "l", "o"], - } - ) - tm.assert_frame_equal(res, expec) + expected = DataFrame(expected) + tm.assert_frame_equal(result, expected) def test_regex_replace_list_mixed(self, mix_ab): # mixed frame to make sure this doesn't break things
https://api.github.com/repos/pandas-dev/pandas/pulls/41499
2021-05-16T00:48:44Z
2021-05-17T12:49:20Z
2021-05-17T12:49:20Z
2021-05-17T13:27:53Z
ENH: groupby rank supports object dtype
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 622029adf357f..9968a103a13bf 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -224,6 +224,7 @@ Other enhancements - :meth:`pandas.read_csv` and :meth:`pandas.read_json` expose the argument ``encoding_errors`` to control how encoding errors are handled (:issue:`39450`) - :meth:`.GroupBy.any` and :meth:`.GroupBy.all` use Kleene logic with nullable data types (:issue:`37506`) - :meth:`.GroupBy.any` and :meth:`.GroupBy.all` return a ``BooleanDtype`` for columns with nullable data types (:issue:`33449`) +- :meth:`.GroupBy.rank` now supports object-dtype data (:issue:`38278`) - Constructing a :class:`DataFrame` or :class:`Series` with the ``data`` argument being a Python iterable that is *not* a NumPy ``ndarray`` consisting of NumPy scalars will now result in a dtype with a precision the maximum of the NumPy scalars; this was already the case when ``data`` is a NumPy ``ndarray`` (:issue:`40908`) - Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`) - Add keyword ``dropna`` to :meth:`DataFrame.value_counts` to allow counting rows that include ``NA`` values (:issue:`41325`)
- [x] closes #38278 - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry This was fixed way back in #38744 and looks thoroughly tested in #41387, so just a whatsnew here. I think the other string types could also be supported with tweaks to `ea_wrap_cython_operation` to pull object data out of those types if we want to support those too.
https://api.github.com/repos/pandas-dev/pandas/pulls/41498
2021-05-16T00:31:48Z
2021-05-17T12:52:27Z
2021-05-17T12:52:26Z
2021-05-17T13:27:59Z
BUG: columns name retention in groupby methods
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 7159f422e3fd6..6ad4975d6bf38 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -1139,6 +1139,8 @@ Groupby/resample/rolling - Bug in :class:`DataFrameGroupBy` aggregations incorrectly failing to drop columns with invalid dtypes for that aggregation when there are no valid columns (:issue:`41291`) - Bug in :meth:`DataFrame.rolling.__iter__` where ``on`` was not assigned to the index of the resulting objects (:issue:`40373`) - Bug in :meth:`.DataFrameGroupBy.transform` and :meth:`.DataFrameGroupBy.agg` with ``engine="numba"`` where ``*args`` were being cached with the user passed function (:issue:`41647`) +- Bug in :class:`DataFrameGroupBy` methods ``agg``, ``transform``, ``sum``, ``bfill``, ``ffill``, ``pad``, ``pct_change``, ``shift``, ``ohlc`` dropping ``.columns.names`` (:issue:`41497`) + Reshaping ^^^^^^^^^ diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 9e787555f2b1f..49e06825617bd 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -348,6 +348,7 @@ def agg_list_like(self) -> FrameOrSeriesUnion: # multiples else: + indices = [] for index, col in enumerate(selected_obj): colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index]) try: @@ -369,7 +370,9 @@ def agg_list_like(self) -> FrameOrSeriesUnion: raise else: results.append(new_res) - keys.append(col) + indices.append(index) + + keys = selected_obj.columns.take(indices) # if we are empty if not len(results): @@ -407,6 +410,7 @@ def agg_dict_like(self) -> FrameOrSeriesUnion: ------- Result of aggregation. """ + from pandas import Index from pandas.core.reshape.concat import concat obj = self.obj @@ -443,8 +447,18 @@ def agg_dict_like(self) -> FrameOrSeriesUnion: keys_to_use = [k for k in keys if not results[k].empty] # Have to check, if at least one DataFrame is not empty. keys_to_use = keys_to_use if keys_to_use != [] else keys + if selected_obj.ndim == 2: + # keys are columns, so we can preserve names + ktu = Index(keys_to_use) + ktu._set_names(selected_obj.columns.names) + # Incompatible types in assignment (expression has type "Index", + # variable has type "List[Hashable]") + keys_to_use = ktu # type: ignore[assignment] + axis = 0 if isinstance(obj, ABCSeries) else 1 - result = concat({k: results[k] for k in keys_to_use}, axis=axis) + result = concat( + {k: results[k] for k in keys_to_use}, axis=axis, keys=keys_to_use + ) elif any(is_ndframe): # There is a mix of NDFrames and scalars raise ValueError( diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 69f992f840c7c..5cb0eac5d9074 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1020,13 +1020,15 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) if isinstance(sobj, Series): # GH#35246 test_groupby_as_index_select_column_sum_empty_df - result.columns = [sobj.name] + result.columns = self._obj_with_exclusions.columns.copy() else: + # Retain our column names + result.columns._set_names( + sobj.columns.names, level=list(range(sobj.columns.nlevels)) + ) # select everything except for the last level, which is the one # containing the name of the function(s), see GH#32040 - result.columns = result.columns.rename( - [sobj.columns.name] * result.columns.nlevels - ).droplevel(-1) + result.columns = result.columns.droplevel(-1) if not self.as_index: self._insert_inaxis_grouper_inplace(result) @@ -1665,7 +1667,7 @@ def _wrap_transformed_output( result.columns = self.obj.columns else: columns = Index(key.label for key in output) - columns.name = self.obj.columns.name + columns._set_names(self.obj._get_axis(1 - self.axis).names) result.columns = columns result.index = self.obj.index @@ -1800,7 +1802,6 @@ def nunique(self, dropna: bool = True) -> DataFrame: results = self._apply_to_column_groupbys( lambda sgb: sgb.nunique(dropna), obj=obj ) - results.columns.names = obj.columns.names # TODO: do at higher level? if not self.as_index: results.index = Index(range(len(results))) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index ea34bc75b4e31..b49622f4ac36a 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -362,8 +362,13 @@ def __init__( clean_keys.append(k) clean_objs.append(v) objs = clean_objs - name = getattr(keys, "name", None) - keys = Index(clean_keys, name=name) + + if isinstance(keys, MultiIndex): + # TODO: retain levels? + keys = type(keys).from_tuples(clean_keys, names=keys.names) + else: + name = getattr(keys, "name", None) + keys = Index(clean_keys, name=name) if len(objs) == 0: raise ValueError("All objects passed were None") diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 1d4ff25c518ee..393dc0813661f 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -300,13 +300,13 @@ def test_agg_multiple_functions_same_name_with_ohlc_present(): # ohlc expands dimensions, so different test to the above is required. df = DataFrame( np.random.randn(1000, 3), - index=pd.date_range("1/1/2012", freq="S", periods=1000), - columns=["A", "B", "C"], + index=pd.date_range("1/1/2012", freq="S", periods=1000, name="dti"), + columns=Index(["A", "B", "C"], name="alpha"), ) result = df.resample("3T").agg( {"A": ["ohlc", partial(np.quantile, q=0.9999), partial(np.quantile, q=0.1111)]} ) - expected_index = pd.date_range("1/1/2012", freq="3T", periods=6) + expected_index = pd.date_range("1/1/2012", freq="3T", periods=6, name="dti") expected_columns = MultiIndex.from_tuples( [ ("A", "ohlc", "open"), @@ -315,7 +315,8 @@ def test_agg_multiple_functions_same_name_with_ohlc_present(): ("A", "ohlc", "close"), ("A", "quantile", "A"), ("A", "quantile", "A"), - ] + ], + names=["alpha", None, None], ) non_ohlc_expected_values = np.array( [df.resample("3T").A.quantile(q=q).values for q in [0.9999, 0.1111]] @@ -901,7 +902,12 @@ def test_grouby_agg_loses_results_with_as_index_false_relabel_multiindex(): def test_multiindex_custom_func(func): # GH 31777 data = [[1, 4, 2], [5, 7, 1]] - df = DataFrame(data, columns=MultiIndex.from_arrays([[1, 1, 2], [3, 4, 3]])) + df = DataFrame( + data, + columns=MultiIndex.from_arrays( + [[1, 1, 2], [3, 4, 3]], names=["Sisko", "Janeway"] + ), + ) result = df.groupby(np.array([0, 1])).agg(func) expected_dict = { (1, 3): {0: 1.0, 1: 5.0}, @@ -909,6 +915,7 @@ def test_multiindex_custom_func(func): (2, 3): {0: 2.0, 1: 1.0}, } expected = DataFrame(expected_dict) + expected.columns = df.columns tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 382a940d2a92c..89944e2a745e4 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -637,10 +637,11 @@ def test_as_index_select_column(): def test_groupby_as_index_select_column_sum_empty_df(): # GH 35246 - df = DataFrame(columns=["A", "B", "C"]) + df = DataFrame(columns=Index(["A", "B", "C"], name="alpha")) left = df.groupby(by="A", as_index=False)["B"].sum(numeric_only=False) - assert type(left) is DataFrame - assert left.to_dict() == {"A": {}, "B": {}} + + expected = DataFrame(columns=df.columns[:2], index=range(0)) + tm.assert_frame_equal(left, expected) def test_groupby_as_index_agg(df): @@ -1944,8 +1945,8 @@ def test_groupby_agg_ohlc_non_first(): # GH 21716 df = DataFrame( [[1], [1]], - columns=["foo"], - index=date_range("2018-01-01", periods=2, freq="D"), + columns=Index(["foo"], name="mycols"), + index=date_range("2018-01-01", periods=2, freq="D", name="dti"), ) expected = DataFrame( @@ -1957,9 +1958,10 @@ def test_groupby_agg_ohlc_non_first(): ("foo", "ohlc", "high"), ("foo", "ohlc", "low"), ("foo", "ohlc", "close"), - ) + ), + names=["mycols", None, None], ), - index=date_range("2018-01-01", periods=2, freq="D"), + index=date_range("2018-01-01", periods=2, freq="D", name="dti"), ) result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"]) @@ -2131,7 +2133,11 @@ def test_groupby_duplicate_index(): @pytest.mark.parametrize( - "idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))] + "idx", + [ + Index(["a", "a"], name="foo"), + MultiIndex.from_tuples((("a", "a"), ("a", "a")), names=["foo", "bar"]), + ], ) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_dup_labels_output_shape(groupby_func, idx):
- [x] closes #41564 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41497
2021-05-15T23:40:24Z
2021-06-17T17:53:44Z
2021-06-17T17:53:44Z
2021-06-17T18:49:26Z
Deprecate passing default arguments as positional in reset_index
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d357e4a633347..532af3c65bc1e 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -677,6 +677,7 @@ Deprecations - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.reset_index` (other than ``"level"``) and :meth:`Series.reset_index` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) .. _whatsnew_130.deprecations.nuisance_columns: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 18ee1ad9bcd96..67c405c792c34 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5619,6 +5619,7 @@ def reset_index( ) -> DataFrame | None: ... + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "level"]) def reset_index( self, level: Hashable | Sequence[Hashable] | None = None, diff --git a/pandas/core/series.py b/pandas/core/series.py index d8b7876028839..506943ce00860 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1308,6 +1308,7 @@ def repeat(self, repeats, axis=None) -> Series: self, method="repeat" ) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "level"]) def reset_index(self, level=None, drop=False, name=None, inplace=False): """ Generate a new DataFrame or Series with the index reset. diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index f50b2c179ad9a..91f354fecca63 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -671,3 +671,16 @@ def test_reset_index_multiindex_nat(): index=pd.DatetimeIndex(["2015-07-01", "2015-07-02", "NaT"], name="tstamp"), ) tm.assert_frame_equal(result, expected) + + +def test_drop_pos_args_deprecation(): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}).set_index("a") + msg = ( + r"In a future version of pandas all arguments of DataFrame\.reset_index " + r"except for the argument 'level' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.reset_index("a", False) + expected = DataFrame({"a": [1, 2, 3]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py index 70b9c9c9dc7d7..b159317bf813b 100644 --- a/pandas/tests/series/methods/test_reset_index.py +++ b/pandas/tests/series/methods/test_reset_index.py @@ -148,6 +148,18 @@ def test_reset_index_with_drop(self, series_with_multilevel_index): assert isinstance(deleveled, Series) assert deleveled.index.name == ser.index.name + def test_drop_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3], index=Index([1, 2, 3], name="a")) + msg = ( + r"In a future version of pandas all arguments of Series\.reset_index " + r"except for the argument 'level' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.reset_index("a", False) + expected = DataFrame({"a": [1, 2, 3], 0: [1, 2, 3]}) + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( "array, dtype",
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41496
2021-05-15T20:21:26Z
2021-05-26T02:07:49Z
2021-05-26T02:07:49Z
2021-05-26T08:07:46Z
Deprecate passing default args as positional in DataFrame.set_index
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index a4a589cef7b02..42c8a64890a16 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -681,6 +681,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``"upper"`` and ``"lower"``) (:issue:`41485`) - Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`) - Deprecated passing arguments as positional (except for ``"method"``) in :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.set_index` (other than ``"keys"``) (:issue:`41485`) - Deprecated passing arguments as positional (except for ``"levels"``) in :meth:`MultiIndex.set_levels` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.sort_index` and :meth:`Series.sort_index` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`(:issue:`41485`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3742fb595d2cd..35b55f68d0240 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5330,6 +5330,7 @@ def shift( periods=periods, freq=freq, axis=axis, fill_value=fill_value ) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "keys"]) def set_index( self, keys, diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py index 51f66128b1500..1b3db10ec6158 100644 --- a/pandas/tests/frame/methods/test_set_index.py +++ b/pandas/tests/frame/methods/test_set_index.py @@ -704,3 +704,15 @@ def test_set_index_periodindex(self): tm.assert_index_equal(df.index, idx1) df = df.set_index(idx2) tm.assert_index_equal(df.index, idx2) + + def test_drop_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame\.set_index " + r"except for the argument 'keys' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.set_index("a", True) + expected = DataFrame(index=Index([1, 2, 3], name="a")) + tm.assert_frame_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41495
2021-05-15T19:54:08Z
2021-05-26T12:40:03Z
2021-05-26T12:40:03Z
2021-05-26T14:50:31Z
TST: Add tests for old issues 2
diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py index 75d93ed2aafc6..0a3d2e1c9a8fc 100644 --- a/pandas/tests/frame/methods/test_diff.py +++ b/pandas/tests/frame/methods/test_diff.py @@ -285,3 +285,12 @@ def test_diff_readonly(self): result = df.diff() expected = DataFrame(np.array(df)).diff() tm.assert_frame_equal(result, expected) + + def test_diff_all_int_dtype(self, any_int_dtype): + # GH 14773 + df = DataFrame(range(5)) + df = df.astype(any_int_dtype) + result = df.diff() + expected_dtype = "float32" if any_int_dtype in ("int8", "int16") else "float64" + expected = DataFrame([np.nan, 1.0, 1.0, 1.0, 1.0], dtype=expected_dtype) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index dbb5cb357de47..aca061cdd197b 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -4,6 +4,7 @@ import pandas as pd from pandas import ( DataFrame, + Index, Series, Timestamp, ) @@ -650,3 +651,68 @@ def test_quantile_ea_scalar(self, index, frame_or_series): assert result == expected else: tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, expected_data, expected_index, axis", + [ + ["float64", [], [], 1], + ["int64", [], [], 1], + ["float64", [np.nan, np.nan], ["a", "b"], 0], + ["int64", [np.nan, np.nan], ["a", "b"], 0], + ], + ) + def test_empty_numeric(self, dtype, expected_data, expected_index, axis): + # GH 14564 + df = DataFrame(columns=["a", "b"], dtype=dtype) + result = df.quantile(0.5, axis=axis) + expected = Series( + expected_data, name=0.5, index=Index(expected_index), dtype="float64" + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, expected_data, expected_index, axis, expected_dtype", + [ + pytest.param( + "datetime64[ns]", + [], + [], + 1, + "datetime64[ns]", + marks=pytest.mark.xfail(reason="#GH 41544"), + ), + ["datetime64[ns]", [pd.NaT, pd.NaT], ["a", "b"], 0, "datetime64[ns]"], + ], + ) + def test_empty_datelike( + self, dtype, expected_data, expected_index, axis, expected_dtype + ): + # GH 14564 + df = DataFrame(columns=["a", "b"], dtype=dtype) + result = df.quantile(0.5, axis=axis, numeric_only=False) + expected = Series( + expected_data, name=0.5, index=Index(expected_index), dtype=expected_dtype + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "expected_data, expected_index, axis", + [ + [[np.nan, np.nan], range(2), 1], + [[], [], 0], + ], + ) + def test_datelike_numeric_only(self, expected_data, expected_index, axis): + # GH 14564 + df = DataFrame( + { + "a": pd.to_datetime(["2010", "2011"]), + "b": [0, 5], + "c": pd.to_datetime(["2011", "2012"]), + } + ) + result = df[["a", "c"]].quantile(0.5, axis=axis) + expected = Series( + expected_data, name=0.5, index=Index(expected_index), dtype=np.float64 + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 03376bdce26f8..6e9991ff17ac3 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2681,3 +2681,14 @@ def test_from_out_of_bounds_timedelta(self, constructor, cls): result = constructor(scalar) assert type(get1(result)) is cls + + def test_nested_list_columns(self): + # GH 14467 + result = DataFrame( + [[1, 2, 3], [4, 5, 6]], columns=[["A", "A", "A"], ["a", "b", "c"]] + ) + expected = DataFrame( + [[1, 2, 3], [4, 5, 6]], + columns=MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")]), + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index 6348014ca72d2..4a7c4faade00d 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -1999,6 +1999,39 @@ def test_stack_nan_in_multiindex_columns(self): ) tm.assert_frame_equal(result, expected) + def test_multi_level_stack_categorical(self): + # GH 15239 + midx = MultiIndex.from_arrays( + [ + ["A"] * 2 + ["B"] * 2, + pd.Categorical(list("abab")), + pd.Categorical(list("ccdd")), + ] + ) + df = DataFrame(np.arange(8).reshape(2, 4), columns=midx) + result = df.stack([1, 2]) + expected = DataFrame( + [ + [0, np.nan], + [np.nan, 2], + [1, np.nan], + [np.nan, 3], + [4, np.nan], + [np.nan, 6], + [5, np.nan], + [np.nan, 7], + ], + columns=["A", "B"], + index=MultiIndex.from_arrays( + [ + [0] * 4 + [1] * 4, + pd.Categorical(list("aabbaabb")), + pd.Categorical(list("cdcdcdcd")), + ] + ), + ) + tm.assert_frame_equal(result, expected) + def test_stack_nan_level(self): # GH 9406 df_nan = DataFrame( diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 83aeb29ec53df..d256b19dbb148 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2265,3 +2265,20 @@ def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex): result = dups.groupby(level=0).mean() expected = dups.groupby(dups.index).mean() tm.assert_series_equal(result, expected) + + +def test_groupby_all_nan_groups_drop(): + # GH 15036 + s = Series([1, 2, 3], [np.nan, np.nan, np.nan]) + result = s.groupby(s.index).sum() + expected = Series([], index=Index([], dtype=np.float64), dtype=np.int64) + tm.assert_series_equal(result, expected) + + +def test_groupby_empty_multi_column(): + # GH 15106 + result = DataFrame(data=[], columns=["A", "B", "C"]).groupby(["A", "B"]).sum() + expected = DataFrame( + [], columns=["C"], index=MultiIndex([[], []], [[], []], names=["A", "B"]) + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 3cc77aa723fe9..0ffc6044a5897 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1750,3 +1750,23 @@ def test_readjson_bool_series(self): result = read_json("[true, true, false]", typ="series") expected = Series([True, True, False]) tm.assert_series_equal(result, expected) + + def test_to_json_multiindex_escape(self): + # GH 15273 + df = DataFrame( + True, + index=pd.date_range("2017-01-20", "2017-01-23"), + columns=["foo", "bar"], + ).stack() + result = df.to_json() + expected = ( + "{\"(Timestamp('2017-01-20 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-20 00:00:00'), 'bar')\":true," + "\"(Timestamp('2017-01-21 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-21 00:00:00'), 'bar')\":true," + "\"(Timestamp('2017-01-22 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-22 00:00:00'), 'bar')\":true," + "\"(Timestamp('2017-01-23 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-23 00:00:00'), 'bar')\":true}" + ) + assert result == expected
- [x] closes #14467 - [x] closes #14564 - [x] closes #14773 - [x] closes #15036 - [x] closes #15106 - [x] closes #15239 - [x] closes #15273 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/41493
2021-05-15T19:22:14Z
2021-05-19T12:53:59Z
2021-05-19T12:53:57Z
2021-05-19T17:25:38Z
Deprecate nonkeyword args set axis
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 24cd41383e9d7..5436685c1f14f 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -692,9 +692,11 @@ Deprecations - Deprecated passing arguments (apart from ``value``) as positional in :meth:`DataFrame.fillna` and :meth:`Series.fillna` (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.reset_index` (other than ``"level"``) and :meth:`Series.reset_index` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) +- Deprecated passing arguments as positional in :meth:`DataFrame.set_axis` and :meth:`Series.set_axis` (other than ``"labels"``) (:issue:`41485`) - Deprecated passing arguments as positional in :meth:`DataFrame.where` and :meth:`Series.where` (other than ``"cond"`` and ``"other"``) (:issue:`41485`) - + .. _whatsnew_130.deprecations.nuisance_columns: Deprecated Dropping Nuisance Columns in DataFrame Reductions and DataFrameGroupBy Operations diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 75d2f4c591053..d2108fb901ca2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4703,6 +4703,7 @@ def set_axis( ) -> DataFrame | None: ... + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"]) @Appender( """ Examples diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8bbfa1f1db680..3e6642d3b1a72 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9221,7 +9221,7 @@ def shift( else: new_ax = index.shift(periods, freq) - result = self.set_axis(new_ax, axis) + result = self.set_axis(new_ax, axis=axis) return result.__finalize__(self, method="shift") @final diff --git a/pandas/core/series.py b/pandas/core/series.py index 686e6966d8e24..5767d7bd1cd44 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4483,6 +4483,7 @@ def set_axis(self, labels, *, inplace: Literal[True]) -> None: def set_axis(self, labels, axis: Axis = ..., inplace: bool = ...) -> Series | None: ... + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"]) @Appender( """ Examples diff --git a/pandas/tests/frame/methods/test_set_axis.py b/pandas/tests/frame/methods/test_set_axis.py index ee538e1d9d9ac..3284243ddac48 100644 --- a/pandas/tests/frame/methods/test_set_axis.py +++ b/pandas/tests/frame/methods/test_set_axis.py @@ -98,3 +98,26 @@ class TestSeriesSetAxis(SharedSetAxisTests): def obj(self): ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64") return ser + + +def test_nonkeyword_arguments_deprecation_warning(): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame\.set_axis " + r"except for the argument 'labels' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.set_axis([1, 2, 4], 0) + expected = DataFrame({"a": [1, 2, 3]}, index=[1, 2, 4]) + tm.assert_frame_equal(result, expected) + + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series\.set_axis " + r"except for the argument 'labels' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.set_axis([1, 2, 4], 0) + expected = Series([1, 2, 3], index=[1, 2, 4]) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py index a81085e083199..d8b5f19c6a745 100644 --- a/pandas/tests/reshape/concat/test_categorical.py +++ b/pandas/tests/reshape/concat/test_categorical.py @@ -148,8 +148,8 @@ def test_categorical_index_preserver(self): result = pd.concat([df2, df3]) expected = pd.concat( [ - df2.set_axis(df2.index.astype(object), 0), - df3.set_axis(df3.index.astype(object), 0), + df2.set_axis(df2.index.astype(object), axis=0), + df3.set_axis(df3.index.astype(object), axis=0), ] ) tm.assert_frame_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41491
2021-05-15T18:17:19Z
2021-05-27T12:08:38Z
2021-05-27T12:08:38Z
2021-05-27T12:23:32Z
[ArrowStringArray] PERF: str.extract object fallback
diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py index 0f68d1043b49d..d7fb36b062388 100644 --- a/asv_bench/benchmarks/strings.py +++ b/asv_bench/benchmarks/strings.py @@ -11,6 +11,19 @@ from .pandas_vb_common import tm +class Dtypes: + params = ["str", "string", "arrow_string"] + param_names = ["dtype"] + + def setup(self, dtype): + from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 + + try: + self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype) + except ImportError: + raise NotImplementedError + + class Construction: params = ["str", "string"] @@ -49,18 +62,7 @@ def peakmem_cat_frame_construction(self, dtype): DataFrame(self.frame_cat_arr, dtype=dtype) -class Methods: - params = ["str", "string", "arrow_string"] - param_names = ["dtype"] - - def setup(self, dtype): - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - - try: - self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype) - except ImportError: - raise NotImplementedError - +class Methods(Dtypes): def time_center(self, dtype): self.s.str.center(100) @@ -211,35 +213,26 @@ def time_cat(self, other_cols, sep, na_rep, na_frac): self.s.str.cat(others=self.others, sep=sep, na_rep=na_rep) -class Contains: +class Contains(Dtypes): - params = (["str", "string", "arrow_string"], [True, False]) + params = (Dtypes.params, [True, False]) param_names = ["dtype", "regex"] def setup(self, dtype, regex): - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - - try: - self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype) - except ImportError: - raise NotImplementedError + super().setup(dtype) def time_contains(self, dtype, regex): self.s.str.contains("A", regex=regex) -class Split: +class Split(Dtypes): - params = (["str", "string", "arrow_string"], [True, False]) + params = (Dtypes.params, [True, False]) param_names = ["dtype", "expand"] def setup(self, dtype, expand): - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - - try: - self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype).str.join("--") - except ImportError: - raise NotImplementedError + super().setup(dtype) + self.s = self.s.str.join("--") def time_split(self, dtype, expand): self.s.str.split("--", expand=expand) @@ -248,17 +241,23 @@ def time_rsplit(self, dtype, expand): self.s.str.rsplit("--", expand=expand) -class Dummies: - params = ["str", "string", "arrow_string"] - param_names = ["dtype"] +class Extract(Dtypes): - def setup(self, dtype): - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 + params = (Dtypes.params, [True, False]) + param_names = ["dtype", "expand"] - try: - self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype).str.join("|") - except ImportError: - raise NotImplementedError + def setup(self, dtype, expand): + super().setup(dtype) + + def time_extract_single_group(self, dtype, expand): + with warnings.catch_warnings(record=True): + self.s.str.extract("(\\w*)A", expand=expand) + + +class Dummies(Dtypes): + def setup(self, dtype): + super().setup(dtype) + self.s = self.s.str.join("|") def time_get_dummies(self, dtype): self.s.str.get_dummies("|") @@ -279,3 +278,9 @@ def setup(self): def time_vector_slice(self): # GH 2602 self.s.str[:5] + + +class Iter(Dtypes): + def time_iter(self, dtype): + for i in self.s: + pass diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 5606380908f38..25d36c617a894 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -3101,7 +3101,7 @@ def _str_extract_noexpand(arr, pat, flags=0): groups_or_na = _groups_or_na_fun(regex) result_dtype = _result_dtype(arr) - result = np.array([groups_or_na(val)[0] for val in arr], dtype=object) + result = np.array([groups_or_na(val)[0] for val in np.asarray(arr)], dtype=object) # not dispatching, so we have to reconstruct here. result = pd_array(result, dtype=result_dtype) return result @@ -3136,7 +3136,7 @@ def _str_extract_frame(arr, pat, flags=0): else: result_index = None return DataFrame( - [groups_or_na(val) for val in arr], + [groups_or_na(val) for val in np.asarray(arr)], columns=columns, index=result_index, dtype=result_dtype, diff --git a/pandas/tests/strings/test_extract.py b/pandas/tests/strings/test_extract.py index 2be00a689a206..16ec4a8c6831c 100644 --- a/pandas/tests/strings/test_extract.py +++ b/pandas/tests/strings/test_extract.py @@ -38,25 +38,23 @@ def test_extract_expand_kwarg(any_string_dtype): def test_extract_expand_False_mixed_object(): - mixed = Series( - [ - "aBAD_BAD", - np.nan, - "BAD_b_BAD", - True, - datetime.today(), - "foo", - None, - 1, - 2.0, - ] + ser = Series( + ["aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0] ) - result = Series(mixed).str.extract(".*(BAD[_]+).*(BAD)", expand=False) + # two groups + result = ser.str.extract(".*(BAD[_]+).*(BAD)", expand=False) er = [np.nan, np.nan] # empty row expected = DataFrame([["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er]) tm.assert_frame_equal(result, expected) + # single group + result = ser.str.extract(".*(BAD[_]+).*BAD", expand=False) + expected = Series( + ["BAD_", np.nan, "BAD_", np.nan, np.nan, np.nan, np.nan, np.nan, np.nan] + ) + tm.assert_series_equal(result, expected) + def test_extract_expand_index_raises(): # GH9980
``` before after ratio [40482273] [1788ffe6] <master> <extract-single-group> - 134±2ms 106±1ms 0.79 strings.Extract.time_extract_single_group('string', False) - 359±5ms 110±0.8ms 0.31 strings.Extract.time_extract_single_group('arrow_string', False) SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/41490
2021-05-15T17:15:34Z
2021-05-17T20:50:32Z
2021-05-17T20:50:32Z
2021-05-18T08:35:05Z
STYLE: Add pre-commit hook for debug statements
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index db3fc1853ea71..1fbd3cf85383e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -21,6 +21,7 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.4.0 hooks: + - id: debug-statements - id: end-of-file-fixer exclude: \.txt$ - id: trailing-whitespace
Added https://github.com/pre-commit/pre-commit-hooks#debug-statements as a pre-commit hook. - [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41489
2021-05-15T16:55:01Z
2021-05-16T09:10:28Z
2021-05-16T09:10:28Z
2021-05-16T10:49:44Z
BUG: CustomBusinessMonthBegin(End) sometimes ignores extra offset (GH41356)
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index ae1844b0a913c..fbb39f0357370 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -281,6 +281,7 @@ Styler Other ^^^^^ +- Bug in :meth:`CustomBusinessMonthBegin.__add__` (:meth:`CustomBusinessMonthEnd.__add__`) not applying the extra ``offset`` parameter when beginning (end) of the target month is already a business day (:issue:`41356`) .. ***DO NOT USE THIS SECTION*** diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 6596aebc1892e..0faf5fb0a741a 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -3370,7 +3370,10 @@ cdef class _CustomBusinessMonth(BusinessMixin): """ Define default roll function to be called in apply method. """ - cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds) + cbday_kwds = self.kwds.copy() + cbday_kwds['offset'] = timedelta(0) + + cbday = CustomBusinessDay(n=1, normalize=False, **cbday_kwds) if self._prefix.endswith("S"): # MonthBegin @@ -3414,6 +3417,9 @@ cdef class _CustomBusinessMonth(BusinessMixin): new = cur_month_offset_date + n * self.m_offset result = self.cbday_roll(new) + + if self.offset: + result = result + self.offset return result diff --git a/pandas/tests/tseries/offsets/test_custom_business_month.py b/pandas/tests/tseries/offsets/test_custom_business_month.py index 4cdd25d6483f7..fb0f331fa3ad3 100644 --- a/pandas/tests/tseries/offsets/test_custom_business_month.py +++ b/pandas/tests/tseries/offsets/test_custom_business_month.py @@ -7,6 +7,7 @@ from datetime import ( date, datetime, + timedelta, ) import numpy as np @@ -200,6 +201,59 @@ def test_datetimeindex(self): 0 ] == datetime(2012, 1, 3) + @pytest.mark.parametrize( + "case", + [ + ( + CBMonthBegin(n=1, offset=timedelta(days=5)), + { + datetime(2021, 3, 1): datetime(2021, 4, 1) + timedelta(days=5), + datetime(2021, 4, 17): datetime(2021, 5, 3) + timedelta(days=5), + }, + ), + ( + CBMonthBegin(n=2, offset=timedelta(days=40)), + { + datetime(2021, 3, 10): datetime(2021, 5, 3) + timedelta(days=40), + datetime(2021, 4, 30): datetime(2021, 6, 1) + timedelta(days=40), + }, + ), + ( + CBMonthBegin(n=1, offset=timedelta(days=-5)), + { + datetime(2021, 3, 1): datetime(2021, 4, 1) - timedelta(days=5), + datetime(2021, 4, 11): datetime(2021, 5, 3) - timedelta(days=5), + }, + ), + ( + -2 * CBMonthBegin(n=1, offset=timedelta(days=10)), + { + datetime(2021, 3, 1): datetime(2021, 1, 1) + timedelta(days=10), + datetime(2021, 4, 3): datetime(2021, 3, 1) + timedelta(days=10), + }, + ), + ( + CBMonthBegin(n=0, offset=timedelta(days=1)), + { + datetime(2021, 3, 2): datetime(2021, 4, 1) + timedelta(days=1), + datetime(2021, 4, 1): datetime(2021, 4, 1) + timedelta(days=1), + }, + ), + ( + CBMonthBegin( + n=1, holidays=["2021-04-01", "2021-04-02"], offset=timedelta(days=1) + ), + { + datetime(2021, 3, 2): datetime(2021, 4, 5) + timedelta(days=1), + }, + ), + ], + ) + def test_apply_with_extra_offset(self, case): + offset, cases = case + for base, expected in cases.items(): + assert_offset_equal(offset, base, expected) + class TestCustomBusinessMonthEnd(CustomBusinessMonthBase, Base): _offset = CBMonthEnd @@ -337,3 +391,54 @@ def test_datetimeindex(self): assert date_range(start="20120101", end="20130101", freq=freq).tolist()[ 0 ] == datetime(2012, 1, 31) + + @pytest.mark.parametrize( + "case", + [ + ( + CBMonthEnd(n=1, offset=timedelta(days=5)), + { + datetime(2021, 3, 1): datetime(2021, 3, 31) + timedelta(days=5), + datetime(2021, 4, 17): datetime(2021, 4, 30) + timedelta(days=5), + }, + ), + ( + CBMonthEnd(n=2, offset=timedelta(days=40)), + { + datetime(2021, 3, 10): datetime(2021, 4, 30) + timedelta(days=40), + datetime(2021, 4, 30): datetime(2021, 6, 30) + timedelta(days=40), + }, + ), + ( + CBMonthEnd(n=1, offset=timedelta(days=-5)), + { + datetime(2021, 3, 1): datetime(2021, 3, 31) - timedelta(days=5), + datetime(2021, 4, 11): datetime(2021, 4, 30) - timedelta(days=5), + }, + ), + ( + -2 * CBMonthEnd(n=1, offset=timedelta(days=10)), + { + datetime(2021, 3, 1): datetime(2021, 1, 29) + timedelta(days=10), + datetime(2021, 4, 3): datetime(2021, 2, 26) + timedelta(days=10), + }, + ), + ( + CBMonthEnd(n=0, offset=timedelta(days=1)), + { + datetime(2021, 3, 2): datetime(2021, 3, 31) + timedelta(days=1), + datetime(2021, 4, 1): datetime(2021, 4, 30) + timedelta(days=1), + }, + ), + ( + CBMonthEnd(n=1, holidays=["2021-03-31"], offset=timedelta(days=1)), + { + datetime(2021, 3, 2): datetime(2021, 3, 30) + timedelta(days=1), + }, + ), + ], + ) + def test_apply_with_extra_offset(self, case): + offset, cases = case + for base, expected in cases.items(): + assert_offset_equal(offset, base, expected)
- [x] closes #41356 #14869 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry ----------------- **Problem description**: _CustomBusinessMonth does not apply extra offset when initially rolled month begin `new` is already a business day. This happens because we currently use CustomBusinessDay.rollforward (rollback) to both 1) roll to a business day and 2) apply the extra offset. **Fix**: Separating the logic to 1) roll to a business day and 2) apply the extra offset.
https://api.github.com/repos/pandas-dev/pandas/pulls/41488
2021-05-15T15:20:04Z
2021-07-28T01:50:05Z
2021-07-28T01:50:05Z
2021-07-28T01:50:22Z
[ArrowStringArray] REF: _str_startswith/_str_endswith
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 219a8c7ec0b82..252bc215869ac 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -820,29 +820,26 @@ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex: bool = True): result[isna(result)] = bool(na) return result - def _str_startswith(self, pat, na=None): + def _str_startswith(self, pat: str, na=None): if pa_version_under4p0: return super()._str_startswith(pat, na) - result = pc.match_substring_regex(self._data, "^" + re.escape(pat)) - result = BooleanDtype().__from_arrow__(result) - if not isna(na): - result[isna(result)] = bool(na) - return result + pat = "^" + re.escape(pat) + return self._str_contains(pat, na=na, regex=True) - def _str_endswith(self, pat, na=None): + def _str_endswith(self, pat: str, na=None): if pa_version_under4p0: return super()._str_endswith(pat, na) - result = pc.match_substring_regex(self._data, re.escape(pat) + "$") - result = BooleanDtype().__from_arrow__(result) - if not isna(na): - result[isna(result)] = bool(na) - return result + pat = re.escape(pat) + "$" + return self._str_contains(pat, na=na, regex=True) def _str_match( self, pat: str, case: bool = True, flags: int = 0, na: Scalar = None ): + if pa_version_under4p0: + return super()._str_match(pat, case, flags, na) + if not pat.startswith("^"): pat = "^" + pat return self._str_contains(pat, case, flags, na, regex=True)
using pyarrow native functions for _str_startswith/_str_endswith #41222 were merged before _str_contains #41217 so we can de-duplication some logic. and also a change to _str_match for perf gain on object fallback ``` - 32.8±0.2ms 25.5±0.1ms 0.78 strings.Methods.time_match('arrow_string') ```
https://api.github.com/repos/pandas-dev/pandas/pulls/41487
2021-05-15T11:17:40Z
2021-05-17T15:08:21Z
2021-05-17T15:08:21Z
2021-05-17T15:53:18Z
Deprecate non-keyword arguments in drop
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 24cd41383e9d7..10a042373a8d1 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -693,6 +693,7 @@ Deprecations - Deprecated passing arguments as positional in :meth:`DataFrame.reset_index` (other than ``"level"``) and :meth:`Series.reset_index` (:issue:`41485`) - Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`,:issue:`33401`) - Deprecated passing arguments as positional in :meth:`DataFrame.where` and :meth:`Series.where` (other than ``"cond"`` and ``"other"``) (:issue:`41485`) +- Deprecated passing arguments as positional in :meth:`DataFrame.drop` (other than ``"labels"``) and :meth:`Series.drop` (:issue:`41485`) - .. _whatsnew_130.deprecations.nuisance_columns: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 75d2f4c591053..710aee6581dc2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4766,6 +4766,7 @@ def reindex(self, *args, **kwargs) -> DataFrame: kwargs.pop("labels", None) return super().reindex(**kwargs) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"]) def drop( self, labels=None, diff --git a/pandas/core/series.py b/pandas/core/series.py index 686e6966d8e24..88580f0427a34 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4522,6 +4522,7 @@ def set_axis(self, labels, axis: Axis = 0, inplace: bool = False): def reindex(self, index=None, **kwargs): return super().reindex(index=index, **kwargs) + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"]) def drop( self, labels=None, diff --git a/pandas/io/stata.py b/pandas/io/stata.py index f1747f94a7ea8..e4f3bcb89cf7e 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1761,7 +1761,9 @@ def _do_convert_missing(self, data: DataFrame, convert_missing: bool) -> DataFra if replacements: columns = data.columns replacement_df = DataFrame(replacements) - replaced = concat([data.drop(replacement_df.columns, 1), replacement_df], 1) + replaced = concat( + [data.drop(replacement_df.columns, axis=1), replacement_df], 1 + ) data = replaced[columns] return data diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 523e5209f3762..76e24a27e0854 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -89,7 +89,7 @@ def test_drop_names(self): with pytest.raises(KeyError, match=msg): df.drop(["g"]) with pytest.raises(KeyError, match=msg): - df.drop(["g"], 1) + df.drop(["g"], axis=1) # errors = 'ignore' dropped = df.drop(["g"], errors="ignore") @@ -123,11 +123,11 @@ def test_drop(self): with pytest.raises(KeyError, match=r"\[5\] not found in axis"): simple.drop(5) with pytest.raises(KeyError, match=r"\['C'\] not found in axis"): - simple.drop("C", 1) + simple.drop("C", axis=1) with pytest.raises(KeyError, match=r"\[5\] not found in axis"): simple.drop([1, 5]) with pytest.raises(KeyError, match=r"\['C'\] not found in axis"): - simple.drop(["A", "C"], 1) + simple.drop(["A", "C"], axis=1) # errors = 'ignore' tm.assert_frame_equal(simple.drop(5, errors="ignore"), simple) @@ -201,7 +201,7 @@ def test_drop_api_equivalence(self): res2 = df.drop(index="a") tm.assert_frame_equal(res1, res2) - res1 = df.drop("d", 1) + res1 = df.drop("d", axis=1) res2 = df.drop(columns="d") tm.assert_frame_equal(res1, res2) @@ -482,6 +482,18 @@ def test_drop_with_duplicate_columns2(self): result = df2.drop("C", axis=1) tm.assert_frame_equal(result, expected) + def test_drop_pos_args_deprecation(self): + # https://github.com/pandas-dev/pandas/issues/41485 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"In a future version of pandas all arguments of DataFrame\.drop " + r"except for the argument 'labels' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.drop("a", 1) + expected = DataFrame(index=[0, 1, 2]) + tm.assert_frame_equal(result, expected) + def test_drop_inplace_no_leftover_column_reference(self): # GH 13934 df = DataFrame({"a": [1, 2, 3]}) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 1949d03998512..b5092f83e1a9f 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -901,7 +901,7 @@ def test_pad_stable_sorting(fill_method): y = y[::-1] df = DataFrame({"x": x, "y": y}) - expected = df.drop("x", 1) + expected = df.drop("x", axis=1) result = getattr(df.groupby("x"), fill_method)() diff --git a/pandas/tests/series/methods/test_drop.py b/pandas/tests/series/methods/test_drop.py index 7ded8ac902d78..a566f8f62d72e 100644 --- a/pandas/tests/series/methods/test_drop.py +++ b/pandas/tests/series/methods/test_drop.py @@ -84,3 +84,16 @@ def test_drop_non_empty_list(data, index, drop_labels): ser = Series(data=data, index=index, dtype=dtype) with pytest.raises(KeyError, match="not found in axis"): ser.drop(drop_labels) + + +def test_drop_pos_args_deprecation(): + # https://github.com/pandas-dev/pandas/issues/41485 + ser = Series([1, 2, 3]) + msg = ( + r"In a future version of pandas all arguments of Series\.drop " + r"except for the argument 'labels' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.drop(1, 0) + expected = Series([1, 3], index=[0, 2]) + tm.assert_series_equal(result, expected)
- [ ] xref #41485 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/41486
2021-05-15T10:10:55Z
2021-05-27T12:07:18Z
2021-05-27T12:07:17Z
2021-05-27T12:26:11Z
TST/CLN: tests/strings/test_strings.py
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index 42d81154dea0f..f77a78b8c4c49 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -26,16 +26,16 @@ def assert_series_or_index_equal(left, right): def test_iter(): # GH3638 strs = "google", "wikimedia", "wikipedia", "wikitravel" - ds = Series(strs) + ser = Series(strs) with tm.assert_produces_warning(FutureWarning): - for s in ds.str: + for s in ser.str: # iter must yield a Series assert isinstance(s, Series) # indices of each yielded Series should be equal to the index of # the original Series - tm.assert_index_equal(s.index, ds.index) + tm.assert_index_equal(s.index, ser.index) for el in s: # each element of the series is either a basestring/str or nan @@ -48,12 +48,12 @@ def test_iter(): def test_iter_empty(): - ds = Series([], dtype=object) + ser = Series([], dtype=object) i, s = 100, 1 with tm.assert_produces_warning(FutureWarning): - for i, s in enumerate(ds.str): + for i, s in enumerate(ser.str): pass # nothing to iterate over so nothing defined values should remain @@ -63,18 +63,18 @@ def test_iter_empty(): def test_iter_single_element(): - ds = Series(["a"]) + ser = Series(["a"]) with tm.assert_produces_warning(FutureWarning): - for i, s in enumerate(ds.str): + for i, s in enumerate(ser.str): pass assert not i - tm.assert_series_equal(ds, s) + tm.assert_series_equal(ser, s) def test_iter_object_try_string(): - ds = Series( + ser = Series( [ slice(None, np.random.randint(10), np.random.randint(10, 20)) for _ in range(4) @@ -84,7 +84,7 @@ def test_iter_object_try_string(): i, s = 100, "h" with tm.assert_produces_warning(FutureWarning): - for i, s in enumerate(ds.str): + for i, s in enumerate(ser.str): pass assert i == 100 @@ -95,44 +95,41 @@ def test_iter_object_try_string(): def test_count(): - values = np.array(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=np.object_) + ser = Series(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=np.object_) + result = ser.str.count("f[o]+") + expected = Series([1, 2, np.nan, 4]) + tm.assert_series_equal(result, expected) - result = Series(values).str.count("f[o]+") - exp = Series([1, 2, np.nan, 4]) - assert isinstance(result, Series) - tm.assert_series_equal(result, exp) - # mixed - mixed = np.array( +def test_count_mixed_object(): + ser = Series( ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0], dtype=object, ) - rs = Series(mixed).str.count("a") - xp = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan]) - assert isinstance(rs, Series) - tm.assert_series_equal(rs, xp) + result = ser.str.count("a") + expected = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan]) + tm.assert_series_equal(result, expected) def test_repeat(): - values = Series(["a", "b", np.nan, "c", np.nan, "d"]) + ser = Series(["a", "b", np.nan, "c", np.nan, "d"]) - result = values.str.repeat(3) - exp = Series(["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"]) - tm.assert_series_equal(result, exp) + result = ser.str.repeat(3) + expected = Series(["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"]) + tm.assert_series_equal(result, expected) - result = values.str.repeat([1, 2, 3, 4, 5, 6]) - exp = Series(["a", "bb", np.nan, "cccc", np.nan, "dddddd"]) - tm.assert_series_equal(result, exp) + result = ser.str.repeat([1, 2, 3, 4, 5, 6]) + expected = Series(["a", "bb", np.nan, "cccc", np.nan, "dddddd"]) + tm.assert_series_equal(result, expected) - # mixed - mixed = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0]) - rs = Series(mixed).str.repeat(3) - xp = Series( +def test_repeat_mixed_object(): + ser = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0]) + result = ser.str.repeat(3) + expected = Series( ["aaa", np.nan, "bbb", np.nan, np.nan, "foofoofoo", np.nan, np.nan, np.nan] ) - assert isinstance(rs, Series) - tm.assert_series_equal(rs, xp) + tm.assert_series_equal(result, expected) def test_repeat_with_null(nullable_string_dtype): @@ -227,514 +224,494 @@ def test_empty_str_methods(any_string_dtype): def test_empty_str_methods_to_frame(): - empty = Series(dtype=str) - empty_df = DataFrame() - tm.assert_frame_equal(empty_df, empty.str.partition("a")) - tm.assert_frame_equal(empty_df, empty.str.rpartition("a")) + ser = Series(dtype=str) + expected = DataFrame() + + result = ser.str.partition("a") + tm.assert_frame_equal(result, expected) + + result = ser.str.rpartition("a") + tm.assert_frame_equal(result, expected) -def test_ismethods(any_string_dtype): +@pytest.mark.parametrize( + "method, expected", + [ + ("isalnum", [True, True, True, True, True, False, True, True, False, False]), + ("isalpha", [True, True, True, False, False, False, True, False, False, False]), + ( + "isdigit", + [False, False, False, True, False, False, False, True, False, False], + ), + ( + "isnumeric", + [False, False, False, True, False, False, False, True, False, False], + ), + ( + "isspace", + [False, False, False, False, False, False, False, False, False, True], + ), + ( + "islower", + [False, True, False, False, False, False, False, False, False, False], + ), + ( + "isupper", + [True, False, False, False, True, False, True, False, False, False], + ), + ( + "istitle", + [True, False, True, False, True, False, False, False, False, False], + ), + ], +) +def test_ismethods(method, expected, any_string_dtype): values = ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "] - str_s = Series(values, dtype=any_string_dtype) - alnum_e = [True, True, True, True, True, False, True, True, False, False] - alpha_e = [True, True, True, False, False, False, True, False, False, False] - digit_e = [False, False, False, True, False, False, False, True, False, False] - - # TODO: unused - num_e = [ # noqa - False, - False, - False, - True, - False, - False, - False, - True, - False, - False, - ] - - space_e = [False, False, False, False, False, False, False, False, False, True] - lower_e = [False, True, False, False, False, False, False, False, False, False] - upper_e = [True, False, False, False, True, False, True, False, False, False] - title_e = [True, False, True, False, True, False, False, False, False, False] - - dtype = "bool" if any_string_dtype == "object" else "boolean" - tm.assert_series_equal(str_s.str.isalnum(), Series(alnum_e, dtype=dtype)) - tm.assert_series_equal(str_s.str.isalpha(), Series(alpha_e, dtype=dtype)) - tm.assert_series_equal(str_s.str.isdigit(), Series(digit_e, dtype=dtype)) - tm.assert_series_equal(str_s.str.isspace(), Series(space_e, dtype=dtype)) - tm.assert_series_equal(str_s.str.islower(), Series(lower_e, dtype=dtype)) - tm.assert_series_equal(str_s.str.isupper(), Series(upper_e, dtype=dtype)) - tm.assert_series_equal(str_s.str.istitle(), Series(title_e, dtype=dtype)) - - assert str_s.str.isalnum().tolist() == [v.isalnum() for v in values] - assert str_s.str.isalpha().tolist() == [v.isalpha() for v in values] - assert str_s.str.isdigit().tolist() == [v.isdigit() for v in values] - assert str_s.str.isspace().tolist() == [v.isspace() for v in values] - assert str_s.str.islower().tolist() == [v.islower() for v in values] - assert str_s.str.isupper().tolist() == [v.isupper() for v in values] - assert str_s.str.istitle().tolist() == [v.istitle() for v in values] - - -def test_isnumeric(any_string_dtype): + ser = Series(values, dtype=any_string_dtype) + + expected_dtype = "bool" if any_string_dtype == "object" else "boolean" + expected = Series(expected, dtype=expected_dtype) + result = getattr(ser.str, method)() + tm.assert_series_equal(result, expected) + + # compare with standard library + expected = [getattr(v, method)() for v in values] + result = result.tolist() + assert result == expected + + +@pytest.mark.parametrize( + "method, expected", + [ + ("isnumeric", [False, True, True, False, True, True, False]), + ("isdecimal", [False, True, False, False, False, True, False]), + ], +) +def test_isnumeric_unicode(method, expected, any_string_dtype): # 0x00bc: ¼ VULGAR FRACTION ONE QUARTER # 0x2605: ★ not number # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY # 0xFF13: 3 Em 3 values = ["A", "3", "¼", "★", "፸", "3", "four"] - s = Series(values, dtype=any_string_dtype) - numeric_e = [False, True, True, False, True, True, False] - decimal_e = [False, True, False, False, False, True, False] - dtype = "bool" if any_string_dtype == "object" else "boolean" - tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e, dtype=dtype)) - tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e, dtype=dtype)) + ser = Series(values, dtype=any_string_dtype) + expected_dtype = "bool" if any_string_dtype == "object" else "boolean" + expected = Series(expected, dtype=expected_dtype) + result = getattr(ser.str, method)() + tm.assert_series_equal(result, expected) - unicodes = ["A", "3", "¼", "★", "፸", "3", "four"] - assert s.str.isnumeric().tolist() == [v.isnumeric() for v in unicodes] - assert s.str.isdecimal().tolist() == [v.isdecimal() for v in unicodes] + # compare with standard library + expected = [getattr(v, method)() for v in values] + result = result.tolist() + assert result == expected + +@pytest.mark.parametrize( + "method, expected", + [ + ("isnumeric", [False, np.nan, True, False, np.nan, True, False]), + ("isdecimal", [False, np.nan, False, False, np.nan, True, False]), + ], +) +def test_isnumeric_unicode_missing(method, expected, any_string_dtype): values = ["A", np.nan, "¼", "★", np.nan, "3", "four"] - s = Series(values, dtype=any_string_dtype) - numeric_e = [False, np.nan, True, False, np.nan, True, False] - decimal_e = [False, np.nan, False, False, np.nan, True, False] - dtype = "object" if any_string_dtype == "object" else "boolean" - tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e, dtype=dtype)) - tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e, dtype=dtype)) + ser = Series(values, dtype=any_string_dtype) + expected_dtype = "object" if any_string_dtype == "object" else "boolean" + expected = Series(expected, dtype=expected_dtype) + result = getattr(ser.str, method)() + tm.assert_series_equal(result, expected) -def test_join(): - values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"]) - result = values.str.split("_").str.join("_") - tm.assert_series_equal(values, result) +def test_spilt_join_roundtrip(): + ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"]) + result = ser.str.split("_").str.join("_") + tm.assert_series_equal(result, ser) - # mixed - mixed = Series( - [ - "a_b", - np.nan, - "asdf_cas_asdf", - True, - datetime.today(), - "foo", - None, - 1, - 2.0, - ] - ) - rs = Series(mixed).str.split("_").str.join("_") - xp = Series( - [ - "a_b", - np.nan, - "asdf_cas_asdf", - np.nan, - np.nan, - "foo", - np.nan, - np.nan, - np.nan, - ] +def test_spilt_join_roundtrip_mixed_object(): + ser = Series( + ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0] ) - - assert isinstance(rs, Series) - tm.assert_almost_equal(rs, xp) + result = ser.str.split("_").str.join("_") + expected = Series( + ["a_b", np.nan, "asdf_cas_asdf", np.nan, np.nan, "foo", np.nan, np.nan, np.nan] + ) + tm.assert_series_equal(result, expected) def test_len(any_string_dtype): - values = Series( + ser = Series( ["foo", "fooo", "fooooo", np.nan, "fooooooo", "foo\n", "あ"], dtype=any_string_dtype, ) - - result = values.str.len() + result = ser.str.len() expected_dtype = "float64" if any_string_dtype == "object" else "Int64" expected = Series([3, 4, 6, np.nan, 8, 4, 1], dtype=expected_dtype) tm.assert_series_equal(result, expected) def test_len_mixed(): - mixed = Series( - [ - "a_b", - np.nan, - "asdf_cas_asdf", - True, - datetime.today(), - "foo", - None, - 1, - 2.0, - ] + ser = Series( + ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0] ) + result = ser.str.len() + expected = Series([3, np.nan, 13, np.nan, np.nan, 3, np.nan, np.nan, np.nan]) + tm.assert_series_equal(result, expected) - rs = Series(mixed).str.len() - xp = Series([3, np.nan, 13, np.nan, np.nan, 3, np.nan, np.nan, np.nan]) - assert isinstance(rs, Series) - tm.assert_almost_equal(rs, xp) +def test_index(index_or_series): + if index_or_series is Series: + _check = tm.assert_series_equal + else: + _check = tm.assert_index_equal + obj = index_or_series(["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"]) -def test_index(): - def _check(result, expected): - if isinstance(result, Series): - tm.assert_series_equal(result, expected) - else: - tm.assert_index_equal(result, expected) + result = obj.str.index("EF") + _check(result, index_or_series([4, 3, 1, 0])) + expected = np.array([v.index("EF") for v in obj.values], dtype=np.int64) + tm.assert_numpy_array_equal(result.values, expected) - for klass in [Series, Index]: - s = klass(["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"]) + result = obj.str.rindex("EF") + _check(result, index_or_series([4, 5, 7, 4])) + expected = np.array([v.rindex("EF") for v in obj.values], dtype=np.int64) + tm.assert_numpy_array_equal(result.values, expected) - result = s.str.index("EF") - _check(result, klass([4, 3, 1, 0])) - expected = np.array([v.index("EF") for v in s.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + result = obj.str.index("EF", 3) + _check(result, index_or_series([4, 3, 7, 4])) + expected = np.array([v.index("EF", 3) for v in obj.values], dtype=np.int64) + tm.assert_numpy_array_equal(result.values, expected) - result = s.str.rindex("EF") - _check(result, klass([4, 5, 7, 4])) - expected = np.array([v.rindex("EF") for v in s.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + result = obj.str.rindex("EF", 3) + _check(result, index_or_series([4, 5, 7, 4])) + expected = np.array([v.rindex("EF", 3) for v in obj.values], dtype=np.int64) + tm.assert_numpy_array_equal(result.values, expected) - result = s.str.index("EF", 3) - _check(result, klass([4, 3, 7, 4])) - expected = np.array([v.index("EF", 3) for v in s.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + result = obj.str.index("E", 4, 8) + _check(result, index_or_series([4, 5, 7, 4])) + expected = np.array([v.index("E", 4, 8) for v in obj.values], dtype=np.int64) + tm.assert_numpy_array_equal(result.values, expected) - result = s.str.rindex("EF", 3) - _check(result, klass([4, 5, 7, 4])) - expected = np.array([v.rindex("EF", 3) for v in s.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) + result = obj.str.rindex("E", 0, 5) + _check(result, index_or_series([4, 3, 1, 4])) + expected = np.array([v.rindex("E", 0, 5) for v in obj.values], dtype=np.int64) + tm.assert_numpy_array_equal(result.values, expected) - result = s.str.index("E", 4, 8) - _check(result, klass([4, 5, 7, 4])) - expected = np.array([v.index("E", 4, 8) for v in s.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) - result = s.str.rindex("E", 0, 5) - _check(result, klass([4, 3, 1, 4])) - expected = np.array([v.rindex("E", 0, 5) for v in s.values], dtype=np.int64) - tm.assert_numpy_array_equal(result.values, expected) +def test_index_not_found(index_or_series): + obj = index_or_series(["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"]) + with pytest.raises(ValueError, match="substring not found"): + obj.str.index("DE") - with pytest.raises(ValueError, match="substring not found"): - result = s.str.index("DE") - msg = "expected a string object, not int" - with pytest.raises(TypeError, match=msg): - result = s.str.index(0) +def test_index_wrong_type_raises(index_or_series): + obj = index_or_series([], dtype=object) + msg = "expected a string object, not int" - with pytest.raises(TypeError, match=msg): - result = s.str.rindex(0) + with pytest.raises(TypeError, match=msg): + obj.str.index(0) - # test with nan - s = Series(["abcb", "ab", "bcbe", np.nan]) - result = s.str.index("b") - tm.assert_series_equal(result, Series([1, 1, 0, np.nan])) - result = s.str.rindex("b") - tm.assert_series_equal(result, Series([3, 1, 2, np.nan])) + with pytest.raises(TypeError, match=msg): + obj.str.rindex(0) -def test_pipe_failures(): - # #2119 - s = Series(["A|B|C"]) +def test_index_missing(): + ser = Series(["abcb", "ab", "bcbe", np.nan]) - result = s.str.split("|") - exp = Series([["A", "B", "C"]]) + result = ser.str.index("b") + expected = Series([1, 1, 0, np.nan]) + tm.assert_series_equal(result, expected) - tm.assert_series_equal(result, exp) + result = ser.str.rindex("b") + expected = Series([3, 1, 2, np.nan]) + tm.assert_series_equal(result, expected) - result = s.str.replace("|", " ", regex=False) - exp = Series(["A B C"]) - tm.assert_series_equal(result, exp) +def test_pipe_failures(): + # #2119 + ser = Series(["A|B|C"]) + + result = ser.str.split("|") + expected = Series([["A", "B", "C"]]) + tm.assert_series_equal(result, expected) + + result = ser.str.replace("|", " ", regex=False) + expected = Series(["A B C"]) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "start, stop, step, expected", [ - (2, 5, None, Series(["foo", "bar", np.nan, "baz"])), - (0, 3, -1, Series(["", "", np.nan, ""])), - (None, None, -1, Series(["owtoofaa", "owtrabaa", np.nan, "xuqzabaa"])), - (3, 10, 2, Series(["oto", "ato", np.nan, "aqx"])), - (3, 0, -1, Series(["ofa", "aba", np.nan, "aba"])), + (2, 5, None, ["foo", "bar", np.nan, "baz"]), + (0, 3, -1, ["", "", np.nan, ""]), + (None, None, -1, ["owtoofaa", "owtrabaa", np.nan, "xuqzabaa"]), + (3, 10, 2, ["oto", "ato", np.nan, "aqx"]), + (3, 0, -1, ["ofa", "aba", np.nan, "aba"]), ], ) def test_slice(start, stop, step, expected): - values = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"]) - result = values.str.slice(start, stop, step) + ser = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"]) + result = ser.str.slice(start, stop, step) + expected = Series(expected) tm.assert_series_equal(result, expected) - # mixed - mixed = Series( - ["aafootwo", np.nan, "aabartwo", True, datetime.today(), None, 1, 2.0] - ) - - rs = Series(mixed).str.slice(2, 5) - xp = Series(["foo", np.nan, "bar", np.nan, np.nan, np.nan, np.nan, np.nan]) - - assert isinstance(rs, Series) - tm.assert_almost_equal(rs, xp) - rs = Series(mixed).str.slice(2, 5, -1) - xp = Series(["oof", np.nan, "rab", np.nan, np.nan, np.nan, np.nan, np.nan]) +@pytest.mark.parametrize( + "start, stop, step, expected", + [ + (2, 5, None, ["foo", np.nan, "bar", np.nan, np.nan, np.nan, np.nan, np.nan]), + (4, 1, -1, ["oof", np.nan, "rab", np.nan, np.nan, np.nan, np.nan, np.nan]), + ], +) +def test_slice_mixed_object(start, stop, step, expected): + ser = Series(["aafootwo", np.nan, "aabartwo", True, datetime.today(), None, 1, 2.0]) + result = ser.str.slice(start, stop, step) + expected = Series(expected) + tm.assert_series_equal(result, expected) def test_slice_replace(): - values = Series(["short", "a bit longer", "evenlongerthanthat", "", np.nan]) + ser = Series(["short", "a bit longer", "evenlongerthanthat", "", np.nan]) - exp = Series(["shrt", "a it longer", "evnlongerthanthat", "", np.nan]) - result = values.str.slice_replace(2, 3) - tm.assert_series_equal(result, exp) + expected = Series(["shrt", "a it longer", "evnlongerthanthat", "", np.nan]) + result = ser.str.slice_replace(2, 3) + tm.assert_series_equal(result, expected) - exp = Series(["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]) - result = values.str.slice_replace(2, 3, "z") - tm.assert_series_equal(result, exp) + expected = Series(["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]) + result = ser.str.slice_replace(2, 3, "z") + tm.assert_series_equal(result, expected) - exp = Series(["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]) - result = values.str.slice_replace(2, 2, "z") - tm.assert_series_equal(result, exp) + expected = Series(["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]) + result = ser.str.slice_replace(2, 2, "z") + tm.assert_series_equal(result, expected) - exp = Series(["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]) - result = values.str.slice_replace(2, 1, "z") - tm.assert_series_equal(result, exp) + expected = Series(["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]) + result = ser.str.slice_replace(2, 1, "z") + tm.assert_series_equal(result, expected) - exp = Series(["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]) - result = values.str.slice_replace(-1, None, "z") - tm.assert_series_equal(result, exp) + expected = Series(["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]) + result = ser.str.slice_replace(-1, None, "z") + tm.assert_series_equal(result, expected) - exp = Series(["zrt", "zer", "zat", "z", np.nan]) - result = values.str.slice_replace(None, -2, "z") - tm.assert_series_equal(result, exp) + expected = Series(["zrt", "zer", "zat", "z", np.nan]) + result = ser.str.slice_replace(None, -2, "z") + tm.assert_series_equal(result, expected) - exp = Series(["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]) - result = values.str.slice_replace(6, 8, "z") - tm.assert_series_equal(result, exp) + expected = Series(["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]) + result = ser.str.slice_replace(6, 8, "z") + tm.assert_series_equal(result, expected) - exp = Series(["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]) - result = values.str.slice_replace(-10, 3, "z") - tm.assert_series_equal(result, exp) + expected = Series(["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]) + result = ser.str.slice_replace(-10, 3, "z") + tm.assert_series_equal(result, expected) def test_strip_lstrip_rstrip(any_string_dtype): - values = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype) - - result = values.str.strip() - exp = Series(["aa", "bb", np.nan, "cc"], dtype=any_string_dtype) - tm.assert_series_equal(result, exp) - - result = values.str.lstrip() - exp = Series(["aa ", "bb \n", np.nan, "cc "], dtype=any_string_dtype) - tm.assert_series_equal(result, exp) - - result = values.str.rstrip() - exp = Series([" aa", " bb", np.nan, "cc"], dtype=any_string_dtype) - tm.assert_series_equal(result, exp) + ser = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype) + result = ser.str.strip() + expected = Series(["aa", "bb", np.nan, "cc"], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) -def test_strip_lstrip_rstrip_mixed(): - # mixed - mixed = Series([" aa ", np.nan, " bb \t\n", True, datetime.today(), None, 1, 2.0]) + result = ser.str.lstrip() + expected = Series(["aa ", "bb \n", np.nan, "cc "], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) - rs = Series(mixed).str.strip() - xp = Series(["aa", np.nan, "bb", np.nan, np.nan, np.nan, np.nan, np.nan]) + result = ser.str.rstrip() + expected = Series([" aa", " bb", np.nan, "cc"], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) - assert isinstance(rs, Series) - tm.assert_almost_equal(rs, xp) - rs = Series(mixed).str.lstrip() - xp = Series(["aa ", np.nan, "bb \t\n", np.nan, np.nan, np.nan, np.nan, np.nan]) +def test_strip_lstrip_rstrip_mixed_object(): + ser = Series([" aa ", np.nan, " bb \t\n", True, datetime.today(), None, 1, 2.0]) - assert isinstance(rs, Series) - tm.assert_almost_equal(rs, xp) + result = ser.str.strip() + expected = Series(["aa", np.nan, "bb", np.nan, np.nan, np.nan, np.nan, np.nan]) + tm.assert_series_equal(result, expected) - rs = Series(mixed).str.rstrip() - xp = Series([" aa", np.nan, " bb", np.nan, np.nan, np.nan, np.nan, np.nan]) + result = ser.str.lstrip() + expected = Series( + ["aa ", np.nan, "bb \t\n", np.nan, np.nan, np.nan, np.nan, np.nan] + ) + tm.assert_series_equal(result, expected) - assert isinstance(rs, Series) - tm.assert_almost_equal(rs, xp) + result = ser.str.rstrip() + expected = Series([" aa", np.nan, " bb", np.nan, np.nan, np.nan, np.nan, np.nan]) + tm.assert_series_equal(result, expected) def test_strip_lstrip_rstrip_args(any_string_dtype): - values = Series(["xxABCxx", "xx BNSD", "LDFJH xx"], dtype=any_string_dtype) + ser = Series(["xxABCxx", "xx BNSD", "LDFJH xx"], dtype=any_string_dtype) - rs = values.str.strip("x") - xp = Series(["ABC", " BNSD", "LDFJH "], dtype=any_string_dtype) - tm.assert_series_equal(rs, xp) + result = ser.str.strip("x") + expected = Series(["ABC", " BNSD", "LDFJH "], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) - rs = values.str.lstrip("x") - xp = Series(["ABCxx", " BNSD", "LDFJH xx"], dtype=any_string_dtype) - tm.assert_series_equal(rs, xp) + result = ser.str.lstrip("x") + expected = Series(["ABCxx", " BNSD", "LDFJH xx"], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) - rs = values.str.rstrip("x") - xp = Series(["xxABC", "xx BNSD", "LDFJH "], dtype=any_string_dtype) - tm.assert_series_equal(rs, xp) + result = ser.str.rstrip("x") + expected = Series(["xxABC", "xx BNSD", "LDFJH "], dtype=any_string_dtype) + tm.assert_series_equal(result, expected) def test_string_slice_get_syntax(): - s = Series( - [ - "YYY", - "B", - "C", - "YYYYYYbYYY", - "BYYYcYYY", - np.nan, - "CYYYBYYY", - "dog", - "cYYYt", - ] + ser = Series( + ["YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", np.nan, "CYYYBYYY", "dog", "cYYYt"] ) - result = s.str[0] - expected = s.str.get(0) + result = ser.str[0] + expected = ser.str.get(0) tm.assert_series_equal(result, expected) - result = s.str[:3] - expected = s.str.slice(stop=3) + result = ser.str[:3] + expected = ser.str.slice(stop=3) tm.assert_series_equal(result, expected) - result = s.str[2::-1] - expected = s.str.slice(start=2, step=-1) + result = ser.str[2::-1] + expected = ser.str.slice(start=2, step=-1) tm.assert_series_equal(result, expected) def test_string_slice_out_of_bounds(): - s = Series([(1, 2), (1,), (3, 4, 5)]) - - result = s.str[1] + ser = Series([(1, 2), (1,), (3, 4, 5)]) + result = ser.str[1] expected = Series([2, np.nan, 4]) - tm.assert_series_equal(result, expected) - s = Series(["foo", "b", "ba"]) - result = s.str[1] + ser = Series(["foo", "b", "ba"]) + result = ser.str[1] expected = Series(["o", np.nan, "a"]) tm.assert_series_equal(result, expected) def test_encode_decode(): - base = Series(["a", "b", "a\xe4"]) - series = base.str.encode("utf-8") - - f = lambda x: x.decode("utf-8") - result = series.str.decode("utf-8") - exp = series.map(f) - - tm.assert_series_equal(result, exp) + ser = Series(["a", "b", "a\xe4"]).str.encode("utf-8") + result = ser.str.decode("utf-8") + expected = ser.map(lambda x: x.decode("utf-8")) + tm.assert_series_equal(result, expected) -def test_encode_decode_errors(): - encodeBase = Series(["a", "b", "a\x9d"]) +def test_encode_errors_kwarg(): + ser = Series(["a", "b", "a\x9d"]) msg = ( r"'charmap' codec can't encode character '\\x9d' in position 1: " "character maps to <undefined>" ) with pytest.raises(UnicodeEncodeError, match=msg): - encodeBase.str.encode("cp1252") + ser.str.encode("cp1252") + + result = ser.str.encode("cp1252", "ignore") + expected = ser.map(lambda x: x.encode("cp1252", "ignore")) + tm.assert_series_equal(result, expected) - f = lambda x: x.encode("cp1252", "ignore") - result = encodeBase.str.encode("cp1252", "ignore") - exp = encodeBase.map(f) - tm.assert_series_equal(result, exp) - decodeBase = Series([b"a", b"b", b"a\x9d"]) +def test_decode_errors_kwarg(): + ser = Series([b"a", b"b", b"a\x9d"]) msg = ( "'charmap' codec can't decode byte 0x9d in position 1: " "character maps to <undefined>" ) with pytest.raises(UnicodeDecodeError, match=msg): - decodeBase.str.decode("cp1252") - - f = lambda x: x.decode("cp1252", "ignore") - result = decodeBase.str.decode("cp1252", "ignore") - exp = decodeBase.map(f) + ser.str.decode("cp1252") - tm.assert_series_equal(result, exp) - - -def test_normalize(): - values = ["ABC", "ABC", "123", np.nan, "アイエ"] - s = Series(values, index=["a", "b", "c", "d", "e"]) - - normed = ["ABC", "ABC", "123", np.nan, "アイエ"] - expected = Series(normed, index=["a", "b", "c", "d", "e"]) - - result = s.str.normalize("NFKC") + result = ser.str.decode("cp1252", "ignore") + expected = ser.map(lambda x: x.decode("cp1252", "ignore")) tm.assert_series_equal(result, expected) - expected = Series( - ["ABC", "ABC", "123", np.nan, "アイエ"], index=["a", "b", "c", "d", "e"] - ) - result = s.str.normalize("NFC") +@pytest.mark.parametrize( + "form, expected", + [ + ("NFKC", ["ABC", "ABC", "123", np.nan, "アイエ"]), + ("NFC", ["ABC", "ABC", "123", np.nan, "アイエ"]), + ], +) +def test_normalize(form, expected): + ser = Series(["ABC", "ABC", "123", np.nan, "アイエ"], index=["a", "b", "c", "d", "e"]) + expected = Series(expected, index=["a", "b", "c", "d", "e"]) + result = ser.str.normalize(form) tm.assert_series_equal(result, expected) + +def test_normalize_bad_arg_raises(): + ser = Series(["ABC", "ABC", "123", np.nan, "アイエ"], index=["a", "b", "c", "d", "e"]) with pytest.raises(ValueError, match="invalid normalization form"): - s.str.normalize("xxx") + ser.str.normalize("xxx") + - s = Index(["ABC", "123", "アイエ"]) +def test_normalize_index(): + idx = Index(["ABC", "123", "アイエ"]) expected = Index(["ABC", "123", "アイエ"]) - result = s.str.normalize("NFKC") + result = idx.str.normalize("NFKC") tm.assert_index_equal(result, expected) -def test_index_str_accessor_visibility(): - from pandas.core.strings import StringMethods - - cases = [ +@pytest.mark.parametrize( + "values,inferred_type", + [ (["a", "b"], "string"), (["a", "b", 1], "mixed-integer"), (["a", "b", 1.3], "mixed"), (["a", "b", 1.3, 1], "mixed-integer"), (["aa", datetime(2011, 1, 1)], "mixed"), - ] - for values, tp in cases: - idx = Index(values) - assert isinstance(Series(values).str, StringMethods) - assert isinstance(idx.str, StringMethods) - assert idx.inferred_type == tp - - for values, tp in cases: - idx = Index(values) - assert isinstance(Series(values).str, StringMethods) - assert isinstance(idx.str, StringMethods) - assert idx.inferred_type == tp - - cases = [ + ], +) +def test_index_str_accessor_visibility(values, inferred_type, index_or_series): + from pandas.core.strings import StringMethods + + obj = index_or_series(values) + if index_or_series is Index: + assert obj.inferred_type == inferred_type + + assert isinstance(obj.str, StringMethods) + + +@pytest.mark.parametrize( + "values,inferred_type", + [ ([1, np.nan], "floating"), ([datetime(2011, 1, 1)], "datetime64"), ([timedelta(1)], "timedelta64"), - ] - for values, tp in cases: - idx = Index(values) - message = "Can only use .str accessor with string values" - with pytest.raises(AttributeError, match=message): - Series(values).str - with pytest.raises(AttributeError, match=message): - idx.str - assert idx.inferred_type == tp + ], +) +def test_index_str_accessor_non_string_values_raises( + values, inferred_type, index_or_series +): + obj = index_or_series(values) + if index_or_series is Index: + assert obj.inferred_type == inferred_type + msg = "Can only use .str accessor with string values" + with pytest.raises(AttributeError, match=msg): + obj.str + + +def test_index_str_accessor_multiindex_raises(): # MultiIndex has mixed dtype, but not allow to use accessor idx = MultiIndex.from_tuples([("a", "b"), ("a", "b")]) assert idx.inferred_type == "mixed" - message = "Can only use .str accessor with Index, not MultiIndex" - with pytest.raises(AttributeError, match=message): + + msg = "Can only use .str accessor with Index, not MultiIndex" + with pytest.raises(AttributeError, match=msg): idx.str def test_str_accessor_no_new_attributes(): # https://github.com/pandas-dev/pandas/issues/10673 - s = Series(list("aabbcde")) + ser = Series(list("aabbcde")) with pytest.raises(AttributeError, match="You cannot add any new attribute"): - s.str.xlabel = "a" + ser.str.xlabel = "a" -def test_method_on_bytes(): +def test_cat_on_bytes_raises(): lhs = Series(np.array(list("abc"), "S1").astype(object)) rhs = Series(np.array(list("def"), "S1").astype(object)) - with pytest.raises(TypeError, match="Cannot use .str.cat with values of.*"): + msg = "Cannot use .str.cat with values of inferred dtype 'bytes'" + with pytest.raises(TypeError, match=msg): lhs.str.cat(rhs)
variable and test renaming, test splitting and parametrization of existing as a pre-cursor to further parametrization on dtype and moving.
https://api.github.com/repos/pandas-dev/pandas/pulls/41484
2021-05-15T10:05:46Z
2021-05-17T18:26:37Z
2021-05-17T18:26:37Z
2021-05-17T18:29:03Z
TST: Add tests for old issues
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index a724f3d9f2a7d..fcccd0d846d0f 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1519,3 +1519,11 @@ def test_apply_np_reducer(float_frame, op, how): getattr(np, op)(float_frame, axis=0, **kwargs), index=float_frame.columns ) tm.assert_series_equal(result, expected) + + +def test_apply_getitem_axis_1(): + # GH 13427 + df = DataFrame({"a": [0, 1, 2], "b": [1, 2, 3]}) + result = df[["a", "a"]].apply(lambda x: x[0] + x[1], axis=1) + expected = Series([0, 2, 4]) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 5d2aabd372fd1..523e5209f3762 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -481,3 +481,12 @@ def test_drop_with_duplicate_columns2(self): df2 = df.take([2, 0, 1, 2, 1], axis=1) result = df2.drop("C", axis=1) tm.assert_frame_equal(result, expected) + + def test_drop_inplace_no_leftover_column_reference(self): + # GH 13934 + df = DataFrame({"a": [1, 2, 3]}) + a = df.a + df.drop(["a"], axis=1, inplace=True) + tm.assert_index_equal(df.columns, Index([], dtype="object")) + a -= a.mean() + tm.assert_index_equal(df.columns, Index([], dtype="object")) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 2df59923221ec..0ca523db60889 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -1638,3 +1638,12 @@ def test_groupy_regular_arithmetic_equivalent(meth): result = getattr(df.groupby(level=0), meth)(numeric_only=False) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("ts_value", [Timestamp("2000-01-01"), pd.NaT]) +def test_frame_mixed_numeric_object_with_timestamp(ts_value): + # GH 13912 + df = DataFrame({"a": [1], "b": [1.1], "c": ["foo"], "d": [ts_value]}) + result = df.sum() + expected = Series([1, 1.1, "foo"], index=list("abc")) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index 365d8abcb6bac..6348014ca72d2 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -2018,3 +2018,18 @@ def test_stack_nan_level(self): ), ) tm.assert_frame_equal(result, expected) + + def test_unstack_categorical_columns(self): + # GH 14018 + idx = MultiIndex.from_product([["A"], [0, 1]]) + df = DataFrame({"cat": pd.Categorical(["a", "b"])}, index=idx) + result = df.unstack() + expected = DataFrame( + { + 0: pd.Categorical(["a"], categories=["a", "b"]), + 1: pd.Categorical(["b"], categories=["a", "b"]), + }, + index=["A"], + ) + expected.columns = MultiIndex.from_tuples([("cat", 0), ("cat", 1)]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py index 2bc9b2cd1a1bd..7a4ba52cdfdd5 100644 --- a/pandas/tests/indexes/base_class/test_setops.py +++ b/pandas/tests/indexes/base_class/test_setops.py @@ -247,3 +247,15 @@ def test_union_name_preservation( else: expected = Index(vals, name=expected_name) tm.equalContents(union, expected) + + @pytest.mark.parametrize( + "diff_type, expected", + [["difference", [1, "B"]], ["symmetric_difference", [1, 2, "B", "C"]]], + ) + def test_difference_object_type(self, diff_type, expected): + # GH 13432 + idx1 = Index([0, 1, "A", "B"]) + idx2 = Index([0, 2, "A", "C"]) + result = getattr(idx1, diff_type)(idx2) + expected = Index(expected) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index c87efdbd35fa4..0c6f2faf77f00 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -788,3 +788,16 @@ def test_mi_columns_loc_list_label_order(): columns=MultiIndex.from_tuples([("B", 1), ("B", 2), ("A", 1), ("A", 2)]), ) tm.assert_frame_equal(result, expected) + + +def test_mi_partial_indexing_list_raises(): + # GH 13501 + frame = DataFrame( + np.arange(12).reshape((4, 3)), + index=[["a", "a", "b", "b"], [1, 2, 1, 2]], + columns=[["Ohio", "Ohio", "Colorado"], ["Green", "Red", "Green"]], + ) + frame.index.names = ["key1", "key2"] + frame.columns.names = ["state", "color"] + with pytest.raises(KeyError, match="\\[2\\] not in index"): + frame.loc[["b", 2], "Colorado"] diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index f450625629c71..a38c652953fab 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -499,3 +499,10 @@ def test_iloc_setitem_chained_assignment(self): df["bb"].iloc[0] = 0.15 assert df["bb"].iloc[0] == 0.15 + + def test_getitem_loc_assignment_slice_state(self): + # GH 13569 + df = DataFrame({"a": [10, 20, 30]}) + df["a"].loc[4] = 40 + tm.assert_frame_equal(df, DataFrame({"a": [10, 20, 30]})) + tm.assert_series_equal(df["a"], Series([10, 20, 30], name="a")) diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index c918832df7aee..7519b24a48566 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -2,6 +2,7 @@ Tests for the pandas.io.common functionalities """ import codecs +import errno from functools import partial from io import ( BytesIO, @@ -519,3 +520,10 @@ def test_bad_encdoing_errors(): with tm.ensure_clean() as path: with pytest.raises(ValueError, match="Invalid value for `encoding_errors`"): icom.get_handle(path, "w", errors="bad") + + +def test_errno_attribute(): + # GH 13872 + with pytest.raises(FileNotFoundError, match="\\[Errno 2\\]") as err: + pd.read_csv("doesnt_exist") + assert err.errno == errno.ENOENT
- [x] closes #13427 - [x] closes #13432 - [x] closes #13501 - [x] closes #13569 - [x] closes #13872 - [x] closes #13912 - [x] closes #13934 - [x] closes #14018 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/41482
2021-05-15T05:07:17Z
2021-05-17T15:17:30Z
2021-05-17T15:17:29Z
2021-05-17T16:17:57Z
Backport PR #27814 on branch 0.25.x (BUG: Series.rename raises error on values accepted by Series construc…)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 680d69a9862cd..b307fae4fbdc1 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -108,6 +108,7 @@ Other ^^^^^ - Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) +- Bug in :meth:`Series.rename` when using a custom type indexer. Now any value that isn't callable or dict-like is treated as a scalar. (:issue:`27814`) .. _whatsnew_0.251.contributors: diff --git a/pandas/core/series.py b/pandas/core/series.py index 42afb3537c5d8..9f31e185fe41a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4207,12 +4207,10 @@ def rename(self, index=None, **kwargs): """ kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace") - non_mapping = is_scalar(index) or ( - is_list_like(index) and not is_dict_like(index) - ) - if non_mapping: + if callable(index) or is_dict_like(index): + return super().rename(index=index, **kwargs) + else: return self._set_name(index, inplace=kwargs.get("inplace")) - return super().rename(index=index, **kwargs) @Substitution(**_shared_doc_kwargs) @Appender(generic.NDFrame.reindex.__doc__) diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 11add8d61deeb..eeb95bc52bf78 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -267,6 +267,25 @@ def test_rename_axis_none(self, kwargs): expected = Series([1, 2, 3], index=expected_index) tm.assert_series_equal(result, expected) + def test_rename_with_custom_indexer(self): + # GH 27814 + class MyIndexer: + pass + + ix = MyIndexer() + s = Series([1, 2, 3]).rename(ix) + assert s.name is ix + + def test_rename_with_custom_indexer_inplace(self): + # GH 27814 + class MyIndexer: + pass + + ix = MyIndexer() + s = Series([1, 2, 3]) + s.rename(ix, inplace=True) + assert s.name is ix + def test_set_axis_inplace_axes(self, axis_series): # GH14636 ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")
Backport PR #27814: BUG: Series.rename raises error on values accepted by Series construc…
https://api.github.com/repos/pandas-dev/pandas/pulls/28087
2019-08-22T13:07:58Z
2019-08-22T13:47:33Z
2019-08-22T13:47:33Z
2019-08-22T13:47:33Z
Backport PR #27827 on branch 0.25.x (BUG: Fixed groupby quantile for listlike q)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index a7b97b41fb776..050e1939875dc 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -122,6 +122,7 @@ Plotting Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ +- Fixed regression in :meth:`pands.core.groupby.DataFrameGroupBy.quantile` raising when multiple quantiles are given (:issue:`27526`) - Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.transform` where applying a timezone conversion lambda function would drop timezone information (:issue:`27496`) - Bug in :meth:`pandas.core.groupby.GroupBy.nth` where ``observed=False`` was being ignored for Categorical groupers (:issue:`26385`) - Bug in windowing over read-only arrays (:issue:`27766`) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index b852513e454a2..41b5e0d803659 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1872,6 +1872,7 @@ def quantile(self, q=0.5, interpolation="linear"): a 2.0 b 3.0 """ + from pandas import concat def pre_processor(vals: np.ndarray) -> Tuple[np.ndarray, Optional[Type]]: if is_object_dtype(vals): @@ -1899,18 +1900,57 @@ def post_processor(vals: np.ndarray, inference: Optional[Type]) -> np.ndarray: return vals - return self._get_cythonized_result( - "group_quantile", - self.grouper, - aggregate=True, - needs_values=True, - needs_mask=True, - cython_dtype=np.float64, - pre_processing=pre_processor, - post_processing=post_processor, - q=q, - interpolation=interpolation, - ) + if is_scalar(q): + return self._get_cythonized_result( + "group_quantile", + self.grouper, + aggregate=True, + needs_values=True, + needs_mask=True, + cython_dtype=np.float64, + pre_processing=pre_processor, + post_processing=post_processor, + q=q, + interpolation=interpolation, + ) + else: + results = [ + self._get_cythonized_result( + "group_quantile", + self.grouper, + aggregate=True, + needs_values=True, + needs_mask=True, + cython_dtype=np.float64, + pre_processing=pre_processor, + post_processing=post_processor, + q=qi, + interpolation=interpolation, + ) + for qi in q + ] + result = concat(results, axis=0, keys=q) + # fix levels to place quantiles on the inside + # TODO(GH-10710): Ideally, we could write this as + # >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :] + # but this hits https://github.com/pandas-dev/pandas/issues/10710 + # which doesn't reorder the list-like `q` on the inner level. + order = np.roll(list(range(result.index.nlevels)), -1) + result = result.reorder_levels(order) + result = result.reindex(q, level=-1) + + # fix order. + hi = len(q) * self.ngroups + arr = np.arange(0, hi, self.ngroups) + arrays = [] + + for i in range(self.ngroups): + arr = arr + i + arrays.append(arr) + + indices = np.concatenate(arrays) + assert len(indices) == len(result) + return result.take(indices) @Substitution(name="groupby") def ngroup(self, ascending=True): diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index efc3142b25b82..397c6653ce967 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1238,6 +1238,57 @@ def test_quantile(interpolation, a_vals, b_vals, q): tm.assert_frame_equal(result, expected) +def test_quantile_array(): + # https://github.com/pandas-dev/pandas/issues/27526 + df = pd.DataFrame({"A": [0, 1, 2, 3, 4]}) + result = df.groupby([0, 0, 1, 1, 1]).quantile([0.25]) + + index = pd.MultiIndex.from_product([[0, 1], [0.25]]) + expected = pd.DataFrame({"A": [0.25, 2.50]}, index=index) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]}) + index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]]) + + result = df.groupby([0, 0, 1, 1]).quantile([0.25, 0.75]) + expected = pd.DataFrame( + {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array_no_sort(): + df = pd.DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]}) + result = df.groupby([1, 0, 1], sort=False).quantile([0.25, 0.5, 0.75]) + expected = pd.DataFrame( + {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]}, + index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]), + ) + tm.assert_frame_equal(result, expected) + + result = df.groupby([1, 0, 1], sort=False).quantile([0.75, 0.25]) + expected = pd.DataFrame( + {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]}, + index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array_multiple_levels(): + df = pd.DataFrame( + {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]} + ) + result = df.groupby(["c", "d"]).quantile([0.25, 0.75]) + index = pd.MultiIndex.from_tuples( + [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)], + names=["c", "d", None], + ) + expected = pd.DataFrame( + {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index + ) + tm.assert_frame_equal(result, expected) + + def test_quantile_raises(): df = pd.DataFrame( [["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"]
Backport PR #27827: BUG: Fixed groupby quantile for listlike q
https://api.github.com/repos/pandas-dev/pandas/pulls/28085
2019-08-22T11:29:00Z
2019-08-22T12:17:29Z
2019-08-22T12:17:28Z
2019-08-23T13:30:32Z
DOC: Remove alias for numpy.random.randn from the docs
diff --git a/doc/source/conf.py b/doc/source/conf.py index 3ebc5d8b6333b..a4b7d97c2cf5e 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -315,7 +315,6 @@ import numpy as np import pandas as pd - randn = np.random.randn np.random.seed(123456) np.set_printoptions(precision=4, suppress=True) pd.options.display.max_rows = 15 diff --git a/doc/source/whatsnew/v0.10.0.rst b/doc/source/whatsnew/v0.10.0.rst index 59ea6b9776232..2e0442364b2f3 100644 --- a/doc/source/whatsnew/v0.10.0.rst +++ b/doc/source/whatsnew/v0.10.0.rst @@ -498,7 +498,7 @@ Here is a taste of what to expect. .. code-block:: ipython - In [58]: p4d = Panel4D(randn(2, 2, 5, 4), + In [58]: p4d = Panel4D(np.random.randn(2, 2, 5, 4), ....: labels=['Label1','Label2'], ....: items=['Item1', 'Item2'], ....: major_axis=date_range('1/1/2000', periods=5),
Based on this comment: https://github.com/pandas-dev/pandas/issues/28038#issuecomment-523439376 Supersedes #28068
https://api.github.com/repos/pandas-dev/pandas/pulls/28082
2019-08-22T03:41:27Z
2019-08-23T09:01:29Z
2019-08-23T09:01:29Z
2019-08-23T09:01:35Z
REF: separate bloated test
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 7e03b9544ee72..80661cc214fd6 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -791,28 +791,33 @@ def wrapper(self, other): self, other = _align_method_SERIES(self, other, align_asobject=True) res_name = get_op_result_name(self, other) + # TODO: shouldn't we be applying finalize whenever + # not isinstance(other, ABCSeries)? + finalizer = ( + lambda x: x.__finalize__(self) + if not isinstance(other, (ABCSeries, ABCIndexClass)) + else x + ) + if isinstance(other, ABCDataFrame): # Defer to DataFrame implementation; fail early return NotImplemented elif isinstance(other, (ABCSeries, ABCIndexClass)): is_other_int_dtype = is_integer_dtype(other.dtype) - other = fill_int(other) if is_other_int_dtype else fill_bool(other) - - ovalues = other.values - finalizer = lambda x: x + other = other if is_other_int_dtype else fill_bool(other) else: # scalars, list, tuple, np.array - is_other_int_dtype = is_integer_dtype(np.asarray(other)) + is_other_int_dtype = is_integer_dtype(np.asarray(other).dtype) if is_list_like(other) and not isinstance(other, np.ndarray): # TODO: Can we do this before the is_integer_dtype check? # could the is_integer_dtype check be checking the wrong # thing? e.g. other = [[0, 1], [2, 3], [4, 5]]? other = construct_1d_object_array_from_listlike(other) - ovalues = other - finalizer = lambda x: x.__finalize__(self) + # TODO: use extract_array once we handle EA correctly, see GH#27959 + ovalues = lib.values_from_object(other) # For int vs int `^`, `|`, `&` are bitwise operators and return # integer dtypes. Otherwise these are boolean ops diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index 062c07cb6242a..aa44760dcd918 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -36,22 +36,14 @@ def test_bool_operators_with_nas(self, bool_op): expected[mask] = False assert_series_equal(result, expected) - def test_operators_bitwise(self): + def test_logical_operators_bool_dtype_with_empty(self): # GH#9016: support bitwise op for integer types index = list("bca") s_tft = Series([True, False, True], index=index) s_fff = Series([False, False, False], index=index) - s_tff = Series([True, False, False], index=index) s_empty = Series([]) - # TODO: unused - # s_0101 = Series([0, 1, 0, 1]) - - s_0123 = Series(range(4), dtype="int64") - s_3333 = Series([3] * 4) - s_4444 = Series([4] * 4) - res = s_tft & s_empty expected = s_fff assert_series_equal(res, expected) @@ -60,6 +52,16 @@ def test_operators_bitwise(self): expected = s_tft assert_series_equal(res, expected) + def test_logical_operators_int_dtype_with_int_dtype(self): + # GH#9016: support bitwise op for integer types + + # TODO: unused + # s_0101 = Series([0, 1, 0, 1]) + + s_0123 = Series(range(4), dtype="int64") + s_3333 = Series([3] * 4) + s_4444 = Series([4] * 4) + res = s_0123 & s_3333 expected = Series(range(4), dtype="int64") assert_series_equal(res, expected) @@ -68,76 +70,129 @@ def test_operators_bitwise(self): expected = Series(range(4, 8), dtype="int64") assert_series_equal(res, expected) - s_a0b1c0 = Series([1], list("b")) - - res = s_tft & s_a0b1c0 - expected = s_tff.reindex(list("abc")) + s_1111 = Series([1] * 4, dtype="int8") + res = s_0123 & s_1111 + expected = Series([0, 1, 0, 1], dtype="int64") assert_series_equal(res, expected) - res = s_tft | s_a0b1c0 - expected = s_tft.reindex(list("abc")) + res = s_0123.astype(np.int16) | s_1111.astype(np.int32) + expected = Series([1, 1, 3, 3], dtype="int32") assert_series_equal(res, expected) - n0 = 0 - res = s_tft & n0 - expected = s_fff - assert_series_equal(res, expected) + def test_logical_operators_int_dtype_with_int_scalar(self): + # GH#9016: support bitwise op for integer types + s_0123 = Series(range(4), dtype="int64") - res = s_0123 & n0 + res = s_0123 & 0 expected = Series([0] * 4) assert_series_equal(res, expected) - n1 = 1 - res = s_tft & n1 - expected = s_tft - assert_series_equal(res, expected) - - res = s_0123 & n1 + res = s_0123 & 1 expected = Series([0, 1, 0, 1]) assert_series_equal(res, expected) - s_1111 = Series([1] * 4, dtype="int8") - res = s_0123 & s_1111 - expected = Series([0, 1, 0, 1], dtype="int64") - assert_series_equal(res, expected) - - res = s_0123.astype(np.int16) | s_1111.astype(np.int32) - expected = Series([1, 1, 3, 3], dtype="int32") - assert_series_equal(res, expected) + def test_logical_operators_int_dtype_with_float(self): + # GH#9016: support bitwise op for integer types + s_0123 = Series(range(4), dtype="int64") - with pytest.raises(TypeError): - s_1111 & "a" - with pytest.raises(TypeError): - s_1111 & ["a", "b", "c", "d"] with pytest.raises(TypeError): s_0123 & np.NaN with pytest.raises(TypeError): s_0123 & 3.14 with pytest.raises(TypeError): s_0123 & [0.1, 4, 3.14, 2] + with pytest.raises(TypeError): + s_0123 & np.array([0.1, 4, 3.14, 2]) - # s_0123 will be all false now because of reindexing like s_tft - exp = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) - assert_series_equal(s_tft & s_0123, exp) - - # s_tft will be all false now because of reindexing like s_0123 - exp = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) - assert_series_equal(s_0123 & s_tft, exp) - - assert_series_equal(s_0123 & False, Series([False] * 4)) - assert_series_equal(s_0123 ^ False, Series([False, True, True, True])) - assert_series_equal(s_0123 & [False], Series([False] * 4)) - assert_series_equal(s_0123 & (False), Series([False] * 4)) - assert_series_equal( - s_0123 & Series([False, np.NaN, False, False]), Series([False] * 4) - ) + # FIXME: this should be consistent with the list case above + expected = Series([False, True, False, True]) + result = s_0123 & Series([0.1, 4, -3.14, 2]) + assert_series_equal(result, expected) + + def test_logical_operators_int_dtype_with_str(self): + s_1111 = Series([1] * 4, dtype="int8") + + with pytest.raises(TypeError): + s_1111 & "a" + with pytest.raises(TypeError): + s_1111 & ["a", "b", "c", "d"] + + def test_logical_operators_int_dtype_with_bool(self): + # GH#9016: support bitwise op for integer types + s_0123 = Series(range(4), dtype="int64") + + expected = Series([False] * 4) + + result = s_0123 & False + assert_series_equal(result, expected) + + result = s_0123 & [False] + assert_series_equal(result, expected) + + result = s_0123 & (False,) + assert_series_equal(result, expected) - s_ftft = Series([False, True, False, True]) - assert_series_equal(s_0123 & Series([0.1, 4, -3.14, 2]), s_ftft) + result = s_0123 ^ False + expected = Series([False, True, True, True]) + assert_series_equal(result, expected) + + def test_logical_operators_int_dtype_with_object(self): + # GH#9016: support bitwise op for integer types + s_0123 = Series(range(4), dtype="int64") + + result = s_0123 & Series([False, np.NaN, False, False]) + expected = Series([False] * 4) + assert_series_equal(result, expected) s_abNd = Series(["a", "b", np.NaN, "d"]) - res = s_0123 & s_abNd - expected = s_ftft + result = s_0123 & s_abNd + expected = Series([False, True, False, True]) + assert_series_equal(result, expected) + + def test_logical_operators_bool_dtype_with_int(self): + index = list("bca") + + s_tft = Series([True, False, True], index=index) + s_fff = Series([False, False, False], index=index) + + res = s_tft & 0 + expected = s_fff + assert_series_equal(res, expected) + + res = s_tft & 1 + expected = s_tft + assert_series_equal(res, expected) + + def test_logical_operators_int_dtype_with_bool_dtype_and_reindex(self): + # GH#9016: support bitwise op for integer types + + # with non-matching indexes, logical operators will cast to object + # before operating + index = list("bca") + + s_tft = Series([True, False, True], index=index) + s_tft = Series([True, False, True], index=index) + s_tff = Series([True, False, False], index=index) + + s_0123 = Series(range(4), dtype="int64") + + # s_0123 will be all false now because of reindexing like s_tft + expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) + result = s_tft & s_0123 + assert_series_equal(result, expected) + + expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) + result = s_0123 & s_tft + assert_series_equal(result, expected) + + s_a0b1c0 = Series([1], list("b")) + + res = s_tft & s_a0b1c0 + expected = s_tff.reindex(list("abc")) + assert_series_equal(res, expected) + + res = s_tft | s_a0b1c0 + expected = s_tft.reindex(list("abc")) assert_series_equal(res, expected) def test_scalar_na_logical_ops_corners(self): @@ -523,6 +578,7 @@ def test_comparison_operators_with_nas(self): assert_series_equal(result, expected) + # FIXME: dont leave commented-out # fffffffuuuuuuuuuuuu # result = f(val, s) # expected = f(val, s.dropna()).reindex(s.index)
Working on logical ops I'm finding a bunch of internal inconsistencies that will need to be addressed. Since those are liable to have large diffs, this starts off with refactor that leaves behavior unchanged: simplify the method itself, and split a giant test into well-scoped ones.
https://api.github.com/repos/pandas-dev/pandas/pulls/28081
2019-08-22T03:09:37Z
2019-09-02T21:06:27Z
2019-09-02T21:06:27Z
2019-09-02T22:56:03Z
Auto backport of pr 28074 on 0.25.x
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index a7b97b41fb776..eb54961309e8e 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -1,57 +1,44 @@ .. _whatsnew_0251: -What's new in 0.25.1 (July XX, 2019) ------------------------------------- +What's new in 0.25.1 (August 21, 2019) +-------------------------------------- -Enhancements -~~~~~~~~~~~~ - - -.. _whatsnew_0251.enhancements.other: +These are the changes in pandas 0.25.1. See :ref:`release` for a full changelog +including other versions of pandas. -Other enhancements -^^^^^^^^^^^^^^^^^^ +I/O and LZMA +~~~~~~~~~~~~ -- -- -- +Some users may unknowingly have an incomplete Python installation lacking the `lzma` module from the standard library. In this case, `import pandas` failed due to an `ImportError` (:issue: `27575`). +Pandas will now warn, rather than raising an `ImportError` if the `lzma` module is not present. Any subsequent attempt to use `lzma` methods will raise a `RuntimeError`. +A possible fix for the lack of the `lzma` module is to ensure you have the necessary libraries and then re-install Python. +For example, on MacOS installing Python with `pyenv` may lead to an incomplete Python installation due to unmet system dependencies at compilation time (like `xz`). Compilation will succeed, but Python might fail at run time. The issue can be solved by installing the necessary dependencies and then re-installing Python. .. _whatsnew_0251.bug_fixes: Bug fixes ~~~~~~~~~ - Categorical ^^^^^^^^^^^ -- Bug in :meth:`Categorical.fillna` would replace all values, not just those that are ``NaN`` (:issue:`26215`) -- -- +- Bug in :meth:`Categorical.fillna` that would replace all values, not just those that are ``NaN`` (:issue:`26215`) Datetimelike ^^^^^^^^^^^^ + - Bug in :func:`to_datetime` where passing a timezone-naive :class:`DatetimeArray` or :class:`DatetimeIndex` and ``utc=True`` would incorrectly return a timezone-naive result (:issue:`27733`) - Bug in :meth:`Period.to_timestamp` where a :class:`Period` outside the :class:`Timestamp` implementation bounds (roughly 1677-09-21 to 2262-04-11) would return an incorrect :class:`Timestamp` instead of raising ``OutOfBoundsDatetime`` (:issue:`19643`) -- -- - -Timedelta -^^^^^^^^^ - -- -- -- +- Bug in iterating over :class:`DatetimeIndex` when the underlying data is read-only (:issue:`28055`) Timezones ^^^^^^^^^ - Bug in :class:`Index` where a numpy object array with a timezone aware :class:`Timestamp` and ``np.nan`` would not return a :class:`DatetimeIndex` (:issue:`27011`) -- -- Numeric ^^^^^^^ + - Bug in :meth:`Series.interpolate` when using a timezone aware :class:`DatetimeIndex` (:issue:`27548`) - Bug when printing negative floating point complex numbers would raise an ``IndexError`` (:issue:`27484`) - Bug where :class:`DataFrame` arithmetic operators such as :meth:`DataFrame.mul` with a :class:`Series` with axis=1 would raise an ``AttributeError`` on :class:`DataFrame` larger than the minimum threshold to invoke numexpr (:issue:`27636`) @@ -61,23 +48,11 @@ Conversion ^^^^^^^^^^ - Improved the warnings for the deprecated methods :meth:`Series.real` and :meth:`Series.imag` (:issue:`27610`) -- -- - -Strings -^^^^^^^ - -- -- -- - Interval ^^^^^^^^ + - Bug in :class:`IntervalIndex` where `dir(obj)` would raise ``ValueError`` (:issue:`27571`) -- -- -- Indexing ^^^^^^^^ @@ -86,38 +61,26 @@ Indexing - Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). - Fix regression in ``.ix`` fallback with an ``IntervalIndex`` (:issue:`27865`). -- Missing ^^^^^^^ -- Bug in :func:`pandas.isnull` or :func:`pandas.isna` when the input is a type e.g. `type(pandas.Series())` (:issue:`27482`) -- -- - -MultiIndex -^^^^^^^^^^ - -- -- -- +- Bug in :func:`pandas.isnull` or :func:`pandas.isna` when the input is a type e.g. ``type(pandas.Series())`` (:issue:`27482`) I/O ^^^ + - Avoid calling ``S3File.s3`` when reading parquet, as this was removed in s3fs version 0.3.0 (:issue:`27756`) - Better error message when a negative header is passed in :func:`pandas.read_csv` (:issue:`27779`) -- Follow the ``min_rows`` display option (introduced in v0.25.0) correctly in the html repr in the notebook (:issue:`27991`). -- +- Follow the ``min_rows`` display option (introduced in v0.25.0) correctly in the HTML repr in the notebook (:issue:`27991`). Plotting ^^^^^^^^ -- Added a pandas_plotting_backends entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`). +- Added a ``pandas_plotting_backends`` entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`). - Fixed the re-instatement of Matplotlib datetime converters after calling - `pandas.plotting.deregister_matplotlib_converters()` (:issue:`27481`). -- + :meth:`pandas.plotting.deregister_matplotlib_converters` (:issue:`27481`). - Fix compatibility issue with matplotlib when passing a pandas ``Index`` to a plot call (:issue:`27775`). -- Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -125,8 +88,7 @@ Groupby/resample/rolling - Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.transform` where applying a timezone conversion lambda function would drop timezone information (:issue:`27496`) - Bug in :meth:`pandas.core.groupby.GroupBy.nth` where ``observed=False`` was being ignored for Categorical groupers (:issue:`26385`) - Bug in windowing over read-only arrays (:issue:`27766`) -- -- +- Fixed segfault in `pandas.core.groupby.DataFrameGroupBy.quantile` when an invalid quantile was passed (:issue:`27470`) Reshaping ^^^^^^^^^ @@ -139,39 +101,12 @@ Reshaping Sparse ^^^^^^ -- -- -- - - -Build Changes -^^^^^^^^^^^^^ - -- -- -- - -ExtensionArray -^^^^^^^^^^^^^^ - -- -- -- +- Bug in reductions for :class:`Series` with Sparse dtypes (:issue:`27080`) Other ^^^^^ -- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) -- -- -- - -I/O and LZMA -~~~~~~~~~~~~ -Some users may unknowingly have an incomplete Python installation, which lacks the `lzma` module from the standard library. In this case, `import pandas` failed due to an `ImportError` (:issue: `27575`). -Pandas will now warn, rather than raising an `ImportError` if the `lzma` module is not present. Any subsequent attempt to use `lzma` methods will raise a `RuntimeError`. -A possible fix for the lack of the `lzma` module is to ensure you have the necessary libraries and then re-install Python. -For example, on MacOS installing Python with `pyenv` may lead to an incomplete Python installation due to unmet system dependencies at compilation time (like `xz`). Compilation will succeed, but Python might fail at run time. The issue can be solved by installing the necessary dependencies and then re-installing Python. +- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) .. _whatsnew_0.251.contributors: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 4e49f660f5e19..01e500a80dcc4 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -71,7 +71,7 @@ cdef inline object create_time_from_ts( @cython.wraparound(False) @cython.boundscheck(False) -def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None, +def ints_to_pydatetime(const int64_t[:] arr, object tz=None, object freq=None, str box="datetime"): """ Convert an i8 repr to an ndarray of datetimes, date, time or Timestamp diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index 4ea32359b8d4a..ab3107a0798e5 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -377,3 +377,11 @@ def test_nanosecond_field(self): dti = DatetimeIndex(np.arange(10)) tm.assert_index_equal(dti.nanosecond, pd.Index(np.arange(10, dtype=np.int64))) + + +def test_iter_readonly(): + # GH#28055 ints_to_pydatetime with readonly array + arr = np.array([np.datetime64("2012-02-15T12:00:00.000000000")]) + arr.setflags(write=False) + dti = pd.to_datetime(arr) + list(dti)
#28073 and #28074
https://api.github.com/repos/pandas-dev/pandas/pulls/28078
2019-08-21T21:08:37Z
2019-08-22T11:30:24Z
2019-08-22T11:30:24Z
2019-08-22T11:30:28Z
Backport PR #28072 on branch 0.25.x (TST: non-strict xfail for period test)
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index b57b817461788..04b92e263d645 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1581,7 +1581,11 @@ def test_period_immutable(): @pytest.mark.xfail( - PY35, reason="Parsing as Period('0007-01-01', 'D') for reasons unknown", strict=True + # xpassing on MacPython with strict=False + # https://travis-ci.org/MacPython/pandas-wheels/jobs/574706922 + PY35, + reason="Parsing as Period('0007-01-01', 'D') for reasons unknown", + strict=False, ) def test_small_year_parsing(): per1 = Period("0001-01-07", "D")
Backport PR #28072: TST: non-strict xfail for period test
https://api.github.com/repos/pandas-dev/pandas/pulls/28077
2019-08-21T20:53:53Z
2019-08-22T11:29:21Z
2019-08-22T11:29:21Z
2019-08-22T11:29:21Z
Backport PR #28065: CI: disable codecov
diff --git a/ci/run_tests.sh b/ci/run_tests.sh index ee46da9f52eab..27d3fcb4cf563 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -50,9 +50,10 @@ do # if no tests are found (the case of "single and slow"), pytest exits with code 5, and would make the script fail, if not for the below code sh -c "$PYTEST_CMD; ret=\$?; [ \$ret = 5 ] && exit 0 || exit \$ret" - if [[ "$COVERAGE" && $? == 0 ]]; then - echo "uploading coverage for $TYPE tests" - echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME" - bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME - fi + # 2019-08-21 disabling because this is hitting HTTP 400 errors GH#27602 + # if [[ "$COVERAGE" && $? == 0 && "$TRAVIS_BRANCH" == "master" ]]; then + # echo "uploading coverage for $TYPE tests" + # echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME" + # bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME + # fi done
https://api.github.com/repos/pandas-dev/pandas/pulls/28076
2019-08-21T20:51:21Z
2019-08-22T11:31:22Z
2019-08-22T11:31:22Z
2019-08-22T11:31:26Z
DOC: redirect from_csv search
diff --git a/doc/redirects.csv b/doc/redirects.csv index a7886779c97d5..975fefead67a5 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -1579,3 +1579,6 @@ generated/pandas.unique,../reference/api/pandas.unique generated/pandas.util.hash_array,../reference/api/pandas.util.hash_array generated/pandas.util.hash_pandas_object,../reference/api/pandas.util.hash_pandas_object generated/pandas.wide_to_long,../reference/api/pandas.wide_to_long + +# Cached searches +reference/api/pandas.DataFrame.from_csv,pandas.read_csv
A web search for "DataFrame from CSV" leads to https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_csv.html which is currently a 404, since DataFrame.from_csv was removed. Redirect it to read_csv. Normally we shouldn't worry about this, but I suspect this is a common search term.
https://api.github.com/repos/pandas-dev/pandas/pulls/28075
2019-08-21T20:30:56Z
2019-09-28T09:14:07Z
2019-09-28T09:14:06Z
2019-09-28T09:14:07Z
BUG: iter with readonly values, closes #28055
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index b658a6efbd1a1..eb54961309e8e 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -29,6 +29,7 @@ Datetimelike - Bug in :func:`to_datetime` where passing a timezone-naive :class:`DatetimeArray` or :class:`DatetimeIndex` and ``utc=True`` would incorrectly return a timezone-naive result (:issue:`27733`) - Bug in :meth:`Period.to_timestamp` where a :class:`Period` outside the :class:`Timestamp` implementation bounds (roughly 1677-09-21 to 2262-04-11) would return an incorrect :class:`Timestamp` instead of raising ``OutOfBoundsDatetime`` (:issue:`19643`) +- Bug in iterating over :class:`DatetimeIndex` when the underlying data is read-only (:issue:`28055`) Timezones ^^^^^^^^^ diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 4e49f660f5e19..01e500a80dcc4 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -71,7 +71,7 @@ cdef inline object create_time_from_ts( @cython.wraparound(False) @cython.boundscheck(False) -def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None, +def ints_to_pydatetime(const int64_t[:] arr, object tz=None, object freq=None, str box="datetime"): """ Convert an i8 repr to an ndarray of datetimes, date, time or Timestamp diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index 4ea32359b8d4a..ab3107a0798e5 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -377,3 +377,11 @@ def test_nanosecond_field(self): dti = DatetimeIndex(np.arange(10)) tm.assert_index_equal(dti.nanosecond, pd.Index(np.arange(10, dtype=np.int64))) + + +def test_iter_readonly(): + # GH#28055 ints_to_pydatetime with readonly array + arr = np.array([np.datetime64("2012-02-15T12:00:00.000000000")]) + arr.setflags(write=False) + dti = pd.to_datetime(arr) + list(dti)
@TomAugspurger wanted to get this in under the wire? - [x] closes #28055 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/28074
2019-08-21T20:20:23Z
2019-08-21T20:54:42Z
2019-08-21T20:54:42Z
2019-08-21T21:35:23Z
DOC: Update whatsnew
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 86d6db01c10c2..b658a6efbd1a1 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -1,56 +1,43 @@ .. _whatsnew_0251: -What's new in 0.25.1 (July XX, 2019) ------------------------------------- +What's new in 0.25.1 (August 21, 2019) +-------------------------------------- -Enhancements -~~~~~~~~~~~~ - - -.. _whatsnew_0251.enhancements.other: +These are the changes in pandas 0.25.1. See :ref:`release` for a full changelog +including other versions of pandas. -Other enhancements -^^^^^^^^^^^^^^^^^^ +I/O and LZMA +~~~~~~~~~~~~ -- -- -- +Some users may unknowingly have an incomplete Python installation lacking the `lzma` module from the standard library. In this case, `import pandas` failed due to an `ImportError` (:issue: `27575`). +Pandas will now warn, rather than raising an `ImportError` if the `lzma` module is not present. Any subsequent attempt to use `lzma` methods will raise a `RuntimeError`. +A possible fix for the lack of the `lzma` module is to ensure you have the necessary libraries and then re-install Python. +For example, on MacOS installing Python with `pyenv` may lead to an incomplete Python installation due to unmet system dependencies at compilation time (like `xz`). Compilation will succeed, but Python might fail at run time. The issue can be solved by installing the necessary dependencies and then re-installing Python. .. _whatsnew_0251.bug_fixes: Bug fixes ~~~~~~~~~ - Categorical ^^^^^^^^^^^ -- Bug in :meth:`Categorical.fillna` would replace all values, not just those that are ``NaN`` (:issue:`26215`) -- +- Bug in :meth:`Categorical.fillna` that would replace all values, not just those that are ``NaN`` (:issue:`26215`) Datetimelike ^^^^^^^^^^^^ + - Bug in :func:`to_datetime` where passing a timezone-naive :class:`DatetimeArray` or :class:`DatetimeIndex` and ``utc=True`` would incorrectly return a timezone-naive result (:issue:`27733`) - Bug in :meth:`Period.to_timestamp` where a :class:`Period` outside the :class:`Timestamp` implementation bounds (roughly 1677-09-21 to 2262-04-11) would return an incorrect :class:`Timestamp` instead of raising ``OutOfBoundsDatetime`` (:issue:`19643`) -- -- - -Timedelta -^^^^^^^^^ - -- -- -- Timezones ^^^^^^^^^ - Bug in :class:`Index` where a numpy object array with a timezone aware :class:`Timestamp` and ``np.nan`` would not return a :class:`DatetimeIndex` (:issue:`27011`) -- -- Numeric ^^^^^^^ + - Bug in :meth:`Series.interpolate` when using a timezone aware :class:`DatetimeIndex` (:issue:`27548`) - Bug when printing negative floating point complex numbers would raise an ``IndexError`` (:issue:`27484`) - Bug where :class:`DataFrame` arithmetic operators such as :meth:`DataFrame.mul` with a :class:`Series` with axis=1 would raise an ``AttributeError`` on :class:`DataFrame` larger than the minimum threshold to invoke numexpr (:issue:`27636`) @@ -60,23 +47,11 @@ Conversion ^^^^^^^^^^ - Improved the warnings for the deprecated methods :meth:`Series.real` and :meth:`Series.imag` (:issue:`27610`) -- -- - -Strings -^^^^^^^ - -- -- -- - Interval ^^^^^^^^ + - Bug in :class:`IntervalIndex` where `dir(obj)` would raise ``ValueError`` (:issue:`27571`) -- -- -- Indexing ^^^^^^^^ @@ -85,38 +60,26 @@ Indexing - Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). - Fix regression in ``.ix`` fallback with an ``IntervalIndex`` (:issue:`27865`). -- Missing ^^^^^^^ -- Bug in :func:`pandas.isnull` or :func:`pandas.isna` when the input is a type e.g. `type(pandas.Series())` (:issue:`27482`) -- -- - -MultiIndex -^^^^^^^^^^ - -- -- -- +- Bug in :func:`pandas.isnull` or :func:`pandas.isna` when the input is a type e.g. ``type(pandas.Series())`` (:issue:`27482`) I/O ^^^ + - Avoid calling ``S3File.s3`` when reading parquet, as this was removed in s3fs version 0.3.0 (:issue:`27756`) - Better error message when a negative header is passed in :func:`pandas.read_csv` (:issue:`27779`) -- Follow the ``min_rows`` display option (introduced in v0.25.0) correctly in the html repr in the notebook (:issue:`27991`). -- +- Follow the ``min_rows`` display option (introduced in v0.25.0) correctly in the HTML repr in the notebook (:issue:`27991`). Plotting ^^^^^^^^ -- Added a pandas_plotting_backends entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`). +- Added a ``pandas_plotting_backends`` entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`). - Fixed the re-instatement of Matplotlib datetime converters after calling - `pandas.plotting.deregister_matplotlib_converters()` (:issue:`27481`). -- + :meth:`pandas.plotting.deregister_matplotlib_converters` (:issue:`27481`). - Fix compatibility issue with matplotlib when passing a pandas ``Index`` to a plot call (:issue:`27775`). -- Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -125,7 +88,6 @@ Groupby/resample/rolling - Bug in :meth:`pandas.core.groupby.GroupBy.nth` where ``observed=False`` was being ignored for Categorical groupers (:issue:`26385`) - Bug in windowing over read-only arrays (:issue:`27766`) - Fixed segfault in `pandas.core.groupby.DataFrameGroupBy.quantile` when an invalid quantile was passed (:issue:`27470`) -- Reshaping ^^^^^^^^^ @@ -137,40 +99,13 @@ Reshaping Sparse ^^^^^^ -- Bug in reductions for :class:`Series` with Sparse dtypes (:issue:`27080`) -- -- -- - - -Build Changes -^^^^^^^^^^^^^ - -- -- -- - -ExtensionArray -^^^^^^^^^^^^^^ -- -- -- +- Bug in reductions for :class:`Series` with Sparse dtypes (:issue:`27080`) Other ^^^^^ -- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) -- -- -- - -I/O and LZMA -~~~~~~~~~~~~ -Some users may unknowingly have an incomplete Python installation, which lacks the `lzma` module from the standard library. In this case, `import pandas` failed due to an `ImportError` (:issue: `27575`). -Pandas will now warn, rather than raising an `ImportError` if the `lzma` module is not present. Any subsequent attempt to use `lzma` methods will raise a `RuntimeError`. -A possible fix for the lack of the `lzma` module is to ensure you have the necessary libraries and then re-install Python. -For example, on MacOS installing Python with `pyenv` may lead to an incomplete Python installation due to unmet system dependencies at compilation time (like `xz`). Compilation will succeed, but Python might fail at run time. The issue can be solved by installing the necessary dependencies and then re-installing Python. +- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) .. _whatsnew_0.251.contributors:
https://api.github.com/repos/pandas-dev/pandas/pulls/28073
2019-08-21T19:39:00Z
2019-08-21T20:52:03Z
2019-08-21T20:52:03Z
2019-08-21T21:09:16Z
TST: non-strict xfail for period test
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 6da4d556ea07e..a1de205afc0e2 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1549,7 +1549,11 @@ def test_period_immutable(): @pytest.mark.xfail( - PY35, reason="Parsing as Period('0007-01-01', 'D') for reasons unknown", strict=True + # xpassing on MacPython with strict=False + # https://travis-ci.org/MacPython/pandas-wheels/jobs/574706922 + PY35, + reason="Parsing as Period('0007-01-01', 'D') for reasons unknown", + strict=False, ) def test_small_year_parsing(): per1 = Period("0001-01-07", "D")
This was XPASSing on the MacPython builds: https://travis-ci.org/MacPython/pandas-wheels/jobs/574706922
https://api.github.com/repos/pandas-dev/pandas/pulls/28072
2019-08-21T19:31:38Z
2019-08-21T20:53:10Z
2019-08-21T20:53:10Z
2019-08-21T20:53:13Z
Set SHA for codecov upload
diff --git a/ci/run_tests.sh b/ci/run_tests.sh index ee46da9f52eab..74c1cde325a02 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -51,8 +51,9 @@ do sh -c "$PYTEST_CMD; ret=\$?; [ \$ret = 5 ] && exit 0 || exit \$ret" if [[ "$COVERAGE" && $? == 0 ]]; then + SHA=`git rev-parse HEAD` echo "uploading coverage for $TYPE tests" - echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME" - bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME + echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME -C $SHA" + bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME -C `git rev-parse HEAD` fi done
Just a test.
https://api.github.com/repos/pandas-dev/pandas/pulls/28067
2019-08-21T17:11:08Z
2019-08-21T18:32:28Z
2019-08-21T18:32:28Z
2019-08-21T18:32:32Z
REF: do extract_array earlier in series arith/comparison ops
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 7e03b9544ee72..4fa2267e9af78 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -5,7 +5,7 @@ """ import datetime import operator -from typing import Any, Callable, Tuple +from typing import Any, Callable, Tuple, Union import numpy as np @@ -34,10 +34,11 @@ ABCIndexClass, ABCSeries, ABCSparseSeries, + ABCTimedeltaArray, + ABCTimedeltaIndex, ) from pandas.core.dtypes.missing import isna, notna -import pandas as pd from pandas._typing import ArrayLike from pandas.core.construction import array, extract_array from pandas.core.ops.array_ops import comp_method_OBJECT_ARRAY, define_na_arithmetic_op @@ -148,6 +149,8 @@ def maybe_upcast_for_op(obj, shape: Tuple[int, ...]): Be careful to call this *after* determining the `name` attribute to be attached to the result of the arithmetic operation. """ + from pandas.core.arrays import TimedeltaArray + if type(obj) is datetime.timedelta: # GH#22390 cast up to Timedelta to rely on Timedelta # implementation; otherwise operation against numeric-dtype @@ -157,12 +160,10 @@ def maybe_upcast_for_op(obj, shape: Tuple[int, ...]): if isna(obj): # wrapping timedelta64("NaT") in Timedelta returns NaT, # which would incorrectly be treated as a datetime-NaT, so - # we broadcast and wrap in a Series + # we broadcast and wrap in a TimedeltaArray + obj = obj.astype("timedelta64[ns]") right = np.broadcast_to(obj, shape) - - # Note: we use Series instead of TimedeltaIndex to avoid having - # to worry about catching NullFrequencyError. - return pd.Series(right) + return TimedeltaArray(right) # In particular non-nanosecond timedelta64 needs to be cast to # nanoseconds, or else we get undesired behavior like @@ -173,7 +174,7 @@ def maybe_upcast_for_op(obj, shape: Tuple[int, ...]): # GH#22390 Unfortunately we need to special-case right-hand # timedelta64 dtypes because numpy casts integer dtypes to # timedelta64 when operating with timedelta64 - return pd.TimedeltaIndex(obj) + return TimedeltaArray._from_sequence(obj) return obj @@ -520,13 +521,34 @@ def column_op(a, b): return result -def dispatch_to_extension_op(op, left, right): +def dispatch_to_extension_op( + op, + left: Union[ABCExtensionArray, np.ndarray], + right: Any, + keep_null_freq: bool = False, +): """ Assume that left or right is a Series backed by an ExtensionArray, apply the operator defined by op. + + Parameters + ---------- + op : binary operator + left : ExtensionArray or np.ndarray + right : object + keep_null_freq : bool, default False + Whether to re-raise a NullFrequencyError unchanged, as opposed to + catching and raising TypeError. + + Returns + ------- + ExtensionArray or np.ndarray + 2-tuple of these if op is divmod or rdivmod """ + # NB: left and right should already be unboxed, so neither should be + # a Series or Index. - if left.dtype.kind in "mM": + if left.dtype.kind in "mM" and isinstance(left, np.ndarray): # We need to cast datetime64 and timedelta64 ndarrays to # DatetimeArray/TimedeltaArray. But we avoid wrapping others in # PandasArray as that behaves poorly with e.g. IntegerArray. @@ -535,15 +557,15 @@ def dispatch_to_extension_op(op, left, right): # The op calls will raise TypeError if the op is not defined # on the ExtensionArray - # unbox Series and Index to arrays - new_left = extract_array(left, extract_numpy=True) - new_right = extract_array(right, extract_numpy=True) - try: - res_values = op(new_left, new_right) + res_values = op(left, right) except NullFrequencyError: # DatetimeIndex and TimedeltaIndex with freq == None raise ValueError # on add/sub of integers (or int-like). We re-raise as a TypeError. + if keep_null_freq: + # TODO: remove keep_null_freq after Timestamp+int deprecation + # GH#22535 is enforced + raise raise TypeError( "incompatible type for a datetime/timedelta " "operation [{name}]".format(name=op.__name__) @@ -615,25 +637,29 @@ def wrapper(left, right): if isinstance(right, ABCDataFrame): return NotImplemented + keep_null_freq = isinstance( + right, + (ABCDatetimeIndex, ABCDatetimeArray, ABCTimedeltaIndex, ABCTimedeltaArray), + ) + left, right = _align_method_SERIES(left, right) res_name = get_op_result_name(left, right) - right = maybe_upcast_for_op(right, left.shape) - if should_extension_dispatch(left, right): - result = dispatch_to_extension_op(op, left, right) + lvalues = extract_array(left, extract_numpy=True) + rvalues = extract_array(right, extract_numpy=True) - elif is_timedelta64_dtype(right) or isinstance( - right, (ABCDatetimeArray, ABCDatetimeIndex) - ): - # We should only get here with td64 right with non-scalar values - # for right upcast by maybe_upcast_for_op - assert not isinstance(right, (np.timedelta64, np.ndarray)) - result = op(left._values, right) + rvalues = maybe_upcast_for_op(rvalues, lvalues.shape) - else: - lvalues = extract_array(left, extract_numpy=True) - rvalues = extract_array(right, extract_numpy=True) + if should_extension_dispatch(lvalues, rvalues): + result = dispatch_to_extension_op(op, lvalues, rvalues, keep_null_freq) + + elif is_timedelta64_dtype(rvalues) or isinstance(rvalues, ABCDatetimeArray): + # We should only get here with td64 rvalues with non-scalar values + # for rvalues upcast by maybe_upcast_for_op + assert not isinstance(rvalues, (np.timedelta64, np.ndarray)) + result = dispatch_to_extension_op(op, lvalues, rvalues, keep_null_freq) + else: with np.errstate(all="ignore"): result = na_op(lvalues, rvalues) @@ -708,25 +734,25 @@ def wrapper(self, other, axis=None): if len(self) != len(other): raise ValueError("Lengths must match to compare") - if should_extension_dispatch(self, other): - res_values = dispatch_to_extension_op(op, self, other) + lvalues = extract_array(self, extract_numpy=True) + rvalues = extract_array(other, extract_numpy=True) - elif is_scalar(other) and isna(other): + if should_extension_dispatch(lvalues, rvalues): + res_values = dispatch_to_extension_op(op, lvalues, rvalues) + + elif is_scalar(rvalues) and isna(rvalues): # numpy does not like comparisons vs None if op is operator.ne: - res_values = np.ones(len(self), dtype=bool) + res_values = np.ones(len(lvalues), dtype=bool) else: - res_values = np.zeros(len(self), dtype=bool) + res_values = np.zeros(len(lvalues), dtype=bool) else: - lvalues = extract_array(self, extract_numpy=True) - rvalues = extract_array(other, extract_numpy=True) - with np.errstate(all="ignore"): res_values = na_op(lvalues, rvalues) if is_scalar(res_values): raise TypeError( - "Could not compare {typ} type with Series".format(typ=type(other)) + "Could not compare {typ} type with Series".format(typ=type(rvalues)) ) result = self._constructor(res_values, index=self.index)
With this, the middle third of _arith_method_SERIES and _comp_method_SERIES are array-specific and can be refactored out (separate step) to become a) block-wise implementation for DataFrame and b) PandasArray implementation. This also simplifies the NullFrequencyError handling nicely.
https://api.github.com/repos/pandas-dev/pandas/pulls/28066
2019-08-21T17:09:14Z
2019-09-02T21:09:20Z
2019-09-02T21:09:20Z
2019-09-02T22:54:55Z
CI: disable codecov
diff --git a/ci/run_tests.sh b/ci/run_tests.sh index 74c1cde325a02..27d3fcb4cf563 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -50,10 +50,10 @@ do # if no tests are found (the case of "single and slow"), pytest exits with code 5, and would make the script fail, if not for the below code sh -c "$PYTEST_CMD; ret=\$?; [ \$ret = 5 ] && exit 0 || exit \$ret" - if [[ "$COVERAGE" && $? == 0 ]]; then - SHA=`git rev-parse HEAD` - echo "uploading coverage for $TYPE tests" - echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME -C $SHA" - bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME -C `git rev-parse HEAD` - fi + # 2019-08-21 disabling because this is hitting HTTP 400 errors GH#27602 + # if [[ "$COVERAGE" && $? == 0 && "$TRAVIS_BRANCH" == "master" ]]; then + # echo "uploading coverage for $TYPE tests" + # echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME" + # bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME + # fi done
xref #27602
https://api.github.com/repos/pandas-dev/pandas/pulls/28065
2019-08-21T16:53:22Z
2019-08-21T20:23:15Z
2019-08-21T20:23:15Z
2019-08-21T21:09:16Z
BUG: Correct the previous bug fixing on xlim for plotting
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index fbca57206e163..6ff3f28440303 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -33,6 +33,8 @@ from pandas.plotting._matplotlib.style import _get_standard_colors from pandas.plotting._matplotlib.tools import ( _flatten, + _get_all_lines, + _get_xlim, _handle_shared_axes, _subplots, format_date_labels, @@ -1099,8 +1101,13 @@ def _make_plot(self): ) self._add_legend_handle(newlines[0], label, index=i) - # GH27686 set_xlim will truncate xaxis to fixed space - ax.relim() + if self._is_ts_plot(): + + # reset of xlim should be used for ts data + # TODO: GH28021, should find a way to change view limit on xaxis + lines = _get_all_lines(ax) + left, right = _get_xlim(lines) + ax.set_xlim(left, right) @classmethod def _plot(cls, ax, x, y, style=None, column_num=None, stacking_id=None, **kwds): diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index fd2913ca51ac3..67fa79ad5da8c 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -356,3 +356,24 @@ def _set_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=Non if yrot is not None: plt.setp(ax.get_yticklabels(), rotation=yrot) return axes + + +def _get_all_lines(ax): + lines = ax.get_lines() + + if hasattr(ax, "right_ax"): + lines += ax.right_ax.get_lines() + + if hasattr(ax, "left_ax"): + lines += ax.left_ax.get_lines() + + return lines + + +def _get_xlim(lines): + left, right = np.inf, -np.inf + for l in lines: + x = l.get_xdata(orig=False) + left = min(np.nanmin(x), left) + right = max(np.nanmax(x), right) + return left, right diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index be87929b4545a..e2b7f2819f957 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -419,8 +419,6 @@ def test_get_finder(self): assert conv.get_finder("A") == conv._annual_finder assert conv.get_finder("W") == conv._daily_finder - # TODO: The finder should be retested due to wrong xlim values on x-axis - @pytest.mark.xfail(reason="TODO: check details in GH28021") @pytest.mark.slow def test_finder_daily(self): day_lst = [10, 40, 252, 400, 950, 2750, 10000] @@ -444,8 +442,6 @@ def test_finder_daily(self): assert rs1 == xpl1 assert rs2 == xpl2 - # TODO: The finder should be retested due to wrong xlim values on x-axis - @pytest.mark.xfail(reason="TODO: check details in GH28021") @pytest.mark.slow def test_finder_quarterly(self): yrs = [3.5, 11] @@ -469,8 +465,6 @@ def test_finder_quarterly(self): assert rs1 == xpl1 assert rs2 == xpl2 - # TODO: The finder should be retested due to wrong xlim values on x-axis - @pytest.mark.xfail(reason="TODO: check details in GH28021") @pytest.mark.slow def test_finder_monthly(self): yrs = [1.15, 2.5, 4, 11] @@ -504,8 +498,6 @@ def test_finder_monthly_long(self): xp = Period("1989Q1", "M").ordinal assert rs == xp - # TODO: The finder should be retested due to wrong xlim values on x-axis - @pytest.mark.xfail(reason="TODO: check details in GH28021") @pytest.mark.slow def test_finder_annual(self): xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170] @@ -530,7 +522,7 @@ def test_finder_minutely(self): _, ax = self.plt.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() - rs = xaxis.get_majorticklocs()[1] + rs = xaxis.get_majorticklocs()[0] xp = Period("1/1/1999", freq="Min").ordinal assert rs == xp @@ -542,7 +534,7 @@ def test_finder_hourly(self): _, ax = self.plt.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() - rs = xaxis.get_majorticklocs()[1] + rs = xaxis.get_majorticklocs()[0] xp = Period("1/1/1999", freq="H").ordinal assert rs == xp @@ -1418,9 +1410,7 @@ def test_plot_outofbounds_datetime(self): def test_format_timedelta_ticks_narrow(self): - expected_labels = [ - "00:00:00.0000000{:0>2d}".format(i) for i in np.arange(0, 10, 2) - ] + expected_labels = ["00:00:00.0000000{:0>2d}".format(i) for i in np.arange(10)] rng = timedelta_range("0", periods=10, freq="ns") df = DataFrame(np.random.randn(len(rng), 3), rng) @@ -1430,8 +1420,8 @@ def test_format_timedelta_ticks_narrow(self): labels = ax.get_xticklabels() result_labels = [x.get_text() for x in labels] - assert (len(result_labels) - 2) == len(expected_labels) - assert result_labels[1:-1] == expected_labels + assert len(result_labels) == len(expected_labels) + assert result_labels == expected_labels def test_format_timedelta_ticks_wide(self): expected_labels = [ @@ -1454,8 +1444,8 @@ def test_format_timedelta_ticks_wide(self): labels = ax.get_xticklabels() result_labels = [x.get_text() for x in labels] - assert (len(result_labels) - 2) == len(expected_labels) - assert result_labels[1:-1] == expected_labels + assert len(result_labels) == len(expected_labels) + assert result_labels == expected_labels def test_timedelta_plot(self): # test issue #8711
- [ ] xref: #28021 #27993 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/28059
2019-08-21T12:42:37Z
2019-08-21T15:18:10Z
2019-08-21T15:18:10Z
2019-08-21T15:18:11Z
Backport PR #28029 on branch 0.25.x (DOC: Change document code prun in a row)
diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst index c15991fabfd3b..fa2fe1ad3989b 100644 --- a/doc/source/user_guide/enhancingperf.rst +++ b/doc/source/user_guide/enhancingperf.rst @@ -243,9 +243,9 @@ We've gotten another big improvement. Let's check again where the time is spent: .. ipython:: python - %prun -l 4 apply_integrate_f(df['a'].to_numpy(), - df['b'].to_numpy(), - df['N'].to_numpy()) + %%prun -l 4 apply_integrate_f(df['a'].to_numpy(), + df['b'].to_numpy(), + df['N'].to_numpy()) As one might expect, the majority of the time is now spent in ``apply_integrate_f``, so if we wanted to make anymore efficiencies we must continue to concentrate our
Backport PR #28029: DOC: Change document code prun in a row
https://api.github.com/repos/pandas-dev/pandas/pulls/28054
2019-08-21T06:43:34Z
2019-08-21T17:08:05Z
2019-08-21T17:08:05Z
2019-08-21T17:08:05Z