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
BUG: interpolate with complex dtype
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index ba5334b2f4fa8..e5dd9e6eb86cc 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -406,6 +406,7 @@ Missing ^^^^^^^ - Bug in :meth:`DataFrame.interpolate` ignoring ``inplace`` when :class:`DataFrame` is empty (:issue:`53199`) - Bug in :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` failing to raise on invalid ``downcast`` keyword, which can be only ``None`` or "infer" (:issue:`53103`) +- Bug in :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` with complex dtype incorrectly failing to fill ``NaN`` entries (:issue:`53635`) - MultiIndex diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d0efa402089dc..981e29df2c323 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1375,7 +1375,7 @@ def interpolate( if method == "asfreq": # type: ignore[comparison-overlap] # clean_fill_method used to allow this raise - if m is None and self.dtype.kind != "f": + if m is None and self.dtype == _dtype_obj: # only deal with floats # bc we already checked that can_hold_na, we don't have int dtype here # test_interp_basic checks that we make a copy here diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index 5a3d53eb96a52..151e281b5ded2 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -13,6 +13,20 @@ class TestDataFrameInterpolate: + def test_interpolate_complex(self): + # GH#53635 + ser = Series([complex("1+1j"), float("nan"), complex("2+2j")]) + assert ser.dtype.kind == "c" + + res = ser.interpolate() + expected = Series([ser[0], ser[0] * 1.5, ser[2]]) + tm.assert_series_equal(res, expected) + + df = ser.to_frame() + res = df.interpolate() + expected = expected.to_frame() + tm.assert_frame_equal(res, expected) + def test_interpolate_datetimelike_values(self, frame_or_series): # GH#11312, GH#51005 orig = Series(date_range("2012-01-01", periods=5))
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53635
2023-06-13T01:45:49Z
2023-06-13T17:13:57Z
2023-06-13T17:13:57Z
2023-06-13T18:04:20Z
BUG: fix datetimeindex repr
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 839870cb18a0b..1e5918d2e5324 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -621,6 +621,7 @@ Metadata Other ^^^^^ - Bug in :class:`DataFrame` and :class:`Series` raising for data of complex dtype when ``NaN`` values are present (:issue:`53627`) +- Bug in :class:`DatetimeIndex` where ``repr`` of index passed with time does not print time is midnight and non-day based freq(:issue:`53470`) - Bug in :class:`FloatingArray.__contains__` with ``NaN`` item incorrectly returning ``False`` when ``NaN`` values are present (:issue:`52840`) - Bug in :func:`api.interchange.from_dataframe` when converting an empty DataFrame object (:issue:`53155`) - Bug in :func:`assert_almost_equal` now throwing assertion error for two unequal sets (:issue:`51727`) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 5465442b17fc3..10779bbcde0a2 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -393,11 +393,18 @@ def _is_dates_only(self) -> bool: ------- bool """ + from pandas.io.formats.format import is_dates_only + delta = getattr(self.freq, "delta", None) + + if delta and delta % dt.timedelta(days=1) != dt.timedelta(days=0): + return False + # error: Argument 1 to "is_dates_only" has incompatible type # "Union[ExtensionArray, ndarray]"; expected "Union[ndarray, # DatetimeArray, Index, DatetimeIndex]" + return self.tz is None and is_dates_only(self._values) # type: ignore[arg-type] def __reduce__(self): diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py index a927799e39783..cb3e0179bf46c 100644 --- a/pandas/tests/indexes/datetimes/test_formats.py +++ b/pandas/tests/indexes/datetimes/test_formats.py @@ -68,6 +68,36 @@ def test_dti_repr_short(self): dr = pd.date_range(start="1/1/2012", periods=3) repr(dr) + @pytest.mark.parametrize( + "dates, freq, expected_repr", + [ + ( + ["2012-01-01 00:00:00"], + "60T", + ( + "DatetimeIndex(['2012-01-01 00:00:00'], " + "dtype='datetime64[ns]', freq='60T')" + ), + ), + ( + ["2012-01-01 00:00:00", "2012-01-01 01:00:00"], + "60T", + "DatetimeIndex(['2012-01-01 00:00:00', '2012-01-01 01:00:00'], " + "dtype='datetime64[ns]', freq='60T')", + ), + ( + ["2012-01-01"], + "24H", + "DatetimeIndex(['2012-01-01'], dtype='datetime64[ns]', freq='24H')", + ), + ], + ) + def test_dti_repr_time_midnight(self, dates, freq, expected_repr): + # GH53634 + dti = DatetimeIndex(dates, freq) + actual_repr = repr(dti) + assert actual_repr == expected_repr + @pytest.mark.parametrize("method", ["__repr__", "__str__"]) def test_dti_representation(self, method): idxs = []
- [x] closes #53470 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Slightly modified `_is_dates_only` in `DatetimeIndex` as mentioned in the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/53634
2023-06-13T01:25:45Z
2023-07-22T20:30:48Z
2023-07-22T20:30:48Z
2023-07-22T20:30:55Z
DOC: pd.Period and pd.period_range should document that they accept datetime, date and pd.Timestamp
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 2ec0649110948..e7b93f9f67cfe 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2664,6 +2664,7 @@ class Period(_Period): One of pandas period strings or corresponding objects. Accepted strings are listed in the :ref:`offset alias section <timeseries.offset_aliases>` in the user docs. + If value is datetime, freq is required. ordinal : int, default None The period offset from the proleptic Gregorian epoch. year : int, default None diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index f40d63c8b8128..fd7cab0344e42 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -478,7 +478,7 @@ def period_range( ---------- start : str, datetime, date, pandas.Timestamp, or period-like, default None Left bound for generating periods. - end : str or period-like, default None + end : str, datetime, date, pandas.Timestamp, or period-like, default None Right bound for generating periods. periods : int, default None Number of periods to generate.
NOTE: This is a follow up to PR #53611 as I realised the issue was incompletely addressed there - [x] closes #53038 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53632
2023-06-12T23:26:07Z
2023-06-23T15:31:24Z
2023-06-23T15:31:24Z
2023-07-02T08:37:20Z
DOC: Added links to GitHub tutorials/resources for Forking Workflow in contributing.rst
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index ea69f0b907d8b..4b9a6ba1e069c 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -119,6 +119,22 @@ Some great resources for learning Git: * the `NumPy documentation <https://numpy.org/doc/stable/dev/index.html>`_. * Matthew Brett's `Pydagogue <https://matthew-brett.github.io/pydagogue/>`_. +Also, the project follows a forking workflow further described on this page whereby +contributors fork the repository, make changes and then create a pull request. +So please be sure to read and follow all the instructions in this guide. + +If you are new to contributing to projects through forking on GitHub, +take a look at the `GitHub documentation for contributing to projects <https://docs.github.com/en/get-started/quickstart/contributing-to-projects>`_. +GitHub provides a quick tutorial using a test repository that may help you become more familiar +with forking a repository, cloning a fork, creating a feature branch, pushing changes and +making pull requests. + +Below are some useful resources for learning more about forking and pull requests on GitHub: + +* the `GitHub documentation for forking a repo <https://docs.github.com/en/get-started/quickstart/fork-a-repo>`_. +* the `GitHub documentation for collaborating with pull requests <https://docs.github.com/en/pull-requests/collaborating-with-pull-requests>`_. +* the `GitHub documentation for working with forks <https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks>`_. + Getting started with Git ------------------------
- [x] closes #53626 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. In the **contributing.rst file**, I have added information/navigation links to the GitHub documentation and tutorials for: 1) contributing to projects 2) forking a repo 3) collaborating with pull requests 4) working with forks I added the updates to the _'Version control, Git and GitHub'_ section as the updates address GitHub workflows. I wanted to provide this information to aid new pandas contributors unsure of GitHub's forking process. I found these resources to be very helpful references when reviewing the contributing guide. Attaching a screenshot below of my local build with the changes (bordered in red). <img width="511" alt="contributing rst GitHub tutorial links" src="https://github.com/pandas-dev/pandas/assets/87046544/ce8c04c4-4f98-4a77-a251-58fd10469b71">
https://api.github.com/repos/pandas-dev/pandas/pulls/53628
2023-06-12T21:02:39Z
2023-06-13T17:17:49Z
2023-06-13T17:17:49Z
2023-06-13T17:17:57Z
TYP: core.missing
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 16e7835a7183d..269b7a086de93 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -769,7 +769,12 @@ def fillna( ) new_values = np.asarray(self) # interpolate_2d modifies new_values inplace - interpolate_2d(new_values, method=method, limit=limit) + # error: Argument "method" to "interpolate_2d" has incompatible type + # "Literal['backfill', 'bfill', 'ffill', 'pad']"; expected + # "Literal['pad', 'backfill']" + interpolate_2d( + new_values, method=method, limit=limit # type: ignore[arg-type] + ) return type(self)(new_values, fill_value=self.fill_value) else: diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 0766b9c5c7145..8b6b6a2c2a07b 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -10,6 +10,7 @@ from typing import ( TYPE_CHECKING, Any, + Literal, cast, ) @@ -22,7 +23,6 @@ ) from pandas._typing import ( ArrayLike, - Axis, AxisInt, F, ReindexMethod, @@ -223,6 +223,35 @@ def find_valid_index(how: str, is_valid: npt.NDArray[np.bool_]) -> int | None: return idxpos # type: ignore[return-value] +def validate_limit_direction( + limit_direction: str, +) -> Literal["forward", "backward", "both"]: + valid_limit_directions = ["forward", "backward", "both"] + limit_direction = limit_direction.lower() + if limit_direction not in valid_limit_directions: + raise ValueError( + "Invalid limit_direction: expecting one of " + f"{valid_limit_directions}, got '{limit_direction}'." + ) + # error: Incompatible return value type (got "str", expected + # "Literal['forward', 'backward', 'both']") + return limit_direction # type: ignore[return-value] + + +def validate_limit_area(limit_area: str | None) -> Literal["inside", "outside"] | None: + if limit_area is not None: + valid_limit_areas = ["inside", "outside"] + limit_area = limit_area.lower() + if limit_area not in valid_limit_areas: + raise ValueError( + f"Invalid limit_area: expecting one of {valid_limit_areas}, got " + f"{limit_area}." + ) + # error: Incompatible return value type (got "Optional[str]", expected + # "Optional[Literal['inside', 'outside']]") + return limit_area # type: ignore[return-value] + + def infer_limit_direction(limit_direction, method): # Set `limit_direction` depending on `method` if limit_direction is None: @@ -308,7 +337,9 @@ def interpolate_array_2d( method=m, axis=axis, limit=limit, - limit_area=limit_area, + # error: Argument "limit_area" to "interpolate_2d" has incompatible + # type "Optional[str]"; expected "Optional[Literal['inside', 'outside']]" + limit_area=limit_area, # type: ignore[arg-type] ) else: assert index is not None # for mypy @@ -362,22 +393,8 @@ def _interpolate_2d_with_fill( ) method = "values" - valid_limit_directions = ["forward", "backward", "both"] - limit_direction = limit_direction.lower() - if limit_direction not in valid_limit_directions: - raise ValueError( - "Invalid limit_direction: expecting one of " - f"{valid_limit_directions}, got '{limit_direction}'." - ) - - if limit_area is not None: - valid_limit_areas = ["inside", "outside"] - limit_area = limit_area.lower() - if limit_area not in valid_limit_areas: - raise ValueError( - f"Invalid limit_area: expecting one of {valid_limit_areas}, got " - f"{limit_area}." - ) + limit_direction = validate_limit_direction(limit_direction) + limit_area_validated = validate_limit_area(limit_area) # default limit is unlimited GH #16282 limit = algos.validate_limit(nobs=None, limit=limit) @@ -393,7 +410,7 @@ def func(yvalues: np.ndarray) -> None: method=method, limit=limit, limit_direction=limit_direction, - limit_area=limit_area, + limit_area=limit_area_validated, fill_value=fill_value, bounds_error=False, **kwargs, @@ -433,10 +450,10 @@ def _index_to_interp_indices(index: Index, method: str) -> np.ndarray: def _interpolate_1d( indices: np.ndarray, yvalues: np.ndarray, - method: str | None = "linear", + method: str = "linear", limit: int | None = None, limit_direction: str = "forward", - limit_area: str | None = None, + limit_area: Literal["inside", "outside"] | None = None, fill_value: Any | None = None, bounds_error: bool = False, order: int | None = None, @@ -539,10 +556,10 @@ def _interpolate_1d( def _interpolate_scipy_wrapper( - x, - y, - new_x, - method, + x: np.ndarray, + y: np.ndarray, + new_x: np.ndarray, + method: str, fill_value=None, bounds_error: bool = False, order=None, @@ -565,19 +582,11 @@ def _interpolate_scipy_wrapper( "krogh": interpolate.krogh_interpolate, "from_derivatives": _from_derivatives, "piecewise_polynomial": _from_derivatives, + "cubicspline": _cubicspline_interpolate, + "akima": _akima_interpolate, + "pchip": interpolate.pchip_interpolate, } - if getattr(x, "_is_all_dates", False): - # GH 5975, scipy.interp1d can't handle datetime64s - x, new_x = x._values.astype("i8"), new_x.astype("i8") - - if method == "pchip": - alt_methods["pchip"] = interpolate.pchip_interpolate - elif method == "akima": - alt_methods["akima"] = _akima_interpolate - elif method == "cubicspline": - alt_methods["cubicspline"] = _cubicspline_interpolate - interp1d_methods = [ "nearest", "zero", @@ -588,9 +597,11 @@ def _interpolate_scipy_wrapper( ] if method in interp1d_methods: if method == "polynomial": - method = order + kind = order + else: + kind = method terp = interpolate.interp1d( - x, y, kind=method, fill_value=fill_value, bounds_error=bounds_error + x, y, kind=kind, fill_value=fill_value, bounds_error=bounds_error ) new_y = terp(new_x) elif method == "spline": @@ -610,13 +621,18 @@ def _interpolate_scipy_wrapper( y = y.copy() if not new_x.flags.writeable: new_x = new_x.copy() - method = alt_methods[method] - new_y = method(x, y, new_x, **kwargs) + terp = alt_methods[method] + new_y = terp(x, y, new_x, **kwargs) return new_y def _from_derivatives( - xi, yi, x, order=None, der: int | list[int] | None = 0, extrapolate: bool = False + xi: np.ndarray, + yi: np.ndarray, + x: np.ndarray, + order=None, + der: int | list[int] | None = 0, + extrapolate: bool = False, ): """ Convenience function for interpolate.BPoly.from_derivatives. @@ -660,7 +676,13 @@ def _from_derivatives( return m(x) -def _akima_interpolate(xi, yi, x, der: int | list[int] | None = 0, axis: AxisInt = 0): +def _akima_interpolate( + xi: np.ndarray, + yi: np.ndarray, + x: np.ndarray, + der: int | list[int] | None = 0, + axis: AxisInt = 0, +): """ Convenience function for akima interpolation. xi and yi are arrays of values used to approximate some function f, @@ -670,13 +692,13 @@ def _akima_interpolate(xi, yi, x, der: int | list[int] | None = 0, axis: AxisInt Parameters ---------- - xi : array-like + xi : np.ndarray A sorted list of x-coordinates, of length N. - yi : array-like + yi : np.ndarray A 1-D array of real values. `yi`'s length along the interpolation axis must be equal to the length of `xi`. If N-D array, use axis parameter to select correct axis. - x : scalar or array-like + x : np.ndarray Of length M. der : int, optional How many derivatives to extract; None for all potentially @@ -704,9 +726,9 @@ def _akima_interpolate(xi, yi, x, der: int | list[int] | None = 0, axis: AxisInt def _cubicspline_interpolate( - xi, - yi, - x, + xi: np.ndarray, + yi: np.ndarray, + x: np.ndarray, axis: AxisInt = 0, bc_type: str | tuple[Any, Any] = "not-a-knot", extrapolate=None, @@ -718,14 +740,14 @@ def _cubicspline_interpolate( Parameters ---------- - xi : array-like, shape (n,) + xi : np.ndarray, shape (n,) 1-d array containing values of the independent variable. Values must be real, finite and in strictly increasing order. - yi : array-like + yi : np.ndarray Array containing values of the dependent variable. It can have arbitrary number of dimensions, but the length along ``axis`` (see below) must match the length of ``x``. Values must be finite. - x : scalar or array-like, shape (m,) + x : np.ndarray, shape (m,) axis : int, optional Axis along which `y` is assumed to be varying. Meaning that for ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``. @@ -790,7 +812,10 @@ def _cubicspline_interpolate( def _interpolate_with_limit_area( - values: np.ndarray, method: str, limit: int | None, limit_area: str | None + values: np.ndarray, + method: Literal["pad", "backfill"], + limit: int | None, + limit_area: Literal["inside", "outside"], ) -> None: """ Apply interpolation and limit_area logic to values along a to-be-specified axis. @@ -803,8 +828,8 @@ def _interpolate_with_limit_area( Interpolation method. Could be "bfill" or "pad" limit: int, optional Index limit on interpolation. - limit_area: str - Limit area for interpolation. Can be "inside" or "outside" + limit_area: {'inside', 'outside'} + Limit area for interpolation. Notes ----- @@ -832,16 +857,18 @@ def _interpolate_with_limit_area( invalid[first : last + 1] = False elif limit_area == "outside": invalid[:first] = invalid[last + 1 :] = False + else: + raise ValueError("limit_area should be 'inside' or 'outside'") values[invalid] = np.nan def interpolate_2d( values: np.ndarray, - method: str = "pad", - axis: Axis = 0, + method: Literal["pad", "backfill"] = "pad", + axis: AxisInt = 0, limit: int | None = None, - limit_area: str | None = None, + limit_area: Literal["inside", "outside"] | None = None, ) -> None: """ Perform an actual interpolation of values, values will be make 2-d if @@ -880,9 +907,7 @@ def interpolate_2d( limit=limit, limit_area=limit_area, ), - # error: Argument 2 to "apply_along_axis" has incompatible type - # "Union[str, int]"; expected "SupportsIndex" - axis, # type: ignore[arg-type] + axis, values, ) return @@ -898,12 +923,9 @@ def interpolate_2d( method = clean_fill_method(method) tvalues = transf(values) + func = get_fill_func(method, ndim=2) # _pad_2d and _backfill_2d both modify tvalues inplace - if method == "pad": - _pad_2d(tvalues, limit=limit) - else: - _backfill_2d(tvalues, limit=limit) - + func(tvalues, limit=limit) return @@ -969,7 +991,7 @@ def _pad_2d( ): mask = _fillna_prep(values, mask) - if np.all(values.shape): + if values.size: algos.pad_2d_inplace(values, mask, limit=limit) else: # for test coverage @@ -983,7 +1005,7 @@ def _backfill_2d( ): mask = _fillna_prep(values, mask) - if np.all(values.shape): + if values.size: algos.backfill_2d_inplace(values, mask, limit=limit) else: # for test coverage @@ -1007,7 +1029,9 @@ def clean_reindex_fill_method(method) -> ReindexMethod | None: return clean_fill_method(method, allow_nearest=True) -def _interp_limit(invalid: npt.NDArray[np.bool_], fw_limit, bw_limit): +def _interp_limit( + invalid: npt.NDArray[np.bool_], fw_limit: int | None, bw_limit: int | None +): """ Get indexers of values that won't be filled because they exceed the limits.
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53625
2023-06-12T20:26:01Z
2023-06-14T17:11:11Z
2023-06-14T17:11:11Z
2023-06-14T17:14:48Z
BUG: groupby sum turning `inf+inf` and `(-inf)+(-inf)` into `nan`
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index ba5334b2f4fa8..bdd83e2adefd6 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -458,8 +458,9 @@ Groupby/resample/rolling - Bug in :meth:`GroupBy.groups` with a datetime key in conjunction with another key produced incorrect number of group keys (:issue:`51158`) - Bug in :meth:`GroupBy.quantile` may implicitly sort the result index with ``sort=False`` (:issue:`53009`) - Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64, timedelta64 or :class:`PeriodDtype` values (:issue:`52128`, :issue:`53045`) -- Bug in :meth:`SeriresGroupBy.nth` and :meth:`DataFrameGroupBy.nth` after performing column selection when using ``dropna="any"`` or ``dropna="all"`` would not subset columns (:issue:`53518`) -- Bug in :meth:`SeriresGroupBy.nth` and :meth:`DataFrameGroupBy.nth` raised after performing column selection when using ``dropna="any"`` or ``dropna="all"`` resulted in rows being dropped (:issue:`53518`) +- Bug in :meth:`SeriesGroupBy.nth` and :meth:`DataFrameGroupBy.nth` after performing column selection when using ``dropna="any"`` or ``dropna="all"`` would not subset columns (:issue:`53518`) +- Bug in :meth:`SeriesGroupBy.nth` and :meth:`DataFrameGroupBy.nth` raised after performing column selection when using ``dropna="any"`` or ``dropna="all"`` resulted in rows being dropped (:issue:`53518`) +- Bug in :meth:`SeriesGroupBy.sum` and :meth:`DataFrameGroupby.sum` summing ``np.inf + np.inf`` and ``(-np.inf) + (-np.inf)`` to ``np.nan`` (:issue:`53606`) Reshaping ^^^^^^^^^ diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 61f448cbe0c3f..0baae23a4a71c 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -746,6 +746,13 @@ def group_sum( y = val - compensation[lab, j] t = sumx[lab, j] + y compensation[lab, j] = t - sumx[lab, j] - y + if compensation[lab, j] != compensation[lab, j]: + # GH#53606 + # If val is +/- infinity compensation is NaN + # which would lead to results being NaN instead + # of +/- infinity. We cannot use util.is_nan + # because of no gil + compensation[lab, j] = 0 sumx[lab, j] = t _check_below_mincount( diff --git a/pandas/tests/groupby/test_libgroupby.py b/pandas/tests/groupby/test_libgroupby.py index d10bcf9053d1a..92c3b68d87fad 100644 --- a/pandas/tests/groupby/test_libgroupby.py +++ b/pandas/tests/groupby/test_libgroupby.py @@ -6,6 +6,7 @@ group_cumprod, group_cumsum, group_mean, + group_sum, group_var, ) @@ -302,3 +303,29 @@ def test_cython_group_mean_Inf_at_begining_and_end(): actual, expected, ) + + +@pytest.mark.parametrize( + "values, out", + [ + ([[np.inf], [np.inf], [np.inf]], [[np.inf], [np.inf]]), + ([[np.inf], [np.inf], [-np.inf]], [[np.inf], [np.nan]]), + ([[np.inf], [-np.inf], [np.inf]], [[np.inf], [np.nan]]), + ([[np.inf], [-np.inf], [-np.inf]], [[np.inf], [-np.inf]]), + ], +) +def test_cython_group_sum_Inf_at_begining_and_end(values, out): + # GH #53606 + actual = np.array([[np.nan], [np.nan]], dtype="float64") + counts = np.array([0, 0], dtype="int64") + data = np.array(values, dtype="float64") + labels = np.array([0, 1, 1], dtype=np.intp) + + group_sum(actual, counts, data, labels, None, is_datetimelike=False) + + expected = np.array(out, dtype="float64") + + tm.assert_numpy_array_equal( + actual, + expected, + )
- [x] Closes #53606 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file This modifies `group_sum` in almost the way as #52964 for `group_mean`.
https://api.github.com/repos/pandas-dev/pandas/pulls/53623
2023-06-12T17:10:23Z
2023-06-14T02:53:13Z
2023-06-14T02:53:13Z
2023-06-28T05:40:57Z
BUG: clean_fill_method failing to raise
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index baacc8c421414..13ba53682144f 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -502,9 +502,11 @@ Other - Bug in :func:`assert_almost_equal` now throwing assertion error for two unequal sets (:issue:`51727`) - Bug in :func:`assert_frame_equal` checks category dtypes even when asked not to check index type (:issue:`52126`) - Bug in :meth:`DataFrame.reindex` with a ``fill_value`` that should be inferred with a :class:`ExtensionDtype` incorrectly inferring ``object`` dtype (:issue:`52586`) +- Bug in :meth:`Series.align`, :meth:`DataFrame.align`, :meth:`Series.reindex`, :meth:`DataFrame.reindex`, :meth:`Series.interpolate`, :meth:`DataFrame.interpolate`, incorrectly failing to raise with method="asfreq" (:issue:`53620`) - Bug in :meth:`Series.map` when giving a callable to an empty series, the returned series had ``object`` dtype. It now keeps the original dtype (:issue:`52384`) - Bug in :meth:`Series.memory_usage` when ``deep=True`` throw an error with Series of objects and the returned value is incorrect, as it does not take into account GC corrections (:issue:`51858`) - Fixed incorrect ``__name__`` attribute of ``pandas._libs.json`` (:issue:`52898`) +- .. ***DO NOT USE THIS SECTION*** diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f73ef36f76086..0c0f1a332c691 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9735,7 +9735,9 @@ def align( method = None if limit is lib.no_default: limit = None - method = clean_fill_method(method) + + if method is not None: + method = clean_fill_method(method) if broadcast_axis is not lib.no_default: # GH#51856 diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 7c5d686d96939..3139f5bc06a00 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1369,6 +1369,12 @@ def interpolate( m = missing.clean_fill_method(method) except ValueError: m = None + # error: Non-overlapping equality check (left operand type: + # "Literal['backfill', 'bfill', 'ffill', 'pad']", right + # operand type: "Literal['asfreq']") + if method == "asfreq": # type: ignore[comparison-overlap] + # clean_fill_method used to allow this + raise if m is None and self.dtype.kind != "f": # only deal with floats # bc we already checked that can_hold_na, we don't have int dtype here diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 7762ba8e2c730..f38a38eee9a62 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -122,11 +122,7 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]: return mask -def clean_fill_method(method: str | None, allow_nearest: bool = False): - # asfreq is compat for resampling - if method in [None, "asfreq"]: - return None - +def clean_fill_method(method: str, allow_nearest: bool = False): if isinstance(method, str): method = method.lower() if method == "ffill": @@ -954,6 +950,8 @@ def get_fill_func(method, ndim: int = 1): def clean_reindex_fill_method(method) -> ReindexMethod | None: + if method is None: + return None return clean_fill_method(method, allow_nearest=True) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 8291162db0834..a9faad4cbef6a 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1506,6 +1506,8 @@ def _upsample(self, method, limit: int | None = None, fill_value=None): result = obj.copy() result.index = res_index else: + if method == "asfreq": + method = None result = obj.reindex( res_index, method=method, limit=limit, fill_value=fill_value ) @@ -1624,6 +1626,8 @@ def _upsample(self, method, limit: int | None = None, fill_value=None): memb = ax.asfreq(self.freq, how=self.convention) # Get the fill indexer + if method == "asfreq": + method = None indexer = memb.get_indexer(new_index, method=method, limit=limit) new_obj = _take_new_index( obj, diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index 576d3a9cdedde..2db9b8cd0ea0d 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -108,7 +108,7 @@ def test_interpolate_cleaned_fill_method(using_copy_on_write): df = DataFrame({"a": ["a", np.nan, "c"], "b": 1}) df_orig = df.copy() - result = df.interpolate(method="asfreq") + result = df.interpolate(method="linear") if using_copy_on_write: assert np.shares_memory(get_array(result, "a"), get_array(df, "a")) diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py index 1dabc95a0f6f4..e56d542972e63 100644 --- a/pandas/tests/frame/methods/test_align.py +++ b/pandas/tests/frame/methods/test_align.py @@ -14,6 +14,14 @@ class TestDataFrameAlign: + def test_align_asfreq_method_raises(self): + df = DataFrame({"A": [1, np.nan, 2]}) + msg = "Invalid fill method" + msg2 = "The 'method', 'limit', and 'fill_axis' keywords" + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=msg2): + df.align(df.iloc[::-1], method="asfreq") + def test_frame_align_aware(self): idx1 = date_range("2001", periods=5, freq="H", tz="US/Eastern") idx2 = date_range("2001", periods=5, freq="2H", tz="US/Eastern") diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index e8cebd5964236..63e2eb790a4ea 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -1291,3 +1291,10 @@ def test_reindex_not_category(self, index_df, index_res, index_exp): result = df.reindex(index=index_res) expected = DataFrame(index=index_exp) tm.assert_frame_equal(result, expected) + + def test_invalid_method(self): + df = DataFrame({"A": [1, np.nan, 2]}) + + msg = "Invalid fill method" + with pytest.raises(ValueError, match=msg): + df.reindex([1, 0, 2], method="asfreq") diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index 6f4c4ba4dd69d..1b0a28f3940cc 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -821,3 +821,9 @@ 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_afreq_raises(self): + ser = Series(["a", None, "b"], dtype=object) + msg = "Invalid fill method" + with pytest.raises(ValueError, match=msg): + ser.interpolate(method="asfreq")
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53620
2023-06-12T15:54:20Z
2023-06-12T23:52:28Z
2023-06-12T23:52:28Z
2023-06-12T23:55:18Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 3ddb9d4ff6d54..adda422296396 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -105,8 +105,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.errors.UnsupportedFunctionCall \ pandas.test \ pandas.NaT \ - pandas.Timestamp.as_unit \ - pandas.Timestamp.ctime \ pandas.Timestamp.date \ pandas.Timestamp.dst \ pandas.Timestamp.isocalendar \ diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index ff07f5d799339..ea859a5f7d53d 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -501,7 +501,6 @@ class NaTType(_NaT): timetuple = _make_error_func("timetuple", datetime) isocalendar = _make_error_func("isocalendar", datetime) dst = _make_error_func("dst", datetime) - ctime = _make_error_func("ctime", datetime) time = _make_error_func("time", datetime) toordinal = _make_error_func("toordinal", datetime) tzname = _make_error_func("tzname", datetime) @@ -514,6 +513,21 @@ class NaTType(_NaT): # The remaining methods have docstrings copy/pasted from the analogous # Timestamp methods. + ctime = _make_error_func( + "ctime", + """ + Return ctime() style string. + + Examples + -------- + >>> ts = pd.Timestamp('2023-01-01 10:00:00.00') + >>> ts + Timestamp('2023-01-01 10:00:00') + >>> ts.ctime() + 'Sun Jan 1 10:00:00 2023' + """, + ) + strftime = _make_error_func( "strftime", """ @@ -1210,6 +1224,19 @@ default 'raise' Returns ------- Timestamp + + Examples + -------- + >>> ts = pd.Timestamp('2023-01-01 00:00:00.01') + >>> ts + Timestamp('2023-01-01 00:00:00.010000') + >>> ts.unit + 'ms' + >>> ts = ts.as_unit('s') + >>> ts + Timestamp('2023-01-01 00:00:00') + >>> ts.unit + 's' """ return c_NaT diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 4f09c0953f3d2..d66e856ef77cf 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1122,6 +1122,19 @@ cdef class _Timestamp(ABCTimestamp): Returns ------- Timestamp + + Examples + -------- + >>> ts = pd.Timestamp('2023-01-01 00:00:00.01') + >>> ts + Timestamp('2023-01-01 00:00:00.010000') + >>> ts.unit + 'ms' + >>> ts = ts.as_unit('s') + >>> ts + Timestamp('2023-01-01 00:00:00') + >>> ts.unit + 's' """ dtype = np.dtype(f"M8[{unit}]") reso = get_unit_from_dtype(dtype) @@ -1493,6 +1506,31 @@ class Timestamp(_Timestamp): ) from err return _dt.strftime(format) + def ctime(self): + """ + Return ctime() style string. + + Examples + -------- + >>> ts = pd.Timestamp('2023-01-01 10:00:00.00') + >>> ts + Timestamp('2023-01-01 10:00:00') + >>> ts.ctime() + 'Sun Jan 1 10:00:00 2023' + """ + try: + _dt = datetime(self.year, self.month, self.day, + self.hour, self.minute, self.second, + self.microsecond, self.tzinfo, fold=self.fold) + except ValueError as err: + raise NotImplementedError( + "ctime not yet supported on Timestamps which " + "are outside the range of Python's standard library. " + "For now, please call the components you need (such as `.year` " + "and `.month`) and construct your string from there." + ) from err + return _dt.ctime() + # Issue 25016. @classmethod def strptime(cls, date_string, format): diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 8296201345d2f..6f163b7ecd89d 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -491,7 +491,7 @@ def test_nat_arithmetic_ndarray(dtype, op, out_dtype): def test_nat_pinned_docstrings(): # see gh-17327 - assert NaT.ctime.__doc__ == datetime.ctime.__doc__ + assert NaT.ctime.__doc__ == Timestamp.ctime.__doc__ def test_to_numpy_alias():
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53619
2023-06-12T14:36:53Z
2023-06-12T16:51:11Z
2023-06-12T16:51:11Z
2023-06-13T07:29:41Z
Bump pypa/cibuildwheel from 2.13.0 to 2.13.1
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index cdc4fd18995da..ea5ab81e74030 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -110,7 +110,7 @@ jobs: path: ./dist - name: Build wheels - uses: pypa/cibuildwheel@v2.13.0 + uses: pypa/cibuildwheel@v2.13.1 with: package-dir: ./dist/${{ needs.build_sdist.outputs.sdist_file }} env:
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.13.0 to 2.13.1. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/pypa/cibuildwheel/releases">pypa/cibuildwheel's releases</a>.</em></p> <blockquote> <h2>v2.13.1</h2> <ul> <li>🛠 Updates the prerelease CPython 3.12 version to 3.12.0b2. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/1516">#1516</a>)</li> <li>🛠 Adds a moving <code>v&lt;major&gt;.&lt;minor&gt;</code> tag for use in GitHub Actions workflow files. If you use this, you'll get the latest patch release within a minor version. Additionally, Dependabot won't send you PRs for patch releases. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/1517">#1517</a>)</li> </ul> </blockquote> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md">pypa/cibuildwheel's changelog</a>.</em></p> <blockquote> <h3>v2.13.1</h3> <p><em>10 June 2023</em></p> <ul> <li>🛠 Updates the prerelease CPython 3.12 version to 3.12.0b2. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/1516">#1516</a>)</li> <li>🛠 Adds a moving <code>v&lt;major&gt;.&lt;minor&gt;</code> tag for use in GitHub Actions workflow files. If you use this, you'll get the latest patch release within a minor version. Additionally, Dependabot won't send you PRs for patch releases. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/1517">#1517</a>)</li> </ul> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/pypa/cibuildwheel/commit/0ecddd92b62987d7a2ae8911f4bb8ec9e2e4496a"><code>0ecddd9</code></a> Bump version: v2.13.1</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/f35d309173dfc5359b18ca3d2c9c422e4cf83abb"><code>f35d309</code></a> Merge pull request <a href="https://redirect.github.com/pypa/cibuildwheel/issues/1517">#1517</a> from pypa/major-dot-minor-tag</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/3160e8dbca733f3125ba9fcf5cf6b0007cdaca73"><code>3160e8d</code></a> Merge pull request <a href="https://redirect.github.com/pypa/cibuildwheel/issues/1516">#1516</a> from pypa/update-dependencies-pr</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/012ae48172b00cfbfad05e1a3fa6d0af04bc0d7b"><code>012ae48</code></a> Add workflow that updates a vX.Y tag on release</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/1c3b8e112e9ceccee1712627b5377213672ae155"><code>1c3b8e1</code></a> Update dependencies</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/ca7b0f75c61a9efc6dd42d7c0600f347df8ca5e0"><code>ca7b0f7</code></a> Merge pull request <a href="https://redirect.github.com/pypa/cibuildwheel/issues/1514">#1514</a> from pypa/fix-travis-windows</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/8d126bc281ea9d9e62e37ec7f604fcd2157044a0"><code>8d126bc</code></a> Try removing the offending line</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/2ca5ff2dcdd0bfc0d558906b2ae20e74b9c5cb51"><code>2ca5ff2</code></a> Merge pull request <a href="https://redirect.github.com/pypa/cibuildwheel/issues/1508">#1508</a> from pypa/update-dependencies-pr</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/7d45cf3dace7240123635298d7429bb99fad6b92"><code>7d45cf3</code></a> Merge pull request <a href="https://redirect.github.com/pypa/cibuildwheel/issues/1511">#1511</a> from ianthomas23/doc_fix_config_settings</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/f6edc817df1b26def09c0278a72f2d097df6da23"><code>f6edc81</code></a> Merge pull request <a href="https://redirect.github.com/pypa/cibuildwheel/issues/1512">#1512</a> from pypa/pre-commit-ci-update-config</li> <li>Additional commits viewable in <a href="https://github.com/pypa/cibuildwheel/compare/v2.13.0...v2.13.1">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=pypa/cibuildwheel&package-manager=github_actions&previous-version=2.13.0&new-version=2.13.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/pandas-dev/pandas/pulls/53614
2023-06-12T09:02:40Z
2023-06-12T16:59:12Z
2023-06-12T16:59:12Z
2023-06-12T16:59:16Z
DOC: pd.Period and pd.period_range should document that they accept datetime, date and pd.Timestamp
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 54bf041d59264..e954ec9bccd9e 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2656,7 +2656,7 @@ class Period(_Period): Parameters ---------- - value : Period or str, default None + value : Period, str, datetime, date or pandas.Timestamp, default None The time period represented (e.g., '4Q2005'). This represents neither the start or the end of the period, but rather the entire period itself. freq : str, default None diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index f693f9557ecdc..f40d63c8b8128 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -476,7 +476,7 @@ def period_range( Parameters ---------- - start : str or period-like, default None + start : str, datetime, date, pandas.Timestamp, or period-like, default None Left bound for generating periods. end : str or period-like, default None Right bound for generating periods.
- [x] closes #53038 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53611
2023-06-12T02:32:41Z
2023-06-12T17:24:54Z
2023-06-12T17:24:54Z
2023-06-12T18:08:22Z
TST: Refactor slow test
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 6d09488df06e2..beddd59b0aa14 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -536,11 +536,9 @@ def test_objects(self): assert isinstance(result, np.ndarray) def test_object_refcount_bug(self): - lst = ["A", "B", "C", "D", "E"] - msg = "unique with argument that is not not a Series" - with tm.assert_produces_warning(FutureWarning, match=msg): - for i in range(1000): - len(algos.unique(lst)) + lst = np.array(["A", "B", "C", "D", "E"], dtype=object) + for i in range(1000): + len(algos.unique(lst)) def test_on_index_object(self): mindex = MultiIndex.from_arrays(
Went from 2s to 0.05s locally
https://api.github.com/repos/pandas-dev/pandas/pulls/53610
2023-06-12T02:29:03Z
2023-06-13T17:25:02Z
2023-06-13T17:25:02Z
2023-06-13T17:25:05Z
TST: Mark numba & threading tests as single cpu
diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index d585cc1648c5a..10ed32a334d18 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -13,6 +13,8 @@ ) import pandas._testing as tm +pytestmark = pytest.mark.single_cpu + @td.skip_if_no("numba") def test_correct_function_signature(): diff --git a/pandas/tests/groupby/test_numba.py b/pandas/tests/groupby/test_numba.py index 4eb7b6a7b5bea..867bdbf583388 100644 --- a/pandas/tests/groupby/test_numba.py +++ b/pandas/tests/groupby/test_numba.py @@ -8,6 +8,8 @@ ) import pandas._testing as tm +pytestmark = pytest.mark.single_cpu + @td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore") diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index 00ff391199652..557e132567a2e 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -11,6 +11,8 @@ ) import pandas._testing as tm +pytestmark = pytest.mark.single_cpu + @td.skip_if_no("numba") def test_correct_function_signature(): diff --git a/pandas/tests/io/parser/test_multi_thread.py b/pandas/tests/io/parser/test_multi_thread.py index ab278470934a5..562b99090dfab 100644 --- a/pandas/tests/io/parser/test_multi_thread.py +++ b/pandas/tests/io/parser/test_multi_thread.py @@ -15,7 +15,11 @@ # We'll probably always skip these for pyarrow # Maybe we'll add our own tests for pyarrow too -pytestmark = pytest.mark.usefixtures("pyarrow_skip") +pytestmark = [ + pytest.mark.single_cpu, + pytest.mark.slow, + pytest.mark.usefixtures("pyarrow_skip"), +] def _construct_dataframe(num_rows): @@ -40,7 +44,6 @@ def _construct_dataframe(num_rows): return df -@pytest.mark.slow def test_multi_thread_string_io_read_csv(all_parsers): # see gh-11786 parser = all_parsers @@ -135,7 +138,6 @@ def reader(arg): return final_dataframe -@pytest.mark.slow def test_multi_thread_path_multipart_read_csv(all_parsers): # see gh-11786 num_tasks = 4 diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py index bb95762950d8e..b227c935c2b62 100644 --- a/pandas/tests/io/pytables/test_categorical.py +++ b/pandas/tests/io/pytables/test_categorical.py @@ -14,9 +14,7 @@ ensure_clean_store, ) -pytestmark = [ - pytest.mark.single_cpu, -] +pytestmark = pytest.mark.single_cpu def test_categorical(setup_path): diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index e54a23b1f8ef6..5c6c33de5ac5f 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -1347,6 +1347,7 @@ def __iter__(self) -> Iterator: assert self.read_html(bad) @pytest.mark.slow + @pytest.mark.single_cpu def test_importcheck_thread_safety(self, datapath): # see gh-16928 diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py index 06051a81679fa..b9d3a20b2ecea 100644 --- a/pandas/tests/io/test_user_agent.py +++ b/pandas/tests/io/test_user_agent.py @@ -17,10 +17,13 @@ import pandas as pd import pandas._testing as tm -pytestmark = pytest.mark.skipif( - is_ci_environment(), - reason="GH 45651: This test can hang in our CI min_versions build", -) +pytestmark = [ + pytest.mark.single_cpu, + pytest.mark.skipif( + is_ci_environment(), + reason="GH 45651: This test can hang in our CI min_versions build", + ), +] class BaseUserAgentResponder(http.server.BaseHTTPRequestHandler): diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index dbafcf12513e0..f5ef6a00e0b32 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -17,13 +17,15 @@ ) import pandas._testing as tm -# TODO(GH#44584): Mark these as pytest.mark.single_cpu -pytestmark = pytest.mark.skipif( - is_ci_environment() and (is_platform_windows() or is_platform_mac()), - reason="On GHA CI, Windows can fail with " - "'Windows fatal exception: stack overflow' " - "and macOS can timeout", -) +pytestmark = [ + pytest.mark.single_cpu, + pytest.mark.skipif( + is_ci_environment() and (is_platform_windows() or is_platform_mac()), + reason="On GHA CI, Windows can fail with " + "'Windows fatal exception: stack overflow' " + "and macOS can timeout", + ), +] @pytest.fixture(params=["single", "table"]) diff --git a/pandas/tests/window/test_online.py b/pandas/tests/window/test_online.py index 875adf6cef4ac..5974de0ae4009 100644 --- a/pandas/tests/window/test_online.py +++ b/pandas/tests/window/test_online.py @@ -14,13 +14,15 @@ ) import pandas._testing as tm -# TODO(GH#44584): Mark these as pytest.mark.single_cpu -pytestmark = pytest.mark.skipif( - is_ci_environment() and (is_platform_windows() or is_platform_mac()), - reason="On GHA CI, Windows can fail with " - "'Windows fatal exception: stack overflow' " - "and macOS can timeout", -) +pytestmark = [ + pytest.mark.single_cpu, + pytest.mark.skipif( + is_ci_environment() and (is_platform_windows() or is_platform_mac()), + reason="On GHA CI, Windows can fail with " + "'Windows fatal exception: stack overflow' " + "and macOS can timeout", + ), +] @td.skip_if_no("numba")
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53608
2023-06-12T01:51:11Z
2023-06-12T17:17:23Z
2023-06-12T17:17:23Z
2023-06-12T17:17:28Z
DEPR: NDFrame.interpolate with ffill/bfill methods
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index baacc8c421414..0c35b0b49e4d4 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -284,6 +284,7 @@ Deprecations - Deprecated option "mode.use_inf_as_na", convert inf entries to ``NaN`` before instead (:issue:`51684`) - Deprecated positional indexing on :class:`Series` with :meth:`Series.__getitem__` and :meth:`Series.__setitem__`, in a future version ``ser[item]`` will *always* interpret ``item`` as a label, not a position (:issue:`50617`) - Deprecated the "method" and "limit" keywords on :meth:`Series.fillna`, :meth:`DataFrame.fillna`, :meth:`SeriesGroupBy.fillna`, :meth:`DataFrameGroupBy.fillna`, and :meth:`Resampler.fillna`, use ``obj.bfill()`` or ``obj.ffill()`` instead (:issue:`53394`) +- Deprecated values "pad", "ffill", "bfill", "backfill" for :meth:`Series.interpolate` and :meth:`DataFrame.interpolate`, use ``obj.ffill()`` or ``obj.bfill()`` instead (:issue:`53581`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f73ef36f76086..2296f769539c3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7806,35 +7806,6 @@ def interpolate( 3 3.0 dtype: float64 - Filling in ``NaN`` in a Series by padding, but filling at most two - consecutive ``NaN`` at a time. - - >>> s = pd.Series([np.nan, "single_one", np.nan, - ... "fill_two_more", np.nan, np.nan, np.nan, - ... 4.71, np.nan]) - >>> s - 0 NaN - 1 single_one - 2 NaN - 3 fill_two_more - 4 NaN - 5 NaN - 6 NaN - 7 4.71 - 8 NaN - dtype: object - >>> s.interpolate(method='pad', limit=2) - 0 NaN - 1 single_one - 2 single_one - 3 fill_two_more - 4 fill_two_more - 5 fill_two_more - 6 NaN - 7 4.71 - 8 4.71 - dtype: object - Filling in ``NaN`` in a Series via polynomial interpolation or splines: Both 'polynomial' and 'spline' methods require that you also specify an ``order`` (int). @@ -7899,6 +7870,17 @@ def interpolate( return None return self.copy() + if not isinstance(method, str): + raise ValueError("'method' should be a string, not None.") + elif method.lower() in fillna_methods: + # GH#53581 + warnings.warn( + f"{type(self).__name__}.interpolate with method={method} is " + "deprecated and will raise in a future version. " + "Use obj.ffill() or obj.bfill() instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) if method not in fillna_methods: axis = self._info_axis_number diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index 576d3a9cdedde..270de481b5441 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -20,7 +20,12 @@ def test_interpolate_no_op(using_copy_on_write, method): df = DataFrame({"a": [1, 2]}) df_orig = df.copy() - result = df.interpolate(method=method) + warn = None + if method == "pad": + warn = FutureWarning + msg = "DataFrame.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = df.interpolate(method=method) if using_copy_on_write: assert np.shares_memory(get_array(result, "a"), get_array(df, "a")) @@ -125,7 +130,9 @@ def test_interpolate_cleaned_fill_method(using_copy_on_write): def test_interpolate_object_convert_no_op(using_copy_on_write): df = DataFrame({"a": ["a", "b", "c"], "b": 1}) arr_a = get_array(df, "a") - df.interpolate(method="pad", inplace=True) + msg = "DataFrame.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.interpolate(method="pad", inplace=True) # Now CoW makes a copy, it should not! if using_copy_on_write: @@ -136,7 +143,9 @@ def test_interpolate_object_convert_no_op(using_copy_on_write): def test_interpolate_object_convert_copies(using_copy_on_write): df = DataFrame({"a": Series([1, 2], dtype=object), "b": 1}) arr_a = get_array(df, "a") - df.interpolate(method="pad", inplace=True) + msg = "DataFrame.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.interpolate(method="pad", inplace=True) if using_copy_on_write: assert df._mgr._has_no_reference(0) @@ -146,7 +155,9 @@ def test_interpolate_object_convert_copies(using_copy_on_write): def test_interpolate_downcast(using_copy_on_write): df = DataFrame({"a": [1, np.nan, 2.5], "b": 1}) arr_a = get_array(df, "a") - df.interpolate(method="pad", inplace=True, downcast="infer") + msg = "DataFrame.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.interpolate(method="pad", inplace=True, downcast="infer") if using_copy_on_write: assert df._mgr._has_no_reference(0) @@ -158,7 +169,9 @@ def test_interpolate_downcast_reference_triggers_copy(using_copy_on_write): df_orig = df.copy() arr_a = get_array(df, "a") view = df[:] - df.interpolate(method="pad", inplace=True, downcast="infer") + msg = "DataFrame.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.interpolate(method="pad", inplace=True, downcast="infer") if using_copy_on_write: assert df._mgr._has_no_reference(0) diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index 9eb1073f4c69c..5a3d53eb96a52 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -436,7 +436,9 @@ def test_interp_fillna_methods(self, request, axis, method, using_array_manager) ) method2 = method if method != "pad" else "ffill" expected = getattr(df, method2)(axis=axis) - result = df.interpolate(method=method, axis=axis) + msg = f"DataFrame.interpolate with method={method} is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.interpolate(method=method, axis=axis) tm.assert_frame_equal(result, expected) def test_interpolate_empty_df(self): diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index 6f4c4ba4dd69d..395206d829682 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -347,6 +347,8 @@ def test_interp_invalid_method(self, invalid_method): s = Series([1, 3, np.nan, 12, np.nan, 25]) msg = f"method must be one of.* Got '{invalid_method}' instead" + if invalid_method is None: + msg = "'method' should be a string, not None" with pytest.raises(ValueError, match=msg): s.interpolate(method=invalid_method) @@ -360,8 +362,10 @@ def test_interp_invalid_method_and_value(self): ser = Series([1, 3, np.nan, 12, np.nan, 25]) msg = "Cannot pass both fill_value and method" + msg2 = "Series.interpolate with method=pad" with pytest.raises(ValueError, match=msg): - ser.interpolate(fill_value=3, method="pad") + with tm.assert_produces_warning(FutureWarning, match=msg2): + ser.interpolate(fill_value=3, method="pad") def test_interp_limit_forward(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) @@ -470,8 +474,10 @@ def test_interp_limit_direction_raises(self, method, limit_direction, expected): s = Series([1, 2, 3]) msg = f"`limit_direction` must be '{expected}' for method `{method}`" + msg2 = "Series.interpolate with method=" with pytest.raises(ValueError, match=msg): - s.interpolate(method=method, limit_direction=limit_direction) + with tm.assert_produces_warning(FutureWarning, match=msg2): + s.interpolate(method=method, limit_direction=limit_direction) @pytest.mark.parametrize( "data, expected_data, kwargs", @@ -513,7 +519,9 @@ def test_interp_limit_area_with_pad(self, data, expected_data, kwargs): s = Series(data) expected = Series(expected_data) - result = s.interpolate(**kwargs) + msg = "Series.interpolate with method=pad" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.interpolate(**kwargs) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -546,7 +554,9 @@ def test_interp_limit_area_with_backfill(self, data, expected_data, kwargs): s = Series(data) expected = Series(expected_data) - result = s.interpolate(**kwargs) + msg = "Series.interpolate with method=bfill" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.interpolate(**kwargs) tm.assert_series_equal(result, expected) def test_interp_limit_direction(self): @@ -642,7 +652,15 @@ def test_interp_datetime64(self, method, tz_naive_fixture): df = Series( [1, np.nan, 3], index=date_range("1/1/2000", periods=3, tz=tz_naive_fixture) ) - result = df.interpolate(method=method) + warn = None if method == "nearest" else FutureWarning + msg = "Series.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = df.interpolate(method=method) + if warn is not None: + # check the "use ffill instead" is equivalent + alt = df.ffill() + tm.assert_series_equal(result, alt) + expected = Series( [1.0, 1.0, 3.0], index=date_range("1/1/2000", periods=3, tz=tz_naive_fixture), @@ -654,7 +672,13 @@ def test_interp_pad_datetime64tz_values(self): dti = date_range("2015-04-05", periods=3, tz="US/Central") ser = Series(dti) ser[1] = pd.NaT - result = ser.interpolate(method="pad") + + msg = "Series.interpolate with method=pad is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.interpolate(method="pad") + # check the "use ffill instead" is equivalent + alt = ser.ffill() + tm.assert_series_equal(result, alt) expected = Series(dti) expected[1] = expected[0]
- [x] closes #53581 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53607
2023-06-12T00:45:39Z
2023-06-12T20:44:22Z
2023-06-12T20:44:22Z
2023-12-11T23:49:03Z
DOC: Fixed inconsistencies in pandas.DataFrame.pivot_table docstring parameter descriptions
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 671924c5e9607..b411cfc4a4685 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8822,22 +8822,22 @@ def pivot(self, *, columns, index=lib.NoDefault, values=lib.NoDefault) -> DataFr values : list-like or scalar, optional Column or columns to aggregate. index : column, Grouper, array, or list of the previous - If an array is passed, it must be the same length as the data. The - list can contain any of the other types (except list). - Keys to group by on the pivot table index. If an array is passed, - it is being used as the same manner as column values. + Keys to group by on the pivot table index. If a list is passed, + it can contain any of the other types (except list). If an array is + passed, it must be the same length as the data and will be used in + the same manner as column values. columns : column, Grouper, array, or list of the previous - If an array is passed, it must be the same length as the data. The - list can contain any of the other types (except list). - Keys to group by on the pivot table column. If an array is passed, - it is being used as the same manner as column values. + Keys to group by on the pivot table column. If a list is passed, + it can contain any of the other types (except list). If an array is + passed, it must be the same length as the data and will be used in + the same manner as column values. aggfunc : function, list of functions, dict, default numpy.mean - If list of functions passed, the resulting pivot table will have + If a list of functions is passed, the resulting pivot table will have hierarchical columns whose top level are the function names - (inferred from the function objects themselves) - If dict is passed, the key is column to aggregate and value - is function or list of functions. If ``margin=True``, - aggfunc will be used to calculate the partial aggregates. + (inferred from the function objects themselves). + If a dict is passed, the key is column to aggregate and the value is + function or list of functions. If ``margin=True``, aggfunc will be + used to calculate the partial aggregates. fill_value : scalar, default None Value to replace missing values with (in the resulting pivot table, after aggregation).
- [x] closes #53351 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Updated the docstring for `pandas.DataFrame.pivot_table` as described in issue #53351
https://api.github.com/repos/pandas-dev/pandas/pulls/53605
2023-06-11T17:27:13Z
2023-06-12T17:28:58Z
2023-06-12T17:28:58Z
2023-06-27T04:59:58Z
ENH: Series.explode to support pyarrow-backed list types
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index bf1a7cd683a89..bea2ad8c7450c 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -102,6 +102,7 @@ Other enhancements - :meth:`DataFrame.stack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`) - :meth:`DataFrame.unstack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`) - :meth:`DataFrameGroupby.agg` and :meth:`DataFrameGroupby.transform` now support grouping by multiple keys when the index is not a :class:`MultiIndex` for ``engine="numba"`` (:issue:`53486`) +- :meth:`Series.explode` now supports pyarrow-backed list types (:issue:`53602`) - :meth:`Series.str.join` now supports ``ArrowDtype(pa.string())`` (:issue:`53646`) - :meth:`SeriesGroupby.agg` and :meth:`DataFrameGroupby.agg` now support passing in multiple functions for ``engine="numba"`` (:issue:`53486`) - :meth:`SeriesGroupby.transform` and :meth:`DataFrameGroupby.transform` now support passing in a string as the function for ``engine="numba"`` (:issue:`53579`) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 601b418296e7f..0c1b86440b11d 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -347,9 +347,9 @@ def _box_pa( ------- pa.Array or pa.ChunkedArray or pa.Scalar """ - if is_list_like(value): - return cls._box_pa_array(value, pa_type) - return cls._box_pa_scalar(value, pa_type) + if isinstance(value, pa.Scalar) or not is_list_like(value): + return cls._box_pa_scalar(value, pa_type) + return cls._box_pa_array(value, pa_type) @classmethod def _box_pa_scalar(cls, value, pa_type: pa.DataType | None = None) -> pa.Scalar: @@ -1549,6 +1549,24 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs): return result.as_py() + def _explode(self): + """ + See Series.explode.__doc__. + """ + values = self + counts = pa.compute.list_value_length(values._pa_array) + counts = counts.fill_null(1).to_numpy() + fill_value = pa.scalar([None], type=self._pa_array.type) + mask = counts == 0 + if mask.any(): + values = values.copy() + values[mask] = fill_value + counts = counts.copy() + counts[mask] = 1 + values = values.fillna(fill_value) + values = type(self)(pa.compute.list_flatten(values._pa_array)) + return values, counts + def __setitem__(self, key, value) -> None: """Set one or more values inplace. @@ -1591,10 +1609,10 @@ def __setitem__(self, key, value) -> None: raise IndexError( f"index {key} is out of bounds for axis 0 with size {n}" ) - if is_list_like(value): - raise ValueError("Length of indexer and values mismatch") - elif isinstance(value, pa.Scalar): + if isinstance(value, pa.Scalar): value = value.as_py() + elif is_list_like(value): + raise ValueError("Length of indexer and values mismatch") chunks = [ *self._pa_array[:key].chunks, pa.array([value], type=self._pa_array.type, from_pandas=True), diff --git a/pandas/core/series.py b/pandas/core/series.py index 9c7110cc21082..959c153561572 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -72,7 +72,10 @@ pandas_dtype, validate_all_hashable, ) -from pandas.core.dtypes.dtypes import ExtensionDtype +from pandas.core.dtypes.dtypes import ( + ArrowDtype, + ExtensionDtype, +) from pandas.core.dtypes.generic import ABCDataFrame from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import ( @@ -4267,12 +4270,14 @@ def explode(self, ignore_index: bool = False) -> Series: 3 4 dtype: object """ - if not len(self) or not is_object_dtype(self.dtype): + if isinstance(self.dtype, ArrowDtype) and self.dtype.type == list: + values, counts = self._values._explode() + elif len(self) and is_object_dtype(self.dtype): + values, counts = reshape.explode(np.asarray(self._values)) + else: result = self.copy() return result.reset_index(drop=True) if ignore_index else result - values, counts = reshape.explode(np.asarray(self._values)) - if ignore_index: index = default_index(len(values)) else: diff --git a/pandas/tests/series/methods/test_explode.py b/pandas/tests/series/methods/test_explode.py index 886152326cf3e..c8a9eb6f89fde 100644 --- a/pandas/tests/series/methods/test_explode.py +++ b/pandas/tests/series/methods/test_explode.py @@ -141,3 +141,25 @@ def test_explode_scalars_can_ignore_index(): result = s.explode(ignore_index=True) expected = pd.Series([1, 2, 3]) tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("ignore_index", [True, False]) +def test_explode_pyarrow_list_type(ignore_index): + # GH 53602 + pa = pytest.importorskip("pyarrow") + + data = [ + [None, None], + [1], + [], + [2, 3], + None, + ] + ser = pd.Series(data, dtype=pd.ArrowDtype(pa.list_(pa.int64()))) + result = ser.explode(ignore_index=ignore_index) + expected = pd.Series( + data=[None, None, 1, None, 2, 3, None], + index=None if ignore_index else [0, 0, 1, 2, 3, 3, 4], + dtype=pd.ArrowDtype(pa.int64()), + ) + tm.assert_series_equal(result, expected)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53602
2023-06-11T13:23:40Z
2023-06-13T23:18:29Z
2023-06-13T23:18:29Z
2023-06-13T23:27:43Z
BUG: fix Series.apply(..., by_row), v2.
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 34b91823abc09..79bb32c54d832 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -112,7 +112,7 @@ Other enhancements - :meth:`SeriesGroupby.transform` and :meth:`DataFrameGroupby.transform` now support passing in a string as the function for ``engine="numba"`` (:issue:`53579`) - Added :meth:`ExtensionArray.interpolate` used by :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` (:issue:`53659`) - Added ``engine_kwargs`` parameter to :meth:`DataFrame.to_excel` (:issue:`53220`) -- Added a new parameter ``by_row`` to :meth:`Series.apply`. When set to ``False`` the supplied callables will always operate on the whole Series (:issue:`53400`). +- Added a new parameter ``by_row`` to :meth:`Series.apply` and :meth:`DataFrame.apply`. When set to ``False`` the supplied callables will always operate on the whole Series or DataFrame (:issue:`53400`, :issue:`53601`). - Groupby aggregations (such as :meth:`DataFrameGroupby.sum`) now can preserve the dtype of the input instead of casting to ``float64`` (:issue:`44952`) - Improved error message when :meth:`DataFrameGroupBy.agg` failed (:issue:`52930`) - Many read/to_* functions, such as :meth:`DataFrame.to_pickle` and :func:`read_csv`, support forwarding compression arguments to lzma.LZMAFile (:issue:`52979`) diff --git a/pandas/core/apply.py b/pandas/core/apply.py index f98a08810c3ff..83a3b29bfd7f0 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -81,6 +81,7 @@ def frame_apply( axis: Axis = 0, raw: bool = False, result_type: str | None = None, + by_row: Literal[False, "compat"] = "compat", args=None, kwargs=None, ) -> FrameApply: @@ -100,6 +101,7 @@ def frame_apply( func, raw=raw, result_type=result_type, + by_row=by_row, args=args, kwargs=kwargs, ) @@ -115,11 +117,16 @@ def __init__( raw: bool, result_type: str | None, *, + by_row: Literal[False, "compat", "_compat"] = "compat", args, kwargs, ) -> None: self.obj = obj self.raw = raw + + assert by_row is False or by_row in ["compat", "_compat"] + self.by_row = by_row + self.args = args or () self.kwargs = kwargs or {} @@ -304,7 +311,14 @@ def agg_or_apply_list_like( func = cast(List[AggFuncTypeBase], self.func) kwargs = self.kwargs if op_name == "apply": - kwargs = {**kwargs, "by_row": False} + if isinstance(self, FrameApply): + by_row = self.by_row + + elif isinstance(self, SeriesApply): + by_row = "_compat" if self.by_row else False + else: + by_row = False + kwargs = {**kwargs, "by_row": by_row} if getattr(obj, "axis", 0) == 1: raise NotImplementedError("axis other than 0 is not supported") @@ -397,7 +411,10 @@ def agg_or_apply_dict_like( obj = self.obj func = cast(AggFuncTypeDict, self.func) - kwargs = {"by_row": False} if op_name == "apply" else {} + kwargs = {} + if op_name == "apply": + by_row = "_compat" if self.by_row else False + kwargs.update({"by_row": by_row}) if getattr(obj, "axis", 0) == 1: raise NotImplementedError("axis other than 0 is not supported") @@ -678,6 +695,23 @@ def agg_axis(self) -> Index: class FrameApply(NDFrameApply): obj: DataFrame + def __init__( + self, + obj: AggObjType, + func: AggFuncType, + raw: bool, + result_type: str | None, + *, + by_row: Literal[False, "compat"] = False, + args, + kwargs, + ) -> None: + if by_row is not False and by_row != "compat": + raise ValueError(f"by_row={by_row} not allowed") + super().__init__( + obj, func, raw, result_type, by_row=by_row, args=args, kwargs=kwargs + ) + # --------------------------------------------------------------- # Abstract Methods @@ -1067,7 +1101,7 @@ def infer_to_same_shape(self, results: ResType, res_index: Index) -> DataFrame: class SeriesApply(NDFrameApply): obj: Series axis: AxisInt = 0 - by_row: bool # only relevant for apply() + by_row: Literal[False, "compat", "_compat"] # only relevant for apply() def __init__( self, @@ -1075,7 +1109,7 @@ def __init__( func: AggFuncType, *, convert_dtype: bool | lib.NoDefault = lib.no_default, - by_row: bool = True, + by_row: Literal[False, "compat", "_compat"] = "compat", args, kwargs, ) -> None: @@ -1090,13 +1124,13 @@ def __init__( stacklevel=find_stack_level(), ) self.convert_dtype = convert_dtype - self.by_row = by_row super().__init__( obj, func, raw=False, result_type=None, + by_row=by_row, args=args, kwargs=kwargs, ) @@ -1115,6 +1149,9 @@ def apply(self) -> DataFrame | Series: # if we are a string, try to dispatch return self.apply_str() + if self.by_row == "_compat": + return self.apply_compat() + # self.func is Callable return self.apply_standard() @@ -1149,6 +1186,28 @@ def apply_empty_result(self) -> Series: obj, method="apply" ) + def apply_compat(self): + """compat apply method for funcs in listlikes and dictlikes. + + Used for each callable when giving listlikes and dictlikes of callables to + apply. Needed for compatibility with Pandas < v2.1. + + .. versionadded:: 2.1.0 + """ + obj = self.obj + func = self.func + + if callable(func): + f = com.get_cython_func(func) + if f and not self.args and not self.kwargs: + return obj.apply(func, by_row=False) + + try: + result = obj.apply(func, by_row="compat") + except (ValueError, AttributeError, TypeError): + result = obj.apply(func, by_row=False) + return result + def apply_standard(self) -> DataFrame | Series: # caller is responsible for ensuring that f is Callable func = cast(Callable, self.func) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 72d586964b524..ae43a44d68f1c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9634,6 +9634,7 @@ def apply( raw: bool = False, result_type: Literal["expand", "reduce", "broadcast"] | None = None, args=(), + by_row: Literal[False, "compat"] = "compat", **kwargs, ): """ @@ -9682,6 +9683,17 @@ def apply( args : tuple Positional arguments to pass to `func` in addition to the array/series. + by_row : False or "compat", default "compat" + Only has an effect when ``func`` is a listlike or dictlike of funcs + and the func isn't a string. + If "compat", will if possible first translate the func into pandas + methods (e.g. ``Series().apply(np.sum)`` will be translated to + ``Series().sum()``). If that doesn't work, will try call to apply again with + ``by_row=True`` and if that fails, will call apply again with + ``by_row=False`` (backward compatible). + If False, the funcs will be passed the whole Series at once. + + .. versionadded:: 2.1.0 **kwargs Additional keyword arguments to pass as keywords arguments to `func`. @@ -9781,6 +9793,7 @@ def apply( axis=axis, raw=raw, result_type=result_type, + by_row=by_row, args=args, kwargs=kwargs, ) diff --git a/pandas/core/series.py b/pandas/core/series.py index 8785e2fb65fb8..e59a4cfc3fcc1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4538,7 +4538,7 @@ def apply( convert_dtype: bool | lib.NoDefault = lib.no_default, args: tuple[Any, ...] = (), *, - by_row: bool = True, + by_row: Literal[False, "compat"] = "compat", **kwargs, ) -> DataFrame | Series: """ @@ -4562,14 +4562,20 @@ def apply( preserved for some extension array dtypes, such as Categorical. .. deprecated:: 2.1.0 - The convert_dtype has been deprecated. Do ``ser.astype(object).apply()`` + ``convert_dtype`` has been deprecated. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``. args : tuple Positional arguments passed to func after the series value. - by_row : bool, default True + by_row : False or "compat", default "compat" + If ``"compat"`` and func is a callable, func will be passed each element of + the Series, like ``Series.map``. If func is a list or dict of + callables, will first try to translate each func into pandas methods. If + that doesn't work, will try call to apply again with ``by_row="compat"`` + and if that fails, will call apply again with ``by_row=False`` + (backward compatible). If False, the func will be passed the whole Series at once. - If True, will func will be passed each element of the Series, like - Series.map (backward compatible). + + ``by_row`` has no effect when ``func`` is a string. .. versionadded:: 2.1.0 **kwargs diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index 99fc393ff82c5..5681167cd54f9 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -667,6 +667,50 @@ def test_infer_row_shape(): assert result == (6, 2) +@pytest.mark.parametrize( + "ops, by_row, expected", + [ + ({"a": lambda x: x + 1}, "compat", DataFrame({"a": [2, 3]})), + ({"a": lambda x: x + 1}, False, DataFrame({"a": [2, 3]})), + ({"a": lambda x: x.sum()}, "compat", Series({"a": 3})), + ({"a": lambda x: x.sum()}, False, Series({"a": 3})), + ( + {"a": ["sum", np.sum, lambda x: x.sum()]}, + "compat", + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", "<lambda>"]), + ), + ( + {"a": ["sum", np.sum, lambda x: x.sum()]}, + False, + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", "<lambda>"]), + ), + ({"a": lambda x: 1}, "compat", DataFrame({"a": [1, 1]})), + ({"a": lambda x: 1}, False, Series({"a": 1})), + ], +) +def test_dictlike_lambda(ops, by_row, expected): + # GH53601 + df = DataFrame({"a": [1, 2]}) + result = df.apply(ops, by_row=by_row) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "ops", + [ + {"a": lambda x: x + 1}, + {"a": lambda x: x.sum()}, + {"a": ["sum", np.sum, lambda x: x.sum()]}, + {"a": lambda x: 1}, + ], +) +def test_dictlike_lambda_raises(ops): + # GH53601 + df = DataFrame({"a": [1, 2]}) + with pytest.raises(ValueError, match="by_row=True not allowed"): + df.apply(ops, by_row=True) + + def test_with_dictlike_columns(): # GH 17602 df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) @@ -716,6 +760,58 @@ def test_with_dictlike_columns_with_infer(): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize( + "ops, by_row, expected", + [ + ([lambda x: x + 1], "compat", DataFrame({("a", "<lambda>"): [2, 3]})), + ([lambda x: x + 1], False, DataFrame({("a", "<lambda>"): [2, 3]})), + ([lambda x: x.sum()], "compat", DataFrame({"a": [3]}, index=["<lambda>"])), + ([lambda x: x.sum()], False, DataFrame({"a": [3]}, index=["<lambda>"])), + ( + ["sum", np.sum, lambda x: x.sum()], + "compat", + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", "<lambda>"]), + ), + ( + ["sum", np.sum, lambda x: x.sum()], + False, + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", "<lambda>"]), + ), + ( + [lambda x: x + 1, lambda x: 3], + "compat", + DataFrame([[2, 3], [3, 3]], columns=[["a", "a"], ["<lambda>", "<lambda>"]]), + ), + ( + [lambda x: 2, lambda x: 3], + False, + DataFrame({"a": [2, 3]}, ["<lambda>", "<lambda>"]), + ), + ], +) +def test_listlike_lambda(ops, by_row, expected): + # GH53601 + df = DataFrame({"a": [1, 2]}) + result = df.apply(ops, by_row=by_row) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "ops", + [ + [lambda x: x + 1], + [lambda x: x.sum()], + ["sum", np.sum, lambda x: x.sum()], + [lambda x: x + 1, lambda x: 3], + ], +) +def test_listlike_lambda_raises(ops): + # GH53601 + df = DataFrame({"a": [1, 2]}) + with pytest.raises(ValueError, match="by_row=True not allowed"): + df.apply(ops, by_row=True) + + def test_with_listlike_columns(): # GH 17348 df = DataFrame( diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index 3e0ff19ae4c1a..9002a5f85cba6 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -14,7 +14,7 @@ from pandas.tests.apply.common import series_transform_kernels -@pytest.fixture(params=[True, False]) +@pytest.fixture(params=[False, "compat"]) def by_row(request): return request.param @@ -69,12 +69,7 @@ def test_apply_map_same_length_inference_bug(): def f(x): return (x, x + 1) - result = s.apply(f, by_row=True) - expected = s.map(f) - tm.assert_series_equal(result, expected) - - s = Series([1, 2, 3]) - result = s.apply(f, by_row=by_row) + result = s.apply(f, by_row="compat") expected = s.map(f) tm.assert_series_equal(result, expected) @@ -87,7 +82,7 @@ def func(x): return x if x > 0 else np.nan with tm.assert_produces_warning(FutureWarning): - ser.apply(func, convert_dtype=convert_dtype, by_row=True) + ser.apply(func, convert_dtype=convert_dtype, by_row="compat") def test_apply_args(): @@ -161,7 +156,7 @@ def test_apply_box(): s = Series(vals) assert s.dtype == "datetime64[ns]" # boxed value must be Timestamp instance - res = s.apply(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}", by_row=True) + res = s.apply(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}", by_row="compat") exp = Series(["Timestamp_1_None", "Timestamp_2_None"]) tm.assert_series_equal(res, exp) @@ -171,7 +166,7 @@ def test_apply_box(): ] s = Series(vals) assert s.dtype == "datetime64[ns, US/Eastern]" - res = s.apply(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}", by_row=True) + res = s.apply(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}", by_row="compat") exp = Series(["Timestamp_1_US/Eastern", "Timestamp_2_US/Eastern"]) tm.assert_series_equal(res, exp) @@ -179,7 +174,7 @@ def test_apply_box(): vals = [pd.Timedelta("1 days"), pd.Timedelta("2 days")] s = Series(vals) assert s.dtype == "timedelta64[ns]" - res = s.apply(lambda x: f"{type(x).__name__}_{x.days}", by_row=True) + res = s.apply(lambda x: f"{type(x).__name__}_{x.days}", by_row="compat") exp = Series(["Timedelta_1", "Timedelta_2"]) tm.assert_series_equal(res, exp) @@ -187,7 +182,7 @@ def test_apply_box(): vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")] s = Series(vals) assert s.dtype == "Period[M]" - res = s.apply(lambda x: f"{type(x).__name__}_{x.freqstr}", by_row=True) + res = s.apply(lambda x: f"{type(x).__name__}_{x.freqstr}", by_row="compat") exp = Series(["Period_M", "Period_M"]) tm.assert_series_equal(res, exp) @@ -397,7 +392,7 @@ def test_demo(): @pytest.mark.parametrize("func", [str, lambda x: str(x)]) def test_apply_map_evaluate_lambdas_the_same(string_series, func, by_row): - # test that we are evaluating row-by-row first if by_row=True + # test that we are evaluating row-by-row first if by_row="compat" # else vectorized evaluation result = string_series.apply(func, by_row=by_row) @@ -435,7 +430,7 @@ def test_with_nested_series(datetime_series, op_name): tm.assert_frame_equal(result, expected) -def test_replicate_describe(string_series, by_row): +def test_replicate_describe(string_series): # this also tests a result set that is all scalars expected = string_series.describe() result = string_series.apply( @@ -449,7 +444,6 @@ def test_replicate_describe(string_series, by_row): "75%": lambda x: x.quantile(0.75), "max": "max", }, - by_row=by_row, ) tm.assert_series_equal(result, expected) @@ -467,7 +461,7 @@ def test_reduce(string_series): @pytest.mark.parametrize( "how, kwds", - [("agg", {}), ("apply", {"by_row": True}), ("apply", {"by_row": False})], + [("agg", {}), ("apply", {"by_row": "compat"}), ("apply", {"by_row": False})], ) def test_non_callable_aggregates(how, kwds): # test agg using non-callable series attributes @@ -526,7 +520,7 @@ def test_apply_series_on_date_time_index_aware_series(dti, exp, aware): @pytest.mark.parametrize( - "by_row, expected", [(True, Series(np.ones(30), dtype="int64")), (False, 1)] + "by_row, expected", [("compat", Series(np.ones(30), dtype="int64")), (False, 1)] ) def test_apply_scalar_on_date_time_index_aware_series(by_row, expected): # GH 25959 @@ -561,7 +555,7 @@ def test_apply_to_timedelta(by_row): ) @pytest.mark.parametrize( "how, kwargs", - [["agg", {}], ["apply", {"by_row": True}], ["apply", {"by_row": False}]], + [["agg", {}], ["apply", {"by_row": "compat"}], ["apply", {"by_row": False}]], ) def test_apply_listlike_reducer(string_series, ops, names, how, kwargs): # GH 39140 @@ -582,7 +576,7 @@ def test_apply_listlike_reducer(string_series, ops, names, how, kwargs): ) @pytest.mark.parametrize( "how, kwargs", - [["agg", {}], ["apply", {"by_row": True}], ["apply", {"by_row": False}]], + [["agg", {}], ["apply", {"by_row": "compat"}], ["apply", {"by_row": False}]], ) def test_apply_dictlike_reducer(string_series, ops, how, kwargs, by_row): # GH 39140 @@ -617,7 +611,7 @@ def test_apply_listlike_transformer(string_series, ops, names, by_row): ([lambda x: x.sum()], Series([6], index=["<lambda>"])), ], ) -def test_apply_listlike_lambda(ops, expected, by_row=by_row): +def test_apply_listlike_lambda(ops, expected, by_row): # GH53400 ser = Series([1, 2, 3]) result = ser.apply(ops, by_row=by_row)
Fixes https://github.com/pandas-dev/pandas/pull/53400#discussion_r1223790606 by making the `by_row` param take `"compat"` as a parameter and using that internally that when `apply` is given dicts og lists. The compatability path is now to deprecate `by_rows=(True|"compat")` at some point, so `by_rows=False` will become the default in v3.0. Supercedes #53584. Code example: ``` df = pd.DataFrame({'a': [1, 1, 2], 'b': [3, 4, 5]}) # On 2.0.x and main print(df.apply([lambda x: 1])) # a b # <lambda> <lambda> # 0 1 1 # 1 1 1 # 2 1 1 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/53601
2023-06-11T11:55:06Z
2023-06-29T21:33:14Z
2023-06-29T21:33:14Z
2023-06-30T02:01:02Z
DOC: Corrected minor typos in the paragraph below 'Formatting the Display'
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb index 79b04ef57d9cf..bf7ecf1399cea 100644 --- a/doc/source/user_guide/style.ipynb +++ b/doc/source/user_guide/style.ipynb @@ -59,9 +59,9 @@ "\n", "### Formatting Values\n", "\n", - "The [Styler][styler] distinguishes the *display* value from the *actual* value, in both data values and index or columns headers. To control the display value, the text is printed in each cell as string, and we can use the [.format()][formatfunc] and [.format_index()][formatfuncindex] methods to manipulate this according to a [format spec string][format] or a callable that takes a single value and returns a string. It is possible to define this for the whole table, or index, or for individual columns, or MultiIndex levels. We can also overwrite index names\n", + "The [Styler][styler] distinguishes the *display* value from the *actual* value, in both data values and index or columns headers. To control the display value, the text is printed in each cell as a string, and we can use the [.format()][formatfunc] and [.format_index()][formatfuncindex] methods to manipulate this according to a [format spec string][format] or a callable that takes a single value and returns a string. It is possible to define this for the whole table, or index, or for individual columns, or MultiIndex levels. We can also overwrite index names.\n", "\n", - "Additionally, the format function has a **precision** argument to specifically help formatting floats, as well as **decimal** and **thousands** separators to support other locales, an **na_rep** argument to display missing data, and an **escape** and **hyperlinks** arguments to help displaying safe-HTML or safe-LaTeX. The default formatter is configured to adopt pandas' global options such as `styler.format.precision` option, controllable using `with pd.option_context('format.precision', 2):` \n", + "Additionally, the format function has a **precision** argument to specifically help format floats, as well as **decimal** and **thousands** separators to support other locales, an **na_rep** argument to display missing data, and an **escape** and **hyperlinks** arguments to help displaying safe-HTML or safe-LaTeX. The default formatter is configured to adopt pandas' global options such as `styler.format.precision` option, controllable using `with pd.option_context('format.precision', 2):`\n", "\n", "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst\n", "[format]: https://docs.python.org/3/library/string.html#format-specification-mini-language\n",
- [ ] closes #53596 - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/53598
2023-06-11T05:10:31Z
2023-06-11T23:09:56Z
2023-06-11T23:09:56Z
2023-06-11T23:10:30Z
ENH: Implement PandasArray, DTA, TDA interpolate
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 8c57496e092c4..ea085b3d1f6ab 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -106,6 +106,7 @@ from pandas.core import ( algorithms, + missing, nanops, ) from pandas.core.algorithms import ( @@ -142,6 +143,7 @@ from pandas.tseries import frequencies if TYPE_CHECKING: + from pandas import Index from pandas.core.arrays import ( DatetimeArray, PeriodArray, @@ -2228,6 +2230,46 @@ def copy(self, order: str = "C") -> Self: new_obj._freq = self.freq return new_obj + def interpolate( + self, + *, + method, + axis: int, + index: Index | None, + limit, + limit_direction, + limit_area, + fill_value, + inplace: bool, + **kwargs, + ) -> Self: + """ + See NDFrame.interpolate.__doc__. + """ + # NB: we return type(self) even if inplace=True + if method != "linear": + raise NotImplementedError + + if inplace: + out_data = self._ndarray + else: + out_data = self._ndarray.copy() + + missing.interpolate_array_2d( + out_data, + method=method, + axis=axis, + index=index, + limit=limit, + limit_direction=limit_direction, + limit_area=limit_area, + fill_value=fill_value, + **kwargs, + ) + if inplace: + return self + return type(self)._simple_new(out_data, dtype=self.dtype) + # ------------------------------------------------------------------- # Shared Constructor Helpers diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 702180b5d779a..113f22ad968bc 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -19,6 +19,7 @@ from pandas.core import ( arraylike, + missing, nanops, ops, ) @@ -33,9 +34,12 @@ Dtype, NpDtype, Scalar, + Self, npt, ) + from pandas import Index + # error: Definition of "_concat_same_type" in base class "NDArrayBacked" is # incompatible with definition in base class "ExtensionArray" @@ -220,6 +224,43 @@ def _values_for_factorize(self) -> tuple[np.ndarray, float | None]: fv = np.nan return self._ndarray, fv + def interpolate( + self, + *, + method, + axis: int, + index: Index | None, + limit, + limit_direction, + limit_area, + fill_value, + inplace: bool, + **kwargs, + ) -> Self: + """ + See NDFrame.interpolate.__doc__. + """ + # NB: we return type(self) even if inplace=True + if inplace: + out_data = self._ndarray + else: + out_data = self._ndarray.copy() + + missing.interpolate_array_2d( + out_data, + method=method, + axis=axis, + index=index, + limit=limit, + limit_direction=limit_direction, + limit_area=limit_area, + fill_value=fill_value, + **kwargs, + ) + if inplace: + return self + return type(self)._simple_new(out_data, dtype=self.dtype) + # ------------------------------------------------------------------------ # Reductions diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 7c5d686d96939..696884e344e40 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1394,18 +1394,16 @@ def interpolate( ) refs = None + arr_inplace = inplace if inplace: if using_cow and self.refs.has_reference(): - data = self.values.copy() + arr_inplace = False else: - data = self.values refs = self.refs - else: - data = self.values.copy() - data = cast(np.ndarray, data) # bc overridden by ExtensionBlock - missing.interpolate_array_2d( - data, + # Dispatch to the PandasArray method. + # We know self.array_values is a PandasArray bc EABlock overrides + new_values = cast(PandasArray, self.array_values).interpolate( method=method, axis=axis, index=index, @@ -1413,8 +1411,10 @@ def interpolate( limit_direction=limit_direction, limit_area=limit_area, fill_value=fill_value, + inplace=arr_inplace, **kwargs, ) + data = new_values._ndarray nb = self.make_block_same_class(data, refs=refs) return nb._maybe_downcast([nb], downcast, using_cow) @@ -2262,18 +2262,22 @@ def interpolate( if method == "linear": # type: ignore[comparison-overlap] # TODO: GH#50950 implement for arbitrary EAs refs = None + arr_inplace = inplace if using_cow: if inplace and not self.refs.has_reference(): - data_out = values._ndarray refs = self.refs else: - data_out = values._ndarray.copy() - else: - data_out = values._ndarray if inplace else values._ndarray.copy() - missing.interpolate_array_2d( - data_out, method=method, limit=limit, index=index, axis=axis + arr_inplace = False + + new_values = self.values.interpolate( + method=method, + index=index, + axis=axis, + inplace=arr_inplace, + limit=limit, + fill_value=fill_value, + **kwargs, ) - new_values = type(values)._simple_new(data_out, dtype=values.dtype) return self.make_block_same_class(new_values, refs=refs) elif values.ndim == 2 and axis == 0:
pushing towards #50950
https://api.github.com/repos/pandas-dev/pandas/pulls/53594
2023-06-10T16:16:32Z
2023-06-12T17:38:04Z
2023-06-12T17:38:04Z
2023-06-12T18:26:58Z
CI: Fix the deprecation bot
diff --git a/.github/workflows/deprecation-tracking-bot.yml b/.github/workflows/deprecation-tracking-bot.yml index c0d871ed54ed6..b3f9bcd840c68 100644 --- a/.github/workflows/deprecation-tracking-bot.yml +++ b/.github/workflows/deprecation-tracking-bot.yml @@ -1,11 +1,13 @@ +# This bot updates the issue with number DEPRECATION_TRACKER_ISSUE +# with the PR number that issued the deprecation. + +# It runs on commits to main, and will trigger if the PR linked to a merged commit has the "Deprecate" label name: Deprecations Bot on: - pull_request: + push: branches: - main - types: - [closed] permissions: @@ -15,17 +17,49 @@ jobs: deprecation_update: permissions: issues: write - if: >- - contains(github.event.pull_request.labels.*.name, 'Deprecate') && github.event.pull_request.merged == true runs-on: ubuntu-22.04 env: DEPRECATION_TRACKER_ISSUE: 50578 steps: - - name: Checkout - run: | - echo "Adding deprecation PR number to deprecation tracking issue" - export PR=${{ github.event.pull_request.number }} - BODY=$(curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/repos/${{ github.repository }}/issues/${DEPRECATION_TRACKER_ISSUE} | - python3 -c "import sys, json, os; x = {'body': json.load(sys.stdin)['body']}; pr = os.environ['PR']; x['body'] += f'\n- [ ] #{pr}'; print(json.dumps(x))") - echo ${BODY} - curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -X PATCH -d "${BODY}" https://api.github.com/repos/${{ github.repository }}/issues/${DEPRECATION_TRACKER_ISSUE} + - uses: actions/github-script@v6 + id: update-deprecation-issue + with: + script: | + body = await github.rest.issues.get({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: ${{ env.DEPRECATION_TRACKER_ISSUE }}, + }) + body = body["data"]["body"]; + linkedPRs = await github.rest.repos.listPullRequestsAssociatedWithCommit({ + owner: context.repo.owner, + repo: context.repo.repo, + commit_sha: '${{ github.sha }}' + }) + linkedPRs = linkedPRs["data"]; + console.log(linkedPRs); + if (linkedPRs.length > 0) { + console.log("Found linked PR"); + linkedPR = linkedPRs[0] + isDeprecation = false + for (label of linkedPR["labels"]) { + if (label["name"] == "Deprecate") { + isDeprecation = true; + break; + } + } + + PR_NUMBER = linkedPR["number"]; + + body += ("\n- [ ] #" + PR_NUMBER); + if (isDeprecation) { + console.log("PR is a deprecation PR. Printing new body of issue"); + console.log(body); + github.rest.issues.update({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: ${{ env.DEPRECATION_TRACKER_ISSUE }}, + body: body + }) + } + }
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This works locally, at least on my fork. See https://github.com/pandas-dev/pandas/issues/50578#issuecomment-1581194128 for what I think went wrong the other time this was tried.
https://api.github.com/repos/pandas-dev/pandas/pulls/53593
2023-06-10T14:49:46Z
2023-06-12T16:57:27Z
2023-06-12T16:57:27Z
2023-06-12T16:59:52Z
TST: Add test for apply cast types GH#9506
diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index 425d2fb42a711..3e0ff19ae4c1a 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -271,6 +271,19 @@ def test_apply_empty_integer_series_with_datetime_index(by_row): tm.assert_series_equal(result, s) +def test_apply_dataframe_iloc(): + uintDF = DataFrame(np.uint64([1, 2, 3, 4, 5]), columns=["Numbers"]) + indexDF = DataFrame([2, 3, 2, 1, 2], columns=["Indices"]) + + def retrieve(targetRow, targetDF): + val = targetDF["Numbers"].iloc[targetRow] + return val + + result = indexDF["Indices"].apply(retrieve, args=(uintDF,)) + expected = Series([3, 4, 3, 2, 3], name="Indices", dtype="uint64") + tm.assert_series_equal(result, expected) + + def test_transform(string_series, by_row): # transforming functions
- [ ] closes #9506 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53591
2023-06-10T12:40:15Z
2023-06-13T16:20:52Z
2023-06-13T16:20:52Z
2023-06-13T23:16:46Z
PERF: Series.str.split(expand=True) for pyarrow-backed strings
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index baacc8c421414..a435358d787d5 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -316,6 +316,7 @@ Performance improvements - Performance improvement in :meth:`Series.add` for pyarrow string and binary dtypes (:issue:`53150`) - Performance improvement in :meth:`Series.corr` and :meth:`Series.cov` for extension dtypes (:issue:`52502`) - Performance improvement in :meth:`Series.str.get` for pyarrow-backed strings (:issue:`53152`) +- Performance improvement in :meth:`Series.str.split` with ``expand=True`` for pyarrow-backed strings (:issue:`53585`) - Performance improvement in :meth:`Series.to_numpy` when dtype is a numpy float dtype and ``na_value`` is ``np.nan`` (:issue:`52430`) - Performance improvement in :meth:`~arrays.ArrowExtensionArray.astype` when converting from a pyarrow timestamp or duration dtype to numpy (:issue:`53326`) - Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`52525`) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 127ad5e962b16..875ca4dcd070e 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -279,7 +279,7 @@ def _wrap_result( from pandas.core.arrays.arrow.array import ArrowExtensionArray - value_lengths = result._pa_array.combine_chunks().value_lengths() + value_lengths = pa.compute.list_value_length(result._pa_array) max_len = pa.compute.max(value_lengths).as_py() min_len = pa.compute.min(value_lengths).as_py() if result._hasna: @@ -313,9 +313,14 @@ def _wrap_result( labels = name else: labels = range(max_len) + result = ( + pa.compute.list_flatten(result._pa_array) + .to_numpy() + .reshape(len(result), max_len) + ) result = { label: ArrowExtensionArray(pa.array(res)) - for label, res in zip(labels, (zip(*result.tolist()))) + for label, res in zip(labels, result.T) } elif is_object_dtype(result):
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file if fixing a bug or adding a new feature. Perf improvement for `Series.str.split` with `expand=True` for `ArrowDtype(pa.string())`: ``` import pandas as pd import pyarrow as pa N = 10_000 data = ["foo|bar|baz"] * N ser = pd.Series(data, dtype=pd.ArrowDtype(pa.string())) %timeit ser.str.split("|", expand=True) # 93.8 ms ± 2.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) -> main # 5.43 ms ± 201 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) -> PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/53585
2023-06-10T10:05:04Z
2023-06-12T17:45:05Z
2023-06-12T17:45:05Z
2023-06-13T23:27:50Z
REF: move interpolate validation to core.missing
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f73ef36f76086..a07a2112faba1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -143,6 +143,7 @@ arraylike, common, indexing, + missing, nanops, sample, ) @@ -7907,20 +7908,7 @@ def interpolate( "Only `method=linear` interpolation is supported on MultiIndexes." ) - # Set `limit_direction` depending on `method` - if limit_direction is None: - limit_direction = ( - "backward" if method in ("backfill", "bfill") else "forward" - ) - else: - if method in ("pad", "ffill") and limit_direction != "forward": - raise ValueError( - f"`limit_direction` must be 'forward' for method `{method}`" - ) - if method in ("backfill", "bfill") and limit_direction != "backward": - raise ValueError( - f"`limit_direction` must be 'backward' for method `{method}`" - ) + limit_direction = missing.infer_limit_direction(limit_direction, method) if obj.ndim == 2 and np.all(obj.dtypes == np.dtype("object")): raise TypeError( @@ -7929,32 +7917,8 @@ def interpolate( "column to a numeric dtype." ) - # create/use the index - if method == "linear": - # prior default - index = Index(np.arange(len(obj.index))) - else: - index = obj.index - methods = {"index", "values", "nearest", "time"} - is_numeric_or_datetime = ( - is_numeric_dtype(index.dtype) - or isinstance(index.dtype, DatetimeTZDtype) - or lib.is_np_dtype(index.dtype, "mM") - ) - if method not in methods and not is_numeric_or_datetime: - raise ValueError( - "Index column must be numeric or datetime type when " - f"using {method} method other than linear. " - "Try setting a numeric or datetime index column before " - "interpolating." - ) + index = missing.get_interp_index(method, obj.index) - if isna(index).any(): - raise NotImplementedError( - "Interpolation with NaNs in the index " - "has not been implemented. Try filling " - "those NaNs before interpolating." - ) new_data = obj._mgr.interpolate( method=method, axis=axis, @@ -8140,13 +8104,13 @@ def asof(self, where, subset=None): locs = self.index.asof_locs(where, ~(nulls._values)) # mask the missing - missing = locs == -1 + mask = locs == -1 data = self.take(locs) data.index = where - if missing.any(): + if mask.any(): # GH#16063 only do this setting when necessary, otherwise # we'd cast e.g. bools to floats - data.loc[missing] = np.nan + data.loc[mask] = np.nan return data if is_list else data.iloc[-1] # ---------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 7c5d686d96939..4244b7bc0c881 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1350,7 +1350,7 @@ def interpolate( index: Index | None = None, inplace: bool = False, limit: int | None = None, - limit_direction: str = "forward", + limit_direction: Literal["forward", "backward", "both"] = "forward", limit_area: str | None = None, fill_value: Any | None = None, downcast: Literal["infer"] | None = None, diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 7762ba8e2c730..2fe6be9ff48c1 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -33,10 +33,12 @@ from pandas.core.dtypes.cast import infer_dtype_from from pandas.core.dtypes.common import ( is_array_like, + is_numeric_dtype, is_numeric_v_string_like, is_object_dtype, needs_i8_conversion, ) +from pandas.core.dtypes.dtypes import DatetimeTZDtype from pandas.core.dtypes.missing import ( is_valid_na_for_dtype, isna, @@ -225,6 +227,56 @@ def find_valid_index(how: str, is_valid: npt.NDArray[np.bool_]) -> int | None: return idxpos # type: ignore[return-value] +def infer_limit_direction(limit_direction, method): + # Set `limit_direction` depending on `method` + if limit_direction is None: + if method in ("backfill", "bfill"): + limit_direction = "backward" + else: + limit_direction = "forward" + else: + if method in ("pad", "ffill") and limit_direction != "forward": + raise ValueError( + f"`limit_direction` must be 'forward' for method `{method}`" + ) + if method in ("backfill", "bfill") and limit_direction != "backward": + raise ValueError( + f"`limit_direction` must be 'backward' for method `{method}`" + ) + return limit_direction + + +def get_interp_index(method, index: Index) -> Index: + # create/use the index + if method == "linear": + # prior default + from pandas import Index + + index = Index(np.arange(len(index))) + else: + methods = {"index", "values", "nearest", "time"} + is_numeric_or_datetime = ( + is_numeric_dtype(index.dtype) + or isinstance(index.dtype, DatetimeTZDtype) + or lib.is_np_dtype(index.dtype, "mM") + ) + if method not in methods and not is_numeric_or_datetime: + raise ValueError( + "Index column must be numeric or datetime type when " + f"using {method} method other than linear. " + "Try setting a numeric or datetime index column before " + "interpolating." + ) + + if isna(index).any(): + raise NotImplementedError( + "Interpolation with NaNs in the index " + "has not been implemented. Try filling " + "those NaNs before interpolating." + ) + return index + + def interpolate_array_2d( data: np.ndarray, method: str = "pad",
Some cleanup found while working towards #50950.
https://api.github.com/repos/pandas-dev/pandas/pulls/53580
2023-06-09T22:00:13Z
2023-06-12T18:44:33Z
2023-06-12T18:44:33Z
2023-06-12T18:47:47Z
ENH: Groupby.transform support string input with engine=numba
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index baacc8c421414..e346870969741 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -103,6 +103,7 @@ Other enhancements - :meth:`DataFrame.unstack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`) - :meth:`DataFrameGroupby.agg` and :meth:`DataFrameGroupby.transform` now support grouping by multiple keys when the index is not a :class:`MultiIndex` for ``engine="numba"`` (:issue:`53486`) - :meth:`SeriesGroupby.agg` and :meth:`DataFrameGroupby.agg` now support passing in multiple functions for ``engine="numba"`` (:issue:`53486`) +- :meth:`SeriesGroupby.transform` and :meth:`DataFrameGroupby.transform` now support passing in a string as the function for ``engine="numba"`` (:issue:`53579`) - Added ``engine_kwargs`` parameter to :meth:`DataFrame.to_excel` (:issue:`53220`) - Added a new parameter ``by_row`` to :meth:`Series.apply`. When set to ``False`` the supplied callables will always operate on the whole Series (:issue:`53400`). - Many read/to_* functions, such as :meth:`DataFrame.to_pickle` and :func:`read_csv`, support forwarding compression arguments to lzma.LZMAFile (:issue:`52979`) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index eef3de3e61f29..2b1ff05f18d5e 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -523,10 +523,16 @@ def _cython_transform( return obj._constructor(result, index=self.obj.index, name=obj.name) - def _transform_general(self, func: Callable, *args, **kwargs) -> Series: + def _transform_general( + self, func: Callable, engine, engine_kwargs, *args, **kwargs + ) -> Series: """ Transform with a callable `func`. """ + if maybe_use_numba(engine): + return self._transform_with_numba( + func, *args, engine_kwargs=engine_kwargs, **kwargs + ) assert callable(func) klass = type(self.obj) @@ -1654,7 +1660,11 @@ def arr_func(bvalues: ArrayLike) -> ArrayLike: res_df = self._maybe_transpose_result(res_df) return res_df - def _transform_general(self, func, *args, **kwargs): + def _transform_general(self, func, engine, engine_kwargs, *args, **kwargs): + if maybe_use_numba(engine): + return self._transform_with_numba( + func, *args, engine_kwargs=engine_kwargs, **kwargs + ) from pandas.core.reshape.concat import concat applied = [] diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index b15b5b11c3d5e..e447377db9e55 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1787,22 +1787,20 @@ def _cython_transform( @final def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): - if maybe_use_numba(engine): - return self._transform_with_numba( - func, *args, engine_kwargs=engine_kwargs, **kwargs - ) - # optimized transforms func = com.get_cython_func(func) or func if not isinstance(func, str): - return self._transform_general(func, *args, **kwargs) + return self._transform_general(func, engine, engine_kwargs, *args, **kwargs) elif func not in base.transform_kernel_allowlist: msg = f"'{func}' is not a valid function name for transform(name)" raise ValueError(msg) elif func in base.cythonized_kernels or func in base.transformation_kernels: # cythonized transform or canned "agg+broadcast" + if engine is not None: + kwargs["engine"] = engine + kwargs["engine_kwargs"] = engine_kwargs return getattr(self, func)(*args, **kwargs) else: @@ -1817,6 +1815,9 @@ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): with com.temp_setattr(self, "as_index", True): # GH#49834 - result needs groups in the index for # _wrap_transform_fast_result + if engine is not None: + kwargs["engine"] = engine + kwargs["engine_kwargs"] = engine_kwargs result = getattr(self, func)(*args, **kwargs) return self._wrap_transform_fast_result(result) diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index 00ff391199652..8da6b23f5ac57 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -130,20 +130,25 @@ def func_1(values, index): tm.assert_frame_equal(expected, result) +# TODO: Test more than just reductions (e.g. actually test transformations once we have @td.skip_if_no("numba") @pytest.mark.parametrize( "agg_func", [["min", "max"], "min", {"B": ["min", "max"], "C": "sum"}] ) -def test_multifunc_notimplimented(agg_func): +def test_string_cython_vs_numba(agg_func, numba_supported_reductions): + agg_func, kwargs = numba_supported_reductions data = DataFrame( {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) grouped = data.groupby(0) - with pytest.raises(NotImplementedError, match="Numba engine can"): - grouped.transform(agg_func, engine="numba") - with pytest.raises(NotImplementedError, match="Numba engine can"): - grouped[1].transform(agg_func, engine="numba") + result = grouped.transform(agg_func, engine="numba", **kwargs) + expected = grouped.transform(agg_func, engine="cython", **kwargs) + tm.assert_frame_equal(result, expected) + + result = grouped[1].transform(agg_func, engine="numba", **kwargs) + expected = grouped[1].transform(agg_func, engine="cython", **kwargs) + tm.assert_series_equal(result, expected) @td.skip_if_no("numba") @@ -232,9 +237,6 @@ def numba_func(values, index): @td.skip_if_no("numba") -@pytest.mark.xfail( - reason="Groupby transform doesn't support strings as function inputs yet with numba" -) def test_multilabel_numba_vs_cython(numba_supported_reductions): reduction, kwargs = numba_supported_reductions df = DataFrame(
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53579
2023-06-09T21:01:08Z
2023-06-12T20:15:06Z
2023-06-12T20:15:06Z
2023-06-12T23:15:37Z
CI: Ensure nightly wheels are uploaded instead of just sdist
diff --git a/ci/upload_wheels.sh b/ci/upload_wheels.sh index e57e9b01b9830..3c4aa76c02003 100644 --- a/ci/upload_wheels.sh +++ b/ci/upload_wheels.sh @@ -28,12 +28,12 @@ upload_wheels() { if compgen -G "./dist/*.gz"; then echo "Found sdist" anaconda -q -t ${TOKEN} upload --skip -u ${ANACONDA_ORG} ./dist/*.gz - elif compgen -G "./wheelhouse/*.whl"; then + echo "Uploaded sdist" + fi + if compgen -G "./wheelhouse/*.whl"; then echo "Found wheel" anaconda -q -t ${TOKEN} upload --skip -u ${ANACONDA_ORG} ./wheelhouse/*.whl - else - echo "Files do not exist" - return 1 + echo "Uploaded wheel" fi echo "PyPI-style index: https://pypi.anaconda.org/$ANACONDA_ORG/simple" fi
null
https://api.github.com/repos/pandas-dev/pandas/pulls/53578
2023-06-09T18:41:54Z
2023-06-09T22:48:40Z
2023-06-09T22:48:40Z
2023-06-09T22:48:43Z
PDEP-1 Revision (Decision Making)
diff --git a/web/pandas/pdeps/0001-purpose-and-guidelines.md b/web/pandas/pdeps/0001-purpose-and-guidelines.md index 24c91fbab0808..49a3bc4c871cd 100644 --- a/web/pandas/pdeps/0001-purpose-and-guidelines.md +++ b/web/pandas/pdeps/0001-purpose-and-guidelines.md @@ -6,7 +6,7 @@ [#51417](https://github.com/pandas-dev/pandas/pull/51417) - Author: [Marc Garcia](https://github.com/datapythonista), [Noa Tamir](https://github.com/noatamir) -- Revision: 2 +- Revision: 3 ## PDEP definition, purpose and scope @@ -56,12 +56,24 @@ advisor on the PDEP when it is submitted to the PDEP repository. ### Workflow +#### Rationale + +Our workflow was created to support and enable a consensus seeking process, and to provide clarity, +for current and future authors, as well as voting members. It is not a strict policy, and we +discourage any interpretation which seeks to take advantage of it in a way that could "force" or +"sneak" decisions in one way or another. We expect and encourage transparency, active discussion, +feedback, and compromise from all our community members. + +#### PDEP States + The possible states of a PDEP are: +- Draft - Under discussion - Accepted - Implemented - Rejected +- Withdrawn Next is described the workflow that PDEPs can follow. @@ -71,16 +83,75 @@ Proposing a PDEP is done by creating a PR adding a new file to `web/pdeps/`. The file is a markdown file, you can use `web/pdeps/0001.md` as a reference for the expected format. -The initial status of a PDEP will be `Status: Under discussion`. This will be changed to -`Status: Accepted` when the PDEP is ready and has the approval of the core team. +The initial status of a PDEP will be `Status: Draft`. This will be changed to +`Status: Under discussion` by the author(s), when they are ready to proceed with the decision +making process. -#### Accepted PDEP +#### PDEP Discussion Timeline + +A PDEP discussion will remain open for up to 60 days. This period aims to enable participation +from volunteers, who might not always be available to respond quickly, as well as provide ample +time to make changes based on suggestions and considerations offered by the participants. +Similarly, the following voting period will remain open for 15 days. + +To enable and encourage discussions on PDEPs, we follow a notification schedule. At each of the +following steps, the pandas team, and the pandas-dev mailing list are notified via GitHub and +E-mail: + +- Once a PDEP is ready for discussion. +- After 30 days, with a note that there is at most 30 days remaining for discussion, + and that a vote will be called for if no discussion occurs in the next 15 days. +- After 45 days, with a note that there is at most 15 days remaining for discussion, + and that a vote will be called for in 15 days. +- Once the voting period starts, after 60 days or in case of an earlier vote, with 15 days + remaining for voting. +- After 10 voting days, with 5 days remaining for voting. + +After 30 discussion days, in case 15 days passed without any new unaddressed comments, +the authors may close the discussion period preemptively, by sending an early reminder +of 15 days remaining until the voting period starts. + +#### Casting Votes + +As the voting period starts, a VOTE issue is created which links to the PDEP discussion pull request. +Each voting member, including author(s) with voting rights, may cast a vote by adding one of the following comments: + +- +1: approve. +- 0: abstain. + - Reason: A one sentence reason is required. +- -1: disapprove + - Reason: A one sentence reason is required. + +A disapprove vote requires prior participation in the PDEP discussion issue. -A PDEP can only be accepted by the core development team, if the proposal is considered -worth implementing. Decisions will be made based on the process detailed in the -[pandas governance document](https://github.com/pandas-dev/pandas-governance/blob/master/governance.md). -In general, more than one approval will be needed before the PR is merged. And -there should not be any `Request changes` review at the time of merging. +Comments made on the public VOTE issue by non-voting members will be deleted. + +Once the voting period ends, any voter may tally the votes in a comment, using the format: w-x-y-z, +where w stands for the total of approving, x of abstaining, y of disapproving votes cast, and z +of number of voting members who did not respond to the VOTE issue. The tally of the votes will state +if a quorum has been reached or not. + +#### Quorum and Majority + +For a PDEP vote to result in accepting the proposal, a quorum is required. All votes (including +abstentions) are counted towards the quorum. The quorum is computed as the lower of these two +values: + +- 11 voting members. +- 50% of voting members. + +Given a quorum, a majority of 70% of the non-abstaining votes is required as well, i.e. 70% of +the approving and disapproving votes must be in favor. + +Thus, abstaining votes count towards a quorum, but not towards a majority. A voting member might +choose to abstain when they have participated in the discussion, have some objections to the +proposal, but do not wish to stop the proposal from moving forward, nor indicate their full +support. + +If a quorum was not reached by the end of the voting period, the PDEP is not accepted. Its status +will change to rejected. + +#### Accepted PDEP Once a PDEP is accepted, any contributions can be made toward the implementation of the PDEP, with an open-ended completion timeline. Development of pandas is difficult to understand and @@ -109,6 +180,17 @@ discussion. A PDEP can be rejected for different reasons, for example good ideas that are not backward-compatible, and the breaking changes are not considered worth implementing. +The PDEP author(s) can also decide to withdraw the PDEP before a final decision +is made (`Status: Withdrawn`), when the PDEP authors themselves have decided +that the PDEP is actually a bad idea, or have accepted that it is not broadly +supported or a competing proposal is a better alternative. + +The author(s) may choose to resubmit a rejected or withdrawn PDEP. We expect +authors to use their judgement in that case, as to whether they believe more +discussion, or an amended proposal has the potential to lead to a different +result. A new PDEP is then created, which includes a link to the previously +rejected PDEP. + #### Invalid PDEP For submitted PDEPs that do not contain proper documentation, are out of scope, or @@ -184,6 +266,7 @@ hope can help clarify our meaning here: - 3 August 2022: Initial version ([GH-47938][47938]) - 15 February 2023: Version 2 ([GH-51417][51417]) clarifies the scope of PDEPs and adds examples +- 09 June 2023: Version 3 ([GH-53576][53576]) defines a structured decision making process for PDEPs [7217]: https://github.com/pandas-dev/pandas/pull/7217 [8074]: https://github.com/pandas-dev/pandas/issues/8074
The governance working group has been discussing the PDEP workflow and decision-making for some time now. **Feedback is welcome.** This PR proposes some formulation of the existing workflow to clarify and facilitate it for current and future authors, and voting members. In our discussions, we assessed that a more structured process would help folks who submit the PDEP know how and when it can progress, and how to better engage with others. The timelines were considered to facilitate an engaging discussion, and automation. We aim to make the lives of the PDEP authors easier by taking away the need to decide "has it been long enough", or "cat herding" folks to engage and clarify their comments so that PDEPs don't get large change requests that could have been clarified early on - late in the process. The quorum was discussed a lot in our working group, and we're unsure about the best strategy here. We were looking for a sufficient number so if a decision is passed one feels it's valid (e.g. maybe 2 people is too low), but not too high so that we feel like ongoing discussions are blocked because it's too hard to get that many voting members involved. Further proposal on this point are welcome. We tried to make things as flexible and clear as possible. Being mindful of the needs of the authors, as well as those engaging in the discussion, be them voting members or not. At this point, we would like to invite feedback. It might be that you need more clarity on the suggestions, have ideas for improvement, or aren't convinced that this will affect the current process positively. Co-authored-by: @MarcoGorelli, @rhshadrach, @Dr-Irv, @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/53576
2023-06-09T15:32:48Z
2024-04-01T18:27:58Z
2024-04-01T18:27:58Z
2024-04-01T20:21:32Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 598281e331f5c..3ddb9d4ff6d54 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -263,15 +263,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.window.ewm.ExponentialMovingWindow.cov \ pandas.api.indexers.BaseIndexer \ pandas.api.indexers.VariableOffsetWindowIndexer \ - pandas.core.groupby.DataFrameGroupBy.ffill \ - pandas.core.groupby.DataFrameGroupBy.ohlc \ pandas.core.groupby.SeriesGroupBy.fillna \ - pandas.core.groupby.SeriesGroupBy.ffill \ - pandas.core.groupby.SeriesGroupBy.nunique \ - pandas.core.groupby.SeriesGroupBy.ohlc \ - pandas.core.groupby.SeriesGroupBy.hist \ - pandas.core.groupby.DataFrameGroupBy.plot \ - pandas.core.groupby.SeriesGroupBy.plot \ pandas.io.formats.style.Styler \ pandas.io.formats.style.Styler.from_custom_template \ pandas.io.formats.style.Styler.set_caption \ diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 3e4da10d8b25b..eef3de3e61f29 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -622,6 +622,22 @@ def nunique(self, dropna: bool = True) -> Series | DataFrame: ------- Series Number of unique values within each group. + + Examples + -------- + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 3 + dtype: int64 + >>> ser.groupby(level=0).nunique() + a 2 + b 1 + dtype: int64 """ ids, _, _ = self.grouper.group_info diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 4ef9b02e3afad..299b58ddce591 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3107,6 +3107,50 @@ def ohlc(self) -> DataFrame: ------- DataFrame Open, high, low and close values within each group. + + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['SPX', 'CAC', 'SPX', 'CAC', 'SPX', 'CAC', 'SPX', 'CAC',] + >>> ser = pd.Series([3.4, 9.0, 7.2, 5.2, 8.8, 9.4, 0.1, 0.5], index=lst) + >>> ser + SPX 3.4 + CAC 9.0 + SPX 7.2 + CAC 5.2 + SPX 8.8 + CAC 9.4 + SPX 0.1 + CAC 0.5 + dtype: float64 + >>> ser.groupby(level=0).ohlc() + open high low close + CAC 9.0 9.4 0.5 0.5 + SPX 3.4 8.8 0.1 0.1 + + For DataFrameGroupBy: + + >>> data = {2022: [1.2, 2.3, 8.9, 4.5, 4.4, 3, 2 , 1], + ... 2023: [3.4, 9.0, 7.2, 5.2, 8.8, 9.4, 8.2, 1.0]} + >>> df = pd.DataFrame(data, index=['SPX', 'CAC', 'SPX', 'CAC', + ... 'SPX', 'CAC', 'SPX', 'CAC']) + >>> df + 2022 2023 + SPX 1.2 3.4 + CAC 2.3 9.0 + SPX 8.9 7.2 + CAC 4.5 5.2 + SPX 4.4 8.8 + CAC 3.0 9.4 + SPX 2.0 8.2 + CAC 1.0 1.0 + >>> df.groupby(level=0).ohlc() + 2022 2023 + open high low close open high low close + CAC 2.3 4.5 1.0 1.0 9.0 9.4 1.0 1.0 + SPX 1.2 8.9 1.2 2.0 3.4 8.8 3.4 8.2 """ if self.obj.ndim == 1: obj = self._selected_obj @@ -3561,6 +3605,26 @@ def ffill(self, limit: int | None = None): Examples -------- + + For SeriesGroupBy: + + >>> key = [0, 0, 1, 1] + >>> ser = pd.Series([np.nan, 2, 3, np.nan], index=key) + >>> ser + 0 NaN + 0 2.0 + 1 3.0 + 1 NaN + dtype: float64 + >>> ser.groupby(level=0).ffill() + 0 NaN + 0 2.0 + 1 3.0 + 1 3.0 + dtype: float64 + + For DataFrameGroupBy: + >>> df = pd.DataFrame( ... { ... "key": [0, 0, 1, 1, 1], diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 0f9fd948b6fe5..24b8816109677 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -98,6 +98,16 @@ def hist_series( See Also -------- matplotlib.axes.Axes.hist : Plot a histogram using matplotlib. + + Examples + -------- + + .. plot:: + :context: close-figs + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst) + >>> hist = ser.groupby(level=0).hist() """ plot_backend = _get_plot_backend(backend) return plot_backend.hist_series( @@ -778,12 +788,23 @@ class PlotAccessor(PandasObject): Examples -------- + For SeriesGroupBy: .. plot:: :context: close-figs >>> ser = pd.Series([1, 2, 3, 3]) >>> plot = ser.plot(kind='hist', title="My plot") + + For DataFrameGroupBy: + + .. plot:: + :context: close-figs + + >>> df = pd.DataFrame({'length': [1.5, 0.5, 1.2, 0.9, 3], + ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1]}, + ... index=['pig', 'rabbit', 'duck', 'chicken', 'horse']) + >>> plot = df.plot() """ _common_kinds = ("line", "bar", "barh", "kde", "density", "area", "hist", "box")
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53575
2023-06-09T14:51:35Z
2023-06-09T20:15:24Z
2023-06-09T20:15:24Z
2023-06-10T14:25:53Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 191e0d03b3a1a..598281e331f5c 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -263,22 +263,12 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.window.ewm.ExponentialMovingWindow.cov \ pandas.api.indexers.BaseIndexer \ pandas.api.indexers.VariableOffsetWindowIndexer \ - pandas.core.groupby.DataFrameGroupBy.diff \ pandas.core.groupby.DataFrameGroupBy.ffill \ - pandas.core.groupby.DataFrameGroupBy.median \ pandas.core.groupby.DataFrameGroupBy.ohlc \ - pandas.core.groupby.DataFrameGroupBy.skew \ - pandas.core.groupby.DataFrameGroupBy.std \ - pandas.core.groupby.DataFrameGroupBy.var \ - pandas.core.groupby.SeriesGroupBy.diff \ pandas.core.groupby.SeriesGroupBy.fillna \ pandas.core.groupby.SeriesGroupBy.ffill \ - pandas.core.groupby.SeriesGroupBy.median \ pandas.core.groupby.SeriesGroupBy.nunique \ pandas.core.groupby.SeriesGroupBy.ohlc \ - pandas.core.groupby.SeriesGroupBy.skew \ - pandas.core.groupby.SeriesGroupBy.std \ - pandas.core.groupby.SeriesGroupBy.var \ pandas.core.groupby.SeriesGroupBy.hist \ pandas.core.groupby.DataFrameGroupBy.plot \ pandas.core.groupby.SeriesGroupBy.plot \ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c372235481614..4ef9b02e3afad 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2217,6 +2217,44 @@ def median(self, numeric_only: bool = False): ------- Series or DataFrame Median of values within each group. + + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst) + >>> ser + a 7 + a 2 + a 8 + b 4 + b 3 + b 3 + dtype: int64 + >>> ser.groupby(level=0).median() + a 7.0 + b 3.0 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = {'a': [1, 3, 5, 7, 7, 8, 3], 'b': [1, 4, 8, 4, 4, 2, 1]} + >>> df = pd.DataFrame(data, index=['dog', 'dog', 'dog', + ... 'mouse', 'mouse', 'mouse', 'mouse']) + >>> df + a b + dog 1 1 + dog 3 4 + dog 5 8 + mouse 7 4 + mouse 7 4 + mouse 8 2 + mouse 3 1 + >>> df.groupby(level=0).median() + a b + dog 3.0 4.0 + mouse 7.0 3.0 """ result = self._cython_agg_general( "median", @@ -2227,7 +2265,7 @@ def median(self, numeric_only: bool = False): @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def std( self, ddof: int = 1, @@ -2275,6 +2313,44 @@ def std( ------- Series or DataFrame Standard deviation of values within each group. + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst) + >>> ser + a 7 + a 2 + a 8 + b 4 + b 3 + b 3 + dtype: int64 + >>> ser.groupby(level=0).std() + a 3.21455 + b 0.57735 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = {'a': [1, 3, 5, 7, 7, 8, 3], 'b': [1, 4, 8, 4, 4, 2, 1]} + >>> df = pd.DataFrame(data, index=['dog', 'dog', 'dog', + ... 'mouse', 'mouse', 'mouse', 'mouse']) + >>> df + a b + dog 1 1 + dog 3 4 + dog 5 8 + mouse 7 4 + mouse 7 4 + mouse 8 2 + mouse 3 1 + >>> df.groupby(level=0).std() + a b + dog 2.000000 3.511885 + mouse 2.217356 1.500000 """ if maybe_use_numba(engine): from pandas.core._numba.kernels import sliding_var @@ -2290,7 +2366,7 @@ def std( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def var( self, ddof: int = 1, @@ -2338,6 +2414,44 @@ def var( ------- Series or DataFrame Variance of values within each group. + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst) + >>> ser + a 7 + a 2 + a 8 + b 4 + b 3 + b 3 + dtype: int64 + >>> ser.groupby(level=0).var() + a 10.333333 + b 0.333333 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = {'a': [1, 3, 5, 7, 7, 8, 3], 'b': [1, 4, 8, 4, 4, 2, 1]} + >>> df = pd.DataFrame(data, index=['dog', 'dog', 'dog', + ... 'mouse', 'mouse', 'mouse', 'mouse']) + >>> df + a b + dog 1 1 + dog 3 4 + dog 5 8 + mouse 7 4 + mouse 7 4 + mouse 8 2 + mouse 3 1 + >>> df.groupby(level=0).var() + a b + dog 4.000000 12.333333 + mouse 4.916667 2.250000 """ if maybe_use_numba(engine): from pandas.core._numba.kernels import sliding_var @@ -4569,7 +4683,7 @@ def shift( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def diff( self, periods: int = 1, axis: AxisInt | lib.NoDefault = lib.no_default ) -> NDFrameT: @@ -4594,6 +4708,53 @@ def diff( ------- Series or DataFrame First differences. + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst) + >>> ser + a 7 + a 2 + a 8 + b 4 + b 3 + b 3 + dtype: int64 + >>> ser.groupby(level=0).diff() + a NaN + a -5.0 + a 6.0 + b NaN + b -1.0 + b 0.0 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = {'a': [1, 3, 5, 7, 7, 8, 3], 'b': [1, 4, 8, 4, 4, 2, 1]} + >>> df = pd.DataFrame(data, index=['dog', 'dog', 'dog', + ... 'mouse', 'mouse', 'mouse', 'mouse']) + >>> df + a b + dog 1 1 + dog 3 4 + dog 5 8 + mouse 7 4 + mouse 7 4 + mouse 8 2 + mouse 3 1 + >>> df.groupby(level=0).diff() + a b + dog NaN NaN + dog 2.0 3.0 + dog 2.0 4.0 + mouse NaN NaN + mouse 0.0 0.0 + mouse 1.0 -2.0 + mouse -5.0 -1.0 """ if axis is not lib.no_default: axis = self.obj._get_axis_number(axis)
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53573
2023-06-09T10:26:20Z
2023-06-09T16:56:20Z
2023-06-09T16:56:20Z
2023-06-10T14:26:10Z
DOC: Multi-conditional examples added to .loc docstring
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 38bf6c34bf9c9..4a2803f638c73 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -400,6 +400,29 @@ def loc(self) -> _LocIndexer: max_speed sidewinder 7 + Multiple conditional using ``&`` that returns a boolean Series + + >>> df.loc[(df['max_speed'] > 1) & (df['shield'] < 8)] + max_speed shield + viper 4 5 + + Multiple conditional using ``|`` that returns a boolean Series + + >>> df.loc[(df['max_speed'] > 4) | (df['shield'] < 5)] + max_speed shield + cobra 1 2 + sidewinder 7 8 + + Please ensure that each condition is wrapped in parentheses ``()``. + See the :ref:`user guide<indexing.boolean>` + for more details and explanations of Boolean indexing. + + .. note:: + If you find yourself using 3 or more conditionals in ``.loc[]``, + consider using :ref:`advanced indexing<advanced.advanced_hierarchical>`. + + See below for using ``.loc[]`` on MultiIndex DataFrames. + Callable that returns a boolean Series >>> df.loc[lambda df: df['shield'] == 8]
- [ ] closes #53546 Adds two examples of using `.loc` with multiple conditions and links to Boolean Indexing [user guide](https://pandas.pydata.org/pandas-docs/dev/user_guide/indexing.html#boolean-indexing). NOTE: I was unable to get the documentation to build on my computer so I could not view the changes before opening this PR. I will have to view them by trying the `/preview` comment.
https://api.github.com/repos/pandas-dev/pandas/pulls/53572
2023-06-09T00:48:15Z
2023-06-12T18:10:33Z
2023-06-12T18:10:33Z
2023-06-12T18:44:36Z
DEPR: deprecate obj argument in GroupBy.get_group
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index e2f0904a78cf9..3c4ca23797f2c 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -289,6 +289,7 @@ Deprecations - Deprecated constructing :class:`SparseArray` from scalar data, pass a sequence instead (:issue:`53039`) - Deprecated falling back to filling when ``value`` is not specified in :meth:`DataFrame.replace` and :meth:`Series.replace` with non-dict-like ``to_replace`` (:issue:`33302`) - Deprecated option "mode.use_inf_as_na", convert inf entries to ``NaN`` before instead (:issue:`51684`) +- Deprecated parameter ``obj`` in :meth:`GroupBy.get_group` (:issue:`53545`) - Deprecated positional indexing on :class:`Series` with :meth:`Series.__getitem__` and :meth:`Series.__setitem__`, in a future version ``ser[item]`` will *always* interpret ``item`` as a label, not a position (:issue:`50617`) - Deprecated the "method" and "limit" keywords on :meth:`Series.fillna`, :meth:`DataFrame.fillna`, :meth:`SeriesGroupBy.fillna`, :meth:`DataFrameGroupBy.fillna`, and :meth:`Resampler.fillna`, use ``obj.bfill()`` or ``obj.ffill()`` instead (:issue:`53394`) - Deprecated the ``method`` and ``limit`` keywords in :meth:`DataFrame.replace` and :meth:`Series.replace` (:issue:`33302`) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 5b6d28ac9ab4a..248ab6bcdd4df 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -925,6 +925,11 @@ def get_group(self, name, obj=None) -> DataFrame | Series: it is None, the object groupby was called on will be used. + .. deprecated:: 2.1.0 + The obj is deprecated and will be removed in a future version. + Do ``df.iloc[gb.indices.get(name)]`` + instead of ``gb.get_group(name, obj=df)``. + Returns ------- same type as obj @@ -961,14 +966,21 @@ def get_group(self, name, obj=None) -> DataFrame | Series: owl 1 2 3 toucan 1 5 6 """ - if obj is None: - obj = self._selected_obj - inds = self._get_index(name) if not len(inds): raise KeyError(name) - return obj._take_with_is_copy(inds, axis=self.axis) + if obj is None: + return self._selected_obj.iloc[inds] + else: + warnings.warn( + "obj is deprecated and will be removed in a future version. " + "Do ``df.iloc[gb.indices.get(name)]`` " + "instead of ``gb.get_group(name, obj=df)``.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return obj._take_with_is_copy(inds, axis=self.axis) @final def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index bf0b646847ed6..775016c673f4d 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -695,6 +695,16 @@ def test_as_index_select_column(): tm.assert_series_equal(result, expected) +def test_obj_arg_get_group_deprecated(): + depr_msg = "obj is deprecated" + + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + expected = df.iloc[df.groupby("b").indices.get(4)] + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.groupby("b").get_group(4, obj=df) + tm.assert_frame_equal(result, expected) + + def test_groupby_as_index_select_column_sum_empty_df(): # GH 35246 df = DataFrame(columns=Index(["A", "B", "C"], name="alpha"))
- [x] closes #53545 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). `obj` argument was deprecated in `GroupBy.get_group` and removed from the parameters in `GroupBy.get_group` docs.
https://api.github.com/repos/pandas-dev/pandas/pulls/53571
2023-06-08T23:32:56Z
2023-06-19T01:46:39Z
2023-06-19T01:46:39Z
2023-06-19T07:10:35Z
TST: Use more pytest fixtures
diff --git a/pandas/tests/arrays/sparse/test_indexing.py b/pandas/tests/arrays/sparse/test_indexing.py index f639e9b18596c..d63d0fb07b404 100644 --- a/pandas/tests/arrays/sparse/test_indexing.py +++ b/pandas/tests/arrays/sparse/test_indexing.py @@ -6,18 +6,25 @@ import pandas._testing as tm from pandas.core.arrays.sparse import SparseArray -arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6]) -arr = SparseArray(arr_data) + +@pytest.fixture +def arr_data(): + return np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6]) + + +@pytest.fixture +def arr(arr_data): + return SparseArray(arr_data) class TestGetitem: - def test_getitem(self): + def test_getitem(self, arr): dense = arr.to_dense() for i, value in enumerate(arr): tm.assert_almost_equal(value, dense[i]) tm.assert_almost_equal(arr[-i], dense[-i]) - def test_getitem_arraylike_mask(self): + def test_getitem_arraylike_mask(self, arr): arr = SparseArray([0, 1, 2]) result = arr[[True, False, True]] expected = SparseArray([0, 2]) @@ -81,7 +88,7 @@ def test_boolean_slice_empty(self): res = arr[[False, False, False]] assert res.dtype == arr.dtype - def test_getitem_bool_sparse_array(self): + def test_getitem_bool_sparse_array(self, arr): # GH 23122 spar_bool = SparseArray([False, True] * 5, dtype=np.bool_, fill_value=True) exp = SparseArray([np.nan, 2, np.nan, 5, 6]) @@ -106,7 +113,7 @@ def test_getitem_bool_sparse_array_as_comparison(self): exp = SparseArray([3.0, 4.0], fill_value=np.nan) tm.assert_sp_array_equal(res, exp) - def test_get_item(self): + def test_get_item(self, arr): zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0) assert np.isnan(arr[1]) @@ -129,7 +136,7 @@ def test_get_item(self): class TestSetitem: - def test_set_item(self): + def test_set_item(self, arr_data): arr = SparseArray(arr_data).copy() def setitem(): @@ -146,12 +153,12 @@ def setslice(): class TestTake: - def test_take_scalar_raises(self): + def test_take_scalar_raises(self, arr): msg = "'indices' must be an array, not a scalar '2'." with pytest.raises(ValueError, match=msg): arr.take(2) - def test_take(self): + def test_take(self, arr_data, arr): exp = SparseArray(np.take(arr_data, [2, 3])) tm.assert_sp_array_equal(arr.take([2, 3]), exp) @@ -173,14 +180,14 @@ def test_take_fill_value(self): exp = SparseArray(np.take(data, [1, 3, 4]), fill_value=0) tm.assert_sp_array_equal(sparse.take([1, 3, 4]), exp) - def test_take_negative(self): + def test_take_negative(self, arr_data, arr): exp = SparseArray(np.take(arr_data, [-1])) tm.assert_sp_array_equal(arr.take([-1]), exp) exp = SparseArray(np.take(arr_data, [-4, -3, -2])) tm.assert_sp_array_equal(arr.take([-4, -3, -2]), exp) - def test_bad_take(self): + def test_bad_take(self, arr): with pytest.raises(IndexError, match="bounds"): arr.take([11]) diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index b7517b1b16445..7a77a2064e7e0 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -14,77 +14,74 @@ make_sparse_index, ) -TEST_LENGTH = 20 - -plain_case = [ - [0, 7, 15], - [3, 5, 5], - [2, 9, 14], - [2, 3, 5], - [2, 9, 15], - [1, 3, 4], -] -delete_blocks = [ - [0, 5], - [4, 4], - [1], - [4], - [1], - [3], -] -split_blocks = [ - [0], - [10], - [0, 5], - [3, 7], - [0, 5], - [3, 5], -] -skip_block = [ - [10], - [5], - [0, 12], - [5, 3], - [12], - [3], -] - -no_intersect = [ - [0, 10], - [4, 6], - [5, 17], - [4, 2], - [], - [], -] - -one_empty = [ - [0], - [5], - [], - [], - [], - [], -] - -both_empty = [ # type: ignore[var-annotated] - [], - [], - [], - [], - [], - [], -] - -CASES = [plain_case, delete_blocks, split_blocks, skip_block, no_intersect, one_empty] -IDS = [ - "plain_case", - "delete_blocks", - "split_blocks", - "skip_block", - "no_intersect", - "one_empty", -] + +@pytest.fixture +def test_length(): + return 20 + + +@pytest.fixture( + params=[ + [ + [0, 7, 15], + [3, 5, 5], + [2, 9, 14], + [2, 3, 5], + [2, 9, 15], + [1, 3, 4], + ], + [ + [0, 5], + [4, 4], + [1], + [4], + [1], + [3], + ], + [ + [0], + [10], + [0, 5], + [3, 7], + [0, 5], + [3, 5], + ], + [ + [10], + [5], + [0, 12], + [5, 3], + [12], + [3], + ], + [ + [0, 10], + [4, 6], + [5, 17], + [4, 2], + [], + [], + ], + [ + [0], + [5], + [], + [], + [], + [], + ], + ], + ids=[ + "plain_case", + "delete_blocks", + "split_blocks", + "skip_block", + "no_intersect", + "one_empty", + ], +) +def cases(request): + return request.param class TestSparseIndexUnion: @@ -101,7 +98,7 @@ class TestSparseIndexUnion: [[0, 10], [3, 3], [5, 15], [2, 2], [0, 5, 10, 15], [3, 2, 3, 2]], ], ) - def test_index_make_union(self, xloc, xlen, yloc, ylen, eloc, elen): + def test_index_make_union(self, xloc, xlen, yloc, ylen, eloc, elen, test_length): # Case 1 # x: ---- # y: ---- @@ -132,8 +129,8 @@ def test_index_make_union(self, xloc, xlen, yloc, ylen, eloc, elen): # Case 8 # x: ---- --- # y: --- --- - xindex = BlockIndex(TEST_LENGTH, xloc, xlen) - yindex = BlockIndex(TEST_LENGTH, yloc, ylen) + xindex = BlockIndex(test_length, xloc, xlen) + yindex = BlockIndex(test_length, yloc, ylen) bresult = xindex.make_union(yindex) assert isinstance(bresult, BlockIndex) tm.assert_numpy_array_equal(bresult.blocs, np.array(eloc, dtype=np.int32)) @@ -180,12 +177,12 @@ def test_int_index_make_union(self): class TestSparseIndexIntersect: @td.skip_if_windows - @pytest.mark.parametrize("xloc, xlen, yloc, ylen, eloc, elen", CASES, ids=IDS) - def test_intersect(self, xloc, xlen, yloc, ylen, eloc, elen): - xindex = BlockIndex(TEST_LENGTH, xloc, xlen) - yindex = BlockIndex(TEST_LENGTH, yloc, ylen) - expected = BlockIndex(TEST_LENGTH, eloc, elen) - longer_index = BlockIndex(TEST_LENGTH + 1, yloc, ylen) + def test_intersect(self, cases, test_length): + xloc, xlen, yloc, ylen, eloc, elen = cases + xindex = BlockIndex(test_length, xloc, xlen) + yindex = BlockIndex(test_length, yloc, ylen) + expected = BlockIndex(test_length, eloc, elen) + longer_index = BlockIndex(test_length + 1, yloc, ylen) result = xindex.intersect(yindex) assert result.equals(expected) @@ -493,10 +490,10 @@ def test_equals(self): assert index.equals(index) assert not index.equals(IntIndex(10, [0, 1, 2, 3])) - @pytest.mark.parametrize("xloc, xlen, yloc, ylen, eloc, elen", CASES, ids=IDS) - def test_to_block_index(self, xloc, xlen, yloc, ylen, eloc, elen): - xindex = BlockIndex(TEST_LENGTH, xloc, xlen) - yindex = BlockIndex(TEST_LENGTH, yloc, ylen) + def test_to_block_index(self, cases, test_length): + xloc, xlen, yloc, ylen, _, _ = cases + xindex = BlockIndex(test_length, xloc, xlen) + yindex = BlockIndex(test_length, yloc, ylen) # see if survive the round trip xbindex = xindex.to_int_index().to_block_index() @@ -512,13 +509,13 @@ def test_to_int_index(self): class TestSparseOperators: @pytest.mark.parametrize("opname", ["add", "sub", "mul", "truediv", "floordiv"]) - @pytest.mark.parametrize("xloc, xlen, yloc, ylen, eloc, elen", CASES, ids=IDS) - def test_op(self, opname, xloc, xlen, yloc, ylen, eloc, elen): + def test_op(self, opname, cases, test_length): + xloc, xlen, yloc, ylen, _, _ = cases sparse_op = getattr(splib, f"sparse_{opname}_float64") python_op = getattr(operator, opname) - xindex = BlockIndex(TEST_LENGTH, xloc, xlen) - yindex = BlockIndex(TEST_LENGTH, yloc, ylen) + xindex = BlockIndex(test_length, xloc, xlen) + yindex = BlockIndex(test_length, yloc, ylen) xdindex = xindex.to_int_index() ydindex = yindex.to_int_index() @@ -542,10 +539,10 @@ def test_op(self, opname, xloc, xlen, yloc, ylen, eloc, elen): # check versus Series... xseries = Series(x, xdindex.indices) - xseries = xseries.reindex(np.arange(TEST_LENGTH)).fillna(xfill) + xseries = xseries.reindex(np.arange(test_length)).fillna(xfill) yseries = Series(y, ydindex.indices) - yseries = yseries.reindex(np.arange(TEST_LENGTH)).fillna(yfill) + yseries = yseries.reindex(np.arange(test_length)).fillna(yfill) series_result = python_op(xseries, yseries) series_result = series_result.reindex(ri_index.indices) diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py index 36b7dcfe4db12..de36d52921622 100644 --- a/pandas/tests/indexing/multiindex/test_indexing_slow.py +++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py @@ -1,8 +1,3 @@ -from typing import ( - Any, - List, -) - import numpy as np import pytest @@ -13,78 +8,72 @@ ) import pandas._testing as tm -m = 50 -n = 1000 -cols = ["jim", "joe", "jolie", "joline", "jolia"] - -vals: List[Any] = [ - np.random.randint(0, 10, n), - np.random.choice(list("abcdefghij"), n), - np.random.choice(pd.date_range("20141009", periods=10).tolist(), n), - np.random.choice(list("ZYXWVUTSRQ"), n), - np.random.randn(n), -] -vals = list(map(tuple, zip(*vals))) - -# bunch of keys for testing -keys: List[Any] = [ - np.random.randint(0, 11, m), - np.random.choice(list("abcdefghijk"), m), - np.random.choice(pd.date_range("20141009", periods=11).tolist(), m), - np.random.choice(list("ZYXWVUTSRQP"), m), -] -keys = list(map(tuple, zip(*keys))) -keys += [t[:-1] for t in vals[:: n // m]] + +@pytest.fixture +def m(): + return 50 + + +@pytest.fixture +def n(): + return 1000 + + +@pytest.fixture +def cols(): + return ["jim", "joe", "jolie", "joline", "jolia"] + + +@pytest.fixture +def vals(n): + vals = [ + np.random.randint(0, 10, n), + np.random.choice(list("abcdefghij"), n), + np.random.choice(pd.date_range("20141009", periods=10).tolist(), n), + np.random.choice(list("ZYXWVUTSRQ"), n), + np.random.randn(n), + ] + vals = list(map(tuple, zip(*vals))) + return vals + + +@pytest.fixture +def keys(n, m, vals): + # bunch of keys for testing + keys = [ + np.random.randint(0, 11, m), + np.random.choice(list("abcdefghijk"), m), + np.random.choice(pd.date_range("20141009", periods=11).tolist(), m), + np.random.choice(list("ZYXWVUTSRQP"), m), + ] + keys = list(map(tuple, zip(*keys))) + keys += [t[:-1] for t in vals[:: n // m]] + return keys # covers both unique index and non-unique index -df = DataFrame(vals, columns=cols) -a = pd.concat([df, df]) -b = df.drop_duplicates(subset=cols[:-1]) - - -def validate(mi, df, key): - # check indexing into a multi-index before & past the lexsort depth - - mask = np.ones(len(df), dtype=bool) - - # test for all partials of this key - for i, k in enumerate(key): - mask &= df.iloc[:, i] == k - - if not mask.any(): - assert key[: i + 1] not in mi.index - continue - - assert key[: i + 1] in mi.index - right = df[mask].copy(deep=False) - - if i + 1 != len(key): # partial key - return_value = right.drop(cols[: i + 1], axis=1, inplace=True) - assert return_value is None - return_value = right.set_index(cols[i + 1 : -1], inplace=True) - assert return_value is None - tm.assert_frame_equal(mi.loc[key[: i + 1]], right) - - else: # full key - return_value = right.set_index(cols[:-1], inplace=True) - assert return_value is None - if len(right) == 1: # single hit - right = Series( - right["jolia"].values, name=right.index[0], index=["jolia"] - ) - tm.assert_series_equal(mi.loc[key[: i + 1]], right) - else: # multi hit - tm.assert_frame_equal(mi.loc[key[: i + 1]], right) +@pytest.fixture +def df(vals, cols): + return DataFrame(vals, columns=cols) + + +@pytest.fixture +def a(df): + return pd.concat([df, df]) + + +@pytest.fixture +def b(df, cols): + return df.drop_duplicates(subset=cols[:-1]) @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") @pytest.mark.parametrize("lexsort_depth", list(range(5))) -@pytest.mark.parametrize("key", keys) -@pytest.mark.parametrize("frame", [a, b]) -def test_multiindex_get_loc(lexsort_depth, key, frame): +@pytest.mark.parametrize("frame_fixture", ["a", "b"]) +def test_multiindex_get_loc(request, lexsort_depth, keys, frame_fixture, cols): # GH7724, GH2646 + frame = request.getfixturevalue(frame_fixture) if lexsort_depth == 0: df = frame.copy(deep=False) else: @@ -92,4 +81,34 @@ def test_multiindex_get_loc(lexsort_depth, key, frame): mi = df.set_index(cols[:-1]) assert not mi.index._lexsort_depth < lexsort_depth - validate(mi, df, key) + for key in keys: + mask = np.ones(len(df), dtype=bool) + + # test for all partials of this key + for i, k in enumerate(key): + mask &= df.iloc[:, i] == k + + if not mask.any(): + assert key[: i + 1] not in mi.index + continue + + assert key[: i + 1] in mi.index + right = df[mask].copy(deep=False) + + if i + 1 != len(key): # partial key + return_value = right.drop(cols[: i + 1], axis=1, inplace=True) + assert return_value is None + return_value = right.set_index(cols[i + 1 : -1], inplace=True) + assert return_value is None + tm.assert_frame_equal(mi.loc[key[: i + 1]], right) + + else: # full key + return_value = right.set_index(cols[:-1], inplace=True) + assert return_value is None + if len(right) == 1: # single hit + right = Series( + right["jolia"].values, name=right.index[0], index=["jolia"] + ) + tm.assert_series_equal(mi.loc[key[: i + 1]], right) + else: # multi hit + tm.assert_frame_equal(mi.loc[key[: i + 1]], right) diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index b863e85cae457..68365c125a951 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -15,9 +15,15 @@ import pandas._testing as tm +import pandas.io.common as icom from pandas.io.parsers import read_csv +@pytest.fixture +def compression_to_extension(): + return {value: key for key, value in icom.extension_to_compression.items()} + + @pytest.fixture def tips_file(datapath): """Path to the tips dataset""" diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index a208daaf9f77b..32509a799fa69 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -13,7 +13,6 @@ compat, ) import pandas._testing as tm -from pandas.tests.io.test_compression import _compression_to_extension class TestToCSV: @@ -543,13 +542,15 @@ def test_to_csv_write_to_open_file_with_newline_py3(self): @pytest.mark.parametrize("to_infer", [True, False]) @pytest.mark.parametrize("read_infer", [True, False]) - def test_to_csv_compression(self, compression_only, read_infer, to_infer): + def test_to_csv_compression( + self, compression_only, read_infer, to_infer, compression_to_extension + ): # see gh-15008 compression = compression_only # We'll complete file extension subsequently. filename = "test." - filename += _compression_to_extension[compression] + filename += compression_to_extension[compression] df = DataFrame({"A": [1]}) diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index 143d2431d4147..4a7606eaf05d7 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -6,7 +6,6 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.io.test_compression import _compression_to_extension def test_compression_roundtrip(compression): @@ -91,13 +90,15 @@ def test_read_unsupported_compression_type(): @pytest.mark.parametrize("to_infer", [True, False]) @pytest.mark.parametrize("read_infer", [True, False]) -def test_to_json_compression(compression_only, read_infer, to_infer): +def test_to_json_compression( + compression_only, read_infer, to_infer, compression_to_extension +): # see gh-15008 compression = compression_only # We'll complete file extension subsequently. filename = "test." - filename += _compression_to_extension[compression] + filename += compression_to_extension[compression] df = pd.DataFrame({"A": [1]}) diff --git a/pandas/tests/io/parser/test_compression.py b/pandas/tests/io/parser/test_compression.py index bcba9c4a1823d..d150b52258d47 100644 --- a/pandas/tests/io/parser/test_compression.py +++ b/pandas/tests/io/parser/test_compression.py @@ -12,7 +12,6 @@ from pandas import DataFrame import pandas._testing as tm -from pandas.tests.io.test_compression import _compression_to_extension skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @@ -91,11 +90,18 @@ def test_zip_error_invalid_zip(parser_and_data): @skip_pyarrow @pytest.mark.parametrize("filename", [None, "test.{ext}"]) -def test_compression(request, parser_and_data, compression_only, buffer, filename): +def test_compression( + request, + parser_and_data, + compression_only, + buffer, + filename, + compression_to_extension, +): parser, data, expected = parser_and_data compress_type = compression_only - ext = _compression_to_extension[compress_type] + ext = compression_to_extension[compress_type] filename = filename if filename is None else filename.format(ext=ext) if filename and buffer: diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index a0d9c6ae99dcf..f3ae5b54d09ce 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -16,7 +16,6 @@ from pandas import DataFrame import pandas._testing as tm -from pandas.tests.io.test_compression import _compression_to_extension from pandas.io.feather_format import read_feather from pandas.io.parsers import read_csv @@ -32,10 +31,12 @@ ) @pytest.mark.parametrize("mode", ["explicit", "infer"]) @pytest.mark.parametrize("engine", ["python", "c"]) -def test_compressed_urls(salaries_table, mode, engine, compression_only): +def test_compressed_urls( + salaries_table, mode, engine, compression_only, compression_to_extension +): # test reading compressed urls with various engines and # extension inference - extension = _compression_to_extension[compression_only] + extension = compression_to_extension[compression_only] base_url = ( "https://github.com/pandas-dev/pandas/raw/main/" "pandas/tests/io/parser/data/salaries.csv" diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index 030650ad0031d..c682963c462cc 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -26,7 +26,6 @@ ArrowStringArray, StringArray, ) -from pandas.tests.io.test_compression import _compression_to_extension from pandas.io.common import urlopen from pandas.io.parsers import ( @@ -667,13 +666,13 @@ def test_default_delimiter(): @pytest.mark.parametrize("infer", [True, False]) -def test_fwf_compression(compression_only, infer): +def test_fwf_compression(compression_only, infer, compression_to_extension): data = """1111111111 2222222222 3333333333""".strip() compression = compression_only - extension = _compression_to_extension[compression] + extension = compression_to_extension[compression] kwargs = {"widths": [5, 5], "names": ["one", "two"]} expected = read_fwf(StringIO(data), **kwargs) diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index ac11e2165eb6f..c84670f0eb69c 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -18,10 +18,6 @@ import pandas.io.common as icom -_compression_to_extension = { - value: key for key, value in icom.extension_to_compression.items() -} - @pytest.mark.parametrize( "obj", @@ -84,11 +80,11 @@ def test_compression_size_fh(obj, method, compression_only): ], ) def test_dataframe_compression_defaults_to_infer( - write_method, write_kwargs, read_method, compression_only + write_method, write_kwargs, read_method, compression_only, compression_to_extension ): # GH22004 input = pd.DataFrame([[1.0, 0, -4], [3.4, 5, 2]], columns=["X", "Y", "Z"]) - extension = _compression_to_extension[compression_only] + extension = compression_to_extension[compression_only] with tm.ensure_clean("compressed" + extension) as path: getattr(input, write_method)(path, **write_kwargs) output = read_method(path, compression=compression_only) @@ -104,11 +100,16 @@ def test_dataframe_compression_defaults_to_infer( ], ) def test_series_compression_defaults_to_infer( - write_method, write_kwargs, read_method, read_kwargs, compression_only + write_method, + write_kwargs, + read_method, + read_kwargs, + compression_only, + compression_to_extension, ): # GH22004 input = pd.Series([0, 5, -2, 10], name="X") - extension = _compression_to_extension[compression_only] + extension = compression_to_extension[compression_only] with tm.ensure_clean("compressed" + extension) as path: getattr(input, write_method)(path, **write_kwargs) if "squeeze" in read_kwargs: diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 01e1be5529bad..7b139dc45624e 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -11,7 +11,7 @@ from pandas.io.feather_format import read_feather, to_feather # isort:skip -pyarrow = pytest.importorskip("pyarrow", minversion="1.0.1") +pyarrow = pytest.importorskip("pyarrow") @pytest.mark.single_cpu diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 18cc0f0b11dc9..d82cfd5bd169d 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -16,7 +16,6 @@ read_parquet, ) import pandas._testing as tm -from pandas.tests.io.test_compression import _compression_to_extension from pandas.util import _test_decorators as td @@ -132,7 +131,9 @@ def assert_equal_zip_safe(result: bytes, expected: bytes, compression: str): @td.skip_if_no("gcsfs") @pytest.mark.parametrize("encoding", ["utf-8", "cp1251"]) -def test_to_csv_compression_encoding_gcs(gcs_buffer, compression_only, encoding): +def test_to_csv_compression_encoding_gcs( + gcs_buffer, compression_only, encoding, compression_to_extension +): """ Compression and encoding should with GCS. @@ -161,7 +162,7 @@ def test_to_csv_compression_encoding_gcs(gcs_buffer, compression_only, encoding) tm.assert_frame_equal(df, read_df) # write compressed file with implicit compression - file_ext = _compression_to_extension[compression_only] + file_ext = compression_to_extension[compression_only] compression["method"] = "infer" path_gcs += f".{file_ext}" df.to_csv(path_gcs, compression=compression, encoding=encoding) diff --git a/pandas/tests/io/test_orc.py b/pandas/tests/io/test_orc.py index 36cfe5576adf9..571d9d5536e20 100644 --- a/pandas/tests/io/test_orc.py +++ b/pandas/tests/io/test_orc.py @@ -25,25 +25,19 @@ def dirpath(datapath): return datapath("io", "data", "orc") -# Examples of dataframes with dtypes for which conversion to ORC -# hasn't been implemented yet, that is, Category, unsigned integers, -# interval, period and sparse. -orc_writer_dtypes_not_supported = [ - pd.DataFrame({"unimpl": np.array([1, 20], dtype="uint64")}), - pd.DataFrame({"unimpl": pd.Series(["a", "b", "a"], dtype="category")}), - pd.DataFrame( - {"unimpl": [pd.Interval(left=0, right=2), pd.Interval(left=0, right=5)]} - ), - pd.DataFrame( - { - "unimpl": [ - pd.Period("2022-01-03", freq="D"), - pd.Period("2022-01-04", freq="D"), - ] - } - ), - pd.DataFrame({"unimpl": [np.nan] * 50}).astype(pd.SparseDtype("float", np.nan)), -] +@pytest.fixture( + params=[ + np.array([1, 20], dtype="uint64"), + pd.Series(["a", "b", "a"], dtype="category"), + [pd.Interval(left=0, right=2), pd.Interval(left=0, right=5)], + [pd.Period("2022-01-03", freq="D"), pd.Period("2022-01-04", freq="D")], + ] +) +def orc_writer_dtypes_not_supported(request): + # Examples of dataframes with dtypes for which conversion to ORC + # hasn't been implemented yet, that is, Category, unsigned integers, + # interval, period and sparse. + return pd.DataFrame({"unimpl": request.param}) def test_orc_reader_empty(dirpath): @@ -297,13 +291,12 @@ def test_orc_roundtrip_bytesio(): @td.skip_if_no("pyarrow", min_version="7.0.0") -@pytest.mark.parametrize("df_not_supported", orc_writer_dtypes_not_supported) -def test_orc_writer_dtypes_not_supported(df_not_supported): +def test_orc_writer_dtypes_not_supported(orc_writer_dtypes_not_supported): # GH44554 # PyArrow gained ORC write support with the current argument order msg = "The dtype of one or more columns is not supported yet." with pytest.raises(NotImplementedError, match=msg): - df_not_supported.to_orc() + orc_writer_dtypes_not_supported.to_orc() @td.skip_if_no("pyarrow", min_version="7.0.0") diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 1b0a1d740677b..68f9b2b64b92a 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -19,7 +19,6 @@ DataFrame, Series, ) -from pandas.tests.io.test_compression import _compression_to_extension from pandas.io.parsers import read_csv from pandas.io.stata import ( @@ -1964,13 +1963,13 @@ def test_statareader_warns_when_used_without_context(datapath): @pytest.mark.parametrize("version", [114, 117, 118, 119, None]) @pytest.mark.parametrize("use_dict", [True, False]) @pytest.mark.parametrize("infer", [True, False]) -def test_compression(compression, version, use_dict, infer): +def test_compression(compression, version, use_dict, infer, compression_to_extension): file_name = "dta_inferred_compression.dta" if compression: if use_dict: file_ext = compression else: - file_ext = _compression_to_extension[compression] + file_ext = compression_to_extension[compression] file_name += f".{file_ext}" compression_arg = compression if infer: @@ -2134,10 +2133,12 @@ def test_compression_roundtrip(compression): @pytest.mark.parametrize("to_infer", [True, False]) @pytest.mark.parametrize("read_infer", [True, False]) -def test_stata_compression(compression_only, read_infer, to_infer): +def test_stata_compression( + compression_only, read_infer, to_infer, compression_to_extension +): compression = compression_only - ext = _compression_to_extension[compression] + ext = compression_to_extension[compression] filename = f"test.{ext}" df = DataFrame( diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py index 1f1f44f408fc1..04194a68ed512 100644 --- a/pandas/tests/io/xml/test_to_xml.py +++ b/pandas/tests/io/xml/test_to_xml.py @@ -17,7 +17,6 @@ Index, ) import pandas._testing as tm -from pandas.tests.io.test_compression import _compression_to_extension from pandas.io.common import get_handle from pandas.io.xml import read_xml @@ -56,60 +55,69 @@ # [X] - XSLTParseError: "failed to compile" # [X] - PermissionError: "Forbidden" -geom_df = DataFrame( - { - "shape": ["square", "circle", "triangle"], - "degrees": [360, 360, 180], - "sides": [4, np.nan, 3], - } -) -planet_df = DataFrame( - { - "planet": [ - "Mercury", - "Venus", - "Earth", - "Mars", - "Jupiter", - "Saturn", - "Uranus", - "Neptune", - ], - "type": [ - "terrestrial", - "terrestrial", - "terrestrial", - "terrestrial", - "gas giant", - "gas giant", - "ice giant", - "ice giant", - ], - "location": [ - "inner", - "inner", - "inner", - "inner", - "outer", - "outer", - "outer", - "outer", - ], - "mass": [ - 0.330114, - 4.86747, - 5.97237, - 0.641712, - 1898.187, - 568.3174, - 86.8127, - 102.4126, - ], - } -) +@pytest.fixture +def geom_df(): + return DataFrame( + { + "shape": ["square", "circle", "triangle"], + "degrees": [360, 360, 180], + "sides": [4, np.nan, 3], + } + ) + + +@pytest.fixture +def planet_df(): + return DataFrame( + { + "planet": [ + "Mercury", + "Venus", + "Earth", + "Mars", + "Jupiter", + "Saturn", + "Uranus", + "Neptune", + ], + "type": [ + "terrestrial", + "terrestrial", + "terrestrial", + "terrestrial", + "gas giant", + "gas giant", + "ice giant", + "ice giant", + ], + "location": [ + "inner", + "inner", + "inner", + "inner", + "outer", + "outer", + "outer", + "outer", + ], + "mass": [ + 0.330114, + 4.86747, + 5.97237, + 0.641712, + 1898.187, + 568.3174, + 86.8127, + 102.4126, + ], + } + ) + -from_file_expected = """\ +@pytest.fixture +def from_file_expected(): + return """\ <?xml version='1.0' encoding='utf-8'?> <data> <row> @@ -163,7 +171,7 @@ def parser(request): # FILE OUTPUT -def test_file_output_str_read(datapath, parser): +def test_file_output_str_read(datapath, parser, from_file_expected): filename = datapath("io", "data", "xml", "books.xml") df_file = read_xml(filename, parser=parser) @@ -177,7 +185,7 @@ def test_file_output_str_read(datapath, parser): assert output == from_file_expected -def test_file_output_bytes_read(datapath, parser): +def test_file_output_bytes_read(datapath, parser, from_file_expected): filename = datapath("io", "data", "xml", "books.xml") df_file = read_xml(filename, parser=parser) @@ -191,7 +199,7 @@ def test_file_output_bytes_read(datapath, parser): assert output == from_file_expected -def test_str_output(datapath, parser): +def test_str_output(datapath, parser, from_file_expected): filename = datapath("io", "data", "xml", "books.xml") df_file = read_xml(filename, parser=parser) @@ -201,7 +209,7 @@ def test_str_output(datapath, parser): assert output == from_file_expected -def test_wrong_file_path(parser): +def test_wrong_file_path(parser, geom_df): path = "/my/fake/path/output.xml" with pytest.raises( @@ -299,7 +307,7 @@ def test_index_false_rename_row_root(datapath, parser): @pytest.mark.parametrize( "offset_index", [list(range(10, 13)), [str(i) for i in range(10, 13)]] ) -def test_index_false_with_offset_input_index(parser, offset_index): +def test_index_false_with_offset_input_index(parser, offset_index, geom_df): """ Tests that the output does not contain the `<index>` field when the index of the input Dataframe has an offset. @@ -361,21 +369,21 @@ def test_index_false_with_offset_input_index(parser, offset_index): </data>""" -def test_na_elem_output(parser): +def test_na_elem_output(parser, geom_df): output = geom_df.to_xml(parser=parser) output = equalize_decl(output) assert output == na_expected -def test_na_empty_str_elem_option(parser): +def test_na_empty_str_elem_option(parser, geom_df): output = geom_df.to_xml(na_rep="", parser=parser) output = equalize_decl(output) assert output == na_expected -def test_na_empty_elem_option(parser): +def test_na_empty_elem_option(parser, geom_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -408,7 +416,7 @@ def test_na_empty_elem_option(parser): # ATTR_COLS -def test_attrs_cols_nan_output(parser): +def test_attrs_cols_nan_output(parser, geom_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -423,7 +431,7 @@ def test_attrs_cols_nan_output(parser): assert output == expected -def test_attrs_cols_prefix(parser): +def test_attrs_cols_prefix(parser, geom_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <doc:data xmlns:doc="http://example.xom"> @@ -446,12 +454,12 @@ def test_attrs_cols_prefix(parser): assert output == expected -def test_attrs_unknown_column(parser): +def test_attrs_unknown_column(parser, geom_df): with pytest.raises(KeyError, match=("no valid column")): geom_df.to_xml(attr_cols=["shape", "degree", "sides"], parser=parser) -def test_attrs_wrong_type(parser): +def test_attrs_wrong_type(parser, geom_df): with pytest.raises(TypeError, match=("is not a valid type for attr_cols")): geom_df.to_xml(attr_cols='"shape", "degree", "sides"', parser=parser) @@ -459,7 +467,7 @@ def test_attrs_wrong_type(parser): # ELEM_COLS -def test_elems_cols_nan_output(parser): +def test_elems_cols_nan_output(parser, geom_df): elems_cols_expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -488,17 +496,17 @@ def test_elems_cols_nan_output(parser): assert output == elems_cols_expected -def test_elems_unknown_column(parser): +def test_elems_unknown_column(parser, geom_df): with pytest.raises(KeyError, match=("no valid column")): geom_df.to_xml(elem_cols=["shape", "degree", "sides"], parser=parser) -def test_elems_wrong_type(parser): +def test_elems_wrong_type(parser, geom_df): with pytest.raises(TypeError, match=("is not a valid type for elem_cols")): geom_df.to_xml(elem_cols='"shape", "degree", "sides"', parser=parser) -def test_elems_and_attrs_cols(parser): +def test_elems_and_attrs_cols(parser, geom_df): elems_cols_expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -530,7 +538,7 @@ def test_elems_and_attrs_cols(parser): # HIERARCHICAL COLUMNS -def test_hierarchical_columns(parser): +def test_hierarchical_columns(parser, planet_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -577,7 +585,7 @@ def test_hierarchical_columns(parser): assert output == expected -def test_hierarchical_attrs_columns(parser): +def test_hierarchical_attrs_columns(parser, planet_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -607,7 +615,7 @@ def test_hierarchical_attrs_columns(parser): # MULTIINDEX -def test_multi_index(parser): +def test_multi_index(parser, planet_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -646,7 +654,7 @@ def test_multi_index(parser): assert output == expected -def test_multi_index_attrs_cols(parser): +def test_multi_index_attrs_cols(parser, planet_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -672,7 +680,7 @@ def test_multi_index_attrs_cols(parser): # NAMESPACE -def test_default_namespace(parser): +def test_default_namespace(parser, geom_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data xmlns="http://example.com"> @@ -705,7 +713,7 @@ def test_default_namespace(parser): # PREFIX -def test_namespace_prefix(parser): +def test_namespace_prefix(parser, geom_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <doc:data xmlns:doc="http://example.com"> @@ -737,14 +745,14 @@ def test_namespace_prefix(parser): assert output == expected -def test_missing_prefix_in_nmsp(parser): +def test_missing_prefix_in_nmsp(parser, geom_df): with pytest.raises(KeyError, match=("doc is not included in namespaces")): geom_df.to_xml( namespaces={"": "http://example.com"}, prefix="doc", parser=parser ) -def test_namespace_prefix_and_default(parser): +def test_namespace_prefix_and_default(parser, geom_df): expected = """\ <?xml version='1.0' encoding='utf-8'?> <doc:data xmlns="http://example.com" xmlns:doc="http://other.org"> @@ -858,7 +866,7 @@ def test_wrong_encoding_option_lxml(datapath, parser, encoding): df_file.to_xml(path, index=False, encoding=encoding, parser=parser) -def test_misspelled_encoding(parser): +def test_misspelled_encoding(parser, geom_df): with pytest.raises(LookupError, match=("unknown encoding")): geom_df.to_xml(encoding="uft-8", parser=parser) @@ -867,7 +875,7 @@ def test_misspelled_encoding(parser): @td.skip_if_no("lxml") -def test_xml_declaration_pretty_print(): +def test_xml_declaration_pretty_print(geom_df): expected = """\ <data> <row> @@ -895,7 +903,7 @@ def test_xml_declaration_pretty_print(): assert output == expected -def test_no_pretty_print_with_decl(parser): +def test_no_pretty_print_with_decl(parser, geom_df): expected = ( "<?xml version='1.0' encoding='utf-8'?>\n" "<data><row><index>0</index><shape>square</shape>" @@ -916,7 +924,7 @@ def test_no_pretty_print_with_decl(parser): assert output == expected -def test_no_pretty_print_no_decl(parser): +def test_no_pretty_print_no_decl(parser, geom_df): expected = ( "<data><row><index>0</index><shape>square</shape>" "<degrees>360</degrees><sides>4.0</sides></row><row>" @@ -939,14 +947,14 @@ def test_no_pretty_print_no_decl(parser): @td.skip_if_installed("lxml") -def test_default_parser_no_lxml(): +def test_default_parser_no_lxml(geom_df): with pytest.raises( ImportError, match=("lxml not found, please install or use the etree parser.") ): geom_df.to_xml() -def test_unknown_parser(): +def test_unknown_parser(geom_df): with pytest.raises( ValueError, match=("Values for parser can only be lxml or etree.") ): @@ -980,7 +988,7 @@ def test_unknown_parser(): @td.skip_if_no("lxml") -def test_stylesheet_file_like(datapath, mode): +def test_stylesheet_file_like(datapath, mode, geom_df): xsl = datapath("io", "data", "xml", "row_field_output.xsl") with open(xsl, mode, encoding="utf-8" if mode == "r" else None) as f: @@ -988,7 +996,7 @@ def test_stylesheet_file_like(datapath, mode): @td.skip_if_no("lxml") -def test_stylesheet_io(datapath, mode): +def test_stylesheet_io(datapath, mode, geom_df): xsl_path = datapath("io", "data", "xml", "row_field_output.xsl") # note: By default the bodies of untyped functions are not checked, @@ -1007,7 +1015,7 @@ def test_stylesheet_io(datapath, mode): @td.skip_if_no("lxml") -def test_stylesheet_buffered_reader(datapath, mode): +def test_stylesheet_buffered_reader(datapath, mode, geom_df): xsl = datapath("io", "data", "xml", "row_field_output.xsl") with open(xsl, mode, encoding="utf-8" if mode == "r" else None) as f: @@ -1019,7 +1027,7 @@ def test_stylesheet_buffered_reader(datapath, mode): @td.skip_if_no("lxml") -def test_stylesheet_wrong_path(): +def test_stylesheet_wrong_path(geom_df): from lxml.etree import XMLSyntaxError xsl = os.path.join("data", "xml", "row_field_output.xslt") @@ -1033,7 +1041,7 @@ def test_stylesheet_wrong_path(): @td.skip_if_no("lxml") @pytest.mark.parametrize("val", ["", b""]) -def test_empty_string_stylesheet(val): +def test_empty_string_stylesheet(val, geom_df): from lxml.etree import XMLSyntaxError msg = "|".join( @@ -1050,7 +1058,7 @@ def test_empty_string_stylesheet(val): @td.skip_if_no("lxml") -def test_incorrect_xsl_syntax(): +def test_incorrect_xsl_syntax(geom_df): from lxml.etree import XMLSyntaxError xsl = """\ @@ -1079,7 +1087,7 @@ def test_incorrect_xsl_syntax(): @td.skip_if_no("lxml") -def test_incorrect_xsl_eval(): +def test_incorrect_xsl_eval(geom_df): from lxml.etree import XSLTParseError xsl = """\ @@ -1108,7 +1116,7 @@ def test_incorrect_xsl_eval(): @td.skip_if_no("lxml") -def test_incorrect_xsl_apply(): +def test_incorrect_xsl_apply(geom_df): from lxml.etree import XSLTApplyError xsl = """\ @@ -1128,7 +1136,7 @@ def test_incorrect_xsl_apply(): geom_df.to_xml(path, stylesheet=xsl) -def test_stylesheet_with_etree(): +def test_stylesheet_with_etree(geom_df): xsl = """\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="utf-8" indent="yes" /> @@ -1147,7 +1155,7 @@ def test_stylesheet_with_etree(): @td.skip_if_no("lxml") -def test_style_to_csv(): +def test_style_to_csv(geom_df): xsl = """\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="yes" /> @@ -1176,7 +1184,7 @@ def test_style_to_csv(): @td.skip_if_no("lxml") -def test_style_to_string(): +def test_style_to_string(geom_df): xsl = """\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="yes" /> @@ -1210,7 +1218,7 @@ def test_style_to_string(): @td.skip_if_no("lxml") -def test_style_to_json(): +def test_style_to_json(geom_df): xsl = """\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="yes" /> @@ -1281,7 +1289,7 @@ def test_style_to_json(): </data>""" -def test_compression_output(parser, compression_only): +def test_compression_output(parser, compression_only, geom_df): with tm.ensure_clean() as path: geom_df.to_xml(path, parser=parser, compression=compression_only) @@ -1297,8 +1305,10 @@ def test_compression_output(parser, compression_only): assert geom_xml == output.strip() -def test_filename_and_suffix_comp(parser, compression_only): - compfile = "xml." + _compression_to_extension[compression_only] +def test_filename_and_suffix_comp( + parser, compression_only, geom_df, compression_to_extension +): + compfile = "xml." + compression_to_extension[compression_only] with tm.ensure_clean(filename=compfile) as path: geom_df.to_xml(path, parser=parser, compression=compression_only) @@ -1328,7 +1338,7 @@ def test_ea_dtypes(any_numeric_ea_dtype, parser): assert equalize_decl(result).strip() == expected -def test_unsuported_compression(parser): +def test_unsuported_compression(parser, geom_df): with pytest.raises(ValueError, match="Unrecognized compression type"): with tm.ensure_clean() as path: geom_df.to_xml(path, parser=parser, compression="7z") @@ -1340,7 +1350,7 @@ def test_unsuported_compression(parser): @pytest.mark.single_cpu @td.skip_if_no("s3fs") @td.skip_if_no("lxml") -def test_s3_permission_output(parser, s3_resource): +def test_s3_permission_output(parser, s3_resource, geom_df): # s3_resource hosts pandas-test import s3fs
null
https://api.github.com/repos/pandas-dev/pandas/pulls/53567
2023-06-08T18:30:57Z
2023-06-09T17:13:04Z
2023-06-09T17:13:04Z
2023-06-09T17:13:07Z
Backport PR #53548: CI/DEPS: Add xfail(strict=False) to related unstable sorting changes in Numpy 1.25
diff --git a/pandas/tests/frame/methods/test_nlargest.py b/pandas/tests/frame/methods/test_nlargest.py index b5c33a41dd780..17dea51263222 100644 --- a/pandas/tests/frame/methods/test_nlargest.py +++ b/pandas/tests/frame/methods/test_nlargest.py @@ -9,6 +9,7 @@ import pandas as pd import pandas._testing as tm +from pandas.util.version import Version @pytest.fixture @@ -155,7 +156,7 @@ def test_nlargest_n_identical_values(self): [["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]], ) @pytest.mark.parametrize("n", range(1, 6)) - def test_nlargest_n_duplicate_index(self, df_duplicates, n, order): + def test_nlargest_n_duplicate_index(self, df_duplicates, n, order, request): # GH#13412 df = df_duplicates @@ -165,6 +166,18 @@ def test_nlargest_n_duplicate_index(self, df_duplicates, n, order): result = df.nlargest(n, order) expected = df.sort_values(order, ascending=False).head(n) + if Version(np.__version__) >= Version("1.25") and ( + (order == ["a"] and n in (1, 2, 3, 4)) or (order == ["a", "b"]) and n == 5 + ): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) tm.assert_frame_equal(result, expected) def test_nlargest_duplicate_keep_all_ties(self): diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index e2877acbdd040..4c41632040dbe 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -12,6 +12,7 @@ date_range, ) import pandas._testing as tm +from pandas.util.version import Version class TestDataFrameSortValues: @@ -849,9 +850,22 @@ def ascending(request): class TestSortValuesLevelAsStr: def test_sort_index_level_and_column_label( - self, df_none, df_idx, sort_names, ascending + self, df_none, df_idx, sort_names, ascending, request ): # GH#14353 + if ( + Version(np.__version__) >= Version("1.25") + and request.node.callspec.id == "df_idx0-inner-True" + ): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) # Get index levels from df_idx levels = df_idx.index.names @@ -867,7 +881,7 @@ def test_sort_index_level_and_column_label( tm.assert_frame_equal(result, expected) def test_sort_column_level_and_index_label( - self, df_none, df_idx, sort_names, ascending + self, df_none, df_idx, sort_names, ascending, request ): # GH#14353 @@ -886,6 +900,17 @@ def test_sort_column_level_and_index_label( # Compute result by transposing and sorting on axis=1. result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1) + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + tm.assert_frame_equal(result, expected) def test_sort_values_validate_ascending_for_value_error(self): diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index 2c3c2277ed627..ce29fba7a7ab0 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -21,6 +21,7 @@ to_datetime, ) import pandas._testing as tm +from pandas.util.version import Version def tests_value_counts_index_names_category_column(): @@ -244,8 +245,18 @@ def test_bad_subset(education_df): gp.value_counts(subset=["country"]) -def test_basic(education_df): +def test_basic(education_df, request): # gh43564 + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) result = education_df.groupby("country")[["gender", "education"]].value_counts( normalize=True ) @@ -283,7 +294,7 @@ def _frame_value_counts(df, keys, normalize, sort, ascending): @pytest.mark.parametrize("as_index", [True, False]) @pytest.mark.parametrize("frame", [True, False]) def test_against_frame_and_seriesgroupby( - education_df, groupby, normalize, name, sort, ascending, as_index, frame + education_df, groupby, normalize, name, sort, ascending, as_index, frame, request ): # test all parameters: # - Use column, array or function as by= parameter @@ -293,6 +304,16 @@ def test_against_frame_and_seriesgroupby( # - 3-way compare against: # - apply with :meth:`~DataFrame.value_counts` # - `~SeriesGroupBy.value_counts` + if Version(np.__version__) >= Version("1.25") and frame and sort and normalize: + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) by = { "column": "country", "array": education_df["country"].values, @@ -454,8 +475,18 @@ def nulls_df(): ], ) def test_dropna_combinations( - nulls_df, group_dropna, count_dropna, expected_rows, expected_values + nulls_df, group_dropna, count_dropna, expected_rows, expected_values, request ): + if Version(np.__version__) >= Version("1.25") and not group_dropna: + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) gp = nulls_df.groupby(["A", "B"], dropna=group_dropna) result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna) columns = DataFrame() @@ -546,10 +577,20 @@ def test_data_frame_value_counts_dropna( ], ) def test_categorical_single_grouper_with_only_observed_categories( - education_df, as_index, observed, normalize, name, expected_data + education_df, as_index, observed, normalize, name, expected_data, request ): # Test single categorical grouper with only observed grouping categories # when non-groupers are also categorical + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) gp = education_df.astype("category").groupby( "country", as_index=as_index, observed=observed @@ -645,10 +686,21 @@ def assert_categorical_single_grouper( ], ) def test_categorical_single_grouper_observed_true( - education_df, as_index, normalize, name, expected_data + education_df, as_index, normalize, name, expected_data, request ): # GH#46357 + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + expected_index = [ ("FR", "male", "low"), ("FR", "female", "high"), @@ -715,10 +767,21 @@ def test_categorical_single_grouper_observed_true( ], ) def test_categorical_single_grouper_observed_false( - education_df, as_index, normalize, name, expected_data + education_df, as_index, normalize, name, expected_data, request ): # GH#46357 + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + expected_index = [ ("FR", "male", "low"), ("FR", "female", "high"), @@ -856,10 +919,22 @@ def test_categorical_multiple_groupers( ], ) def test_categorical_non_groupers( - education_df, as_index, observed, normalize, name, expected_data + education_df, as_index, observed, normalize, name, expected_data, request ): # GH#46357 Test non-observed categories are included in the result, # regardless of `observed` + + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + education_df = education_df.copy() education_df["gender"] = education_df["gender"].astype("category") education_df["education"] = education_df["education"].astype("category")
null
https://api.github.com/repos/pandas-dev/pandas/pulls/53566
2023-06-08T18:24:40Z
2023-06-08T21:47:30Z
2023-06-08T21:47:30Z
2023-06-08T21:47:35Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index f2d6a2b222a3c..191e0d03b3a1a 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -267,10 +267,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.groupby.DataFrameGroupBy.ffill \ pandas.core.groupby.DataFrameGroupBy.median \ pandas.core.groupby.DataFrameGroupBy.ohlc \ - pandas.core.groupby.DataFrameGroupBy.pct_change \ - pandas.core.groupby.DataFrameGroupBy.sem \ - pandas.core.groupby.DataFrameGroupBy.shift \ - pandas.core.groupby.DataFrameGroupBy.size \ pandas.core.groupby.DataFrameGroupBy.skew \ pandas.core.groupby.DataFrameGroupBy.std \ pandas.core.groupby.DataFrameGroupBy.var \ @@ -280,10 +276,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.groupby.SeriesGroupBy.median \ pandas.core.groupby.SeriesGroupBy.nunique \ pandas.core.groupby.SeriesGroupBy.ohlc \ - pandas.core.groupby.SeriesGroupBy.pct_change \ - pandas.core.groupby.SeriesGroupBy.sem \ - pandas.core.groupby.SeriesGroupBy.shift \ - pandas.core.groupby.SeriesGroupBy.size \ pandas.core.groupby.SeriesGroupBy.skew \ pandas.core.groupby.SeriesGroupBy.std \ pandas.core.groupby.SeriesGroupBy.var \ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c96310c51b2a2..c372235481614 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2509,6 +2509,40 @@ def sem(self, ddof: int = 1, numeric_only: bool = False): ------- Series or DataFrame Standard error of the mean of values within each group. + + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([5, 10, 8, 14], index=lst) + >>> ser + a 5 + a 10 + b 8 + b 14 + dtype: int64 + >>> ser.groupby(level=0).sem() + a 2.5 + b 3.0 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = [[1, 12, 11], [1, 15, 2], [2, 5, 8], [2, 6, 12]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tuna", "salmon", "catfish", "goldfish"]) + >>> df + a b c + tuna 1 12 11 + salmon 1 15 2 + catfish 2 5 8 + goldfish 2 6 12 + >>> df.groupby("a").sem() + b c + a + 1 1.5 4.5 + 2 0.5 2.0 """ if numeric_only and self.obj.ndim == 1 and not is_numeric_dtype(self.obj.dtype): raise TypeError( @@ -2524,7 +2558,7 @@ def sem(self, ddof: int = 1, numeric_only: bool = False): @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def size(self) -> DataFrame | Series: """ Compute group sizes. @@ -2534,6 +2568,37 @@ def size(self) -> DataFrame | Series: DataFrame or Series Number of rows in each group as a Series if as_index is True or a DataFrame if as_index is False. + %(see_also)s + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + dtype: int64 + >>> ser.groupby(level=0).size() + a 2 + b 1 + dtype: int64 + + >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["owl", "toucan", "eagle"]) + >>> df + a b c + owl 1 2 3 + toucan 1 5 6 + eagle 7 8 9 + >>> df.groupby("a").size() + a + 1 2 + 7 1 + dtype: int64 """ result = self.grouper.size() @@ -4439,6 +4504,44 @@ def shift( See Also -------- Index.shift : Shift values of Index. + + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 4], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 4 + dtype: int64 + >>> ser.groupby(level=0).shift(1) + a NaN + a 1.0 + b NaN + b 3.0 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = [[1, 2, 3], [1, 5, 6], [2, 5, 8], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tuna", "salmon", "catfish", "goldfish"]) + >>> df + a b c + tuna 1 2 3 + salmon 1 5 6 + catfish 2 5 8 + goldfish 2 6 9 + >>> df.groupby("a").shift(1) + b c + tuna NaN NaN + salmon 2.0 3.0 + catfish NaN NaN + goldfish 5.0 8.0 """ if axis is not lib.no_default: axis = self.obj._get_axis_number(axis) @@ -4519,7 +4622,7 @@ def diff( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def pct_change( self, periods: int = 1, @@ -4535,7 +4638,46 @@ def pct_change( ------- Series or DataFrame Percentage changes within each group. + %(see_also)s + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 4], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 4 + dtype: int64 + >>> ser.groupby(level=0).pct_change() + a NaN + a 1.000000 + b NaN + b 0.333333 + dtype: float64 + + For DataFrameGroupBy: + + >>> data = [[1, 2, 3], [1, 5, 6], [2, 5, 8], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tuna", "salmon", "catfish", "goldfish"]) + >>> df + a b c + tuna 1 2 3 + salmon 1 5 6 + catfish 2 5 8 + goldfish 2 6 9 + >>> df.groupby("a").pct_change() + b c + tuna NaN NaN + salmon 1.5 1.000 + catfish NaN NaN + goldfish 0.2 0.125 """ + if axis is not lib.no_default: axis = self.obj._get_axis_number(axis) self._deprecate_axis(axis, "pct_change")
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53564
2023-06-08T17:18:30Z
2023-06-08T21:48:30Z
2023-06-08T21:48:30Z
2023-06-09T08:40:18Z
TST: Use monkeypatch instead of custom func for env variables
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 7908c9df60df8..de3dd58d3b716 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -97,7 +97,6 @@ from pandas._testing.contexts import ( decompress_file, ensure_clean, - ensure_safe_environment_variables, raises_chained_assignment_error, set_timezone, use_numexpr, @@ -1104,7 +1103,6 @@ def shares_memory(left, right) -> bool: "EMPTY_STRING_PATTERN", "ENDIAN", "ensure_clean", - "ensure_safe_environment_variables", "equalContents", "external_error_raised", "FLOAT_EA_DTYPES", diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index ba2c8c219dc41..f939bd42add93 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -138,22 +138,6 @@ def ensure_clean( path.unlink() -@contextmanager -def ensure_safe_environment_variables() -> Generator[None, None, None]: - """ - Get a context manager to safely set environment variables - - All changes will be undone on close, hence environment variables set - within this contextmanager will neither persist nor change global state. - """ - saved_environ = dict(os.environ) - try: - yield - finally: - os.environ.clear() - os.environ.update(saved_environ) - - @contextmanager def with_csv_dialect(name: str, **kwargs) -> Generator[None, None, None]: """ diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index 68365c125a951..1fc867f95de53 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -1,4 +1,3 @@ -import os import shlex import subprocess import time @@ -13,8 +12,6 @@ ) import pandas.util._test_decorators as td -import pandas._testing as tm - import pandas.io.common as icom from pandas.io.parsers import read_csv @@ -58,7 +55,13 @@ def s3so(worker_id): @pytest.fixture(scope="session") -def s3_base(worker_id): +def monkeysession(): + with pytest.MonkeyPatch.context() as mp: + yield mp + + +@pytest.fixture(scope="session") +def s3_base(worker_id, monkeysession): """ Fixture for mocking S3 interaction. @@ -68,56 +71,55 @@ def s3_base(worker_id): pytest.importorskip("s3fs") pytest.importorskip("boto3") - with tm.ensure_safe_environment_variables(): - # temporary workaround as moto fails for botocore >= 1.11 otherwise, - # see https://github.com/spulec/moto/issues/1924 & 1952 - os.environ.setdefault("AWS_ACCESS_KEY_ID", "foobar_key") - os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "foobar_secret") - if is_ci_environment(): - if is_platform_arm() or is_platform_mac() or is_platform_windows(): - # NOT RUN on Windows/macOS/ARM, only Ubuntu - # - subprocess in CI can cause timeouts - # - GitHub Actions do not support - # container services for the above OSs - # - CircleCI will probably hit the Docker rate pull limit - pytest.skip( - "S3 tests do not have a corresponding service in " - "Windows, macOS or ARM platforms" - ) - else: - yield "http://localhost:5000" + # temporary workaround as moto fails for botocore >= 1.11 otherwise, + # see https://github.com/spulec/moto/issues/1924 & 1952 + monkeysession.setenv("AWS_ACCESS_KEY_ID", "foobar_key") + monkeysession.setenv("AWS_SECRET_ACCESS_KEY", "foobar_secret") + if is_ci_environment(): + if is_platform_arm() or is_platform_mac() or is_platform_windows(): + # NOT RUN on Windows/macOS/ARM, only Ubuntu + # - subprocess in CI can cause timeouts + # - GitHub Actions do not support + # container services for the above OSs + # - CircleCI will probably hit the Docker rate pull limit + pytest.skip( + "S3 tests do not have a corresponding service in " + "Windows, macOS or ARM platforms" + ) else: - requests = pytest.importorskip("requests") - pytest.importorskip("moto", minversion="1.3.14") - pytest.importorskip("flask") # server mode needs flask too - - # Launching moto in server mode, i.e., as a separate process - # with an S3 endpoint on localhost - - worker_id = "5" if worker_id == "master" else worker_id.lstrip("gw") - endpoint_port = f"555{worker_id}" - endpoint_uri = f"http://127.0.0.1:{endpoint_port}/" - - # pipe to null to avoid logging in terminal - with subprocess.Popen( - shlex.split(f"moto_server s3 -p {endpoint_port}"), - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) as proc: - timeout = 5 - while timeout > 0: - try: - # OK to go once server is accepting connections - r = requests.get(endpoint_uri) - if r.ok: - break - except Exception: - pass - timeout -= 0.1 - time.sleep(0.1) - yield endpoint_uri - - proc.terminate() + yield "http://localhost:5000" + else: + requests = pytest.importorskip("requests") + pytest.importorskip("moto", minversion="1.3.14") + pytest.importorskip("flask") # server mode needs flask too + + # Launching moto in server mode, i.e., as a separate process + # with an S3 endpoint on localhost + + worker_id = "5" if worker_id == "master" else worker_id.lstrip("gw") + endpoint_port = f"555{worker_id}" + endpoint_uri = f"http://127.0.0.1:{endpoint_port}/" + + # pipe to null to avoid logging in terminal + with subprocess.Popen( + shlex.split(f"moto_server s3 -p {endpoint_port}"), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) as proc: + timeout = 5 + while timeout > 0: + try: + # OK to go once server is accepting connections + r = requests.get(endpoint_uri) + if r.ok: + break + except Exception: + pass + timeout -= 0.1 + time.sleep(0.1) + yield endpoint_uri + + proc.terminate() @pytest.fixture diff --git a/pandas/tests/io/test_s3.py b/pandas/tests/io/test_s3.py index 6702d58c139af..5171ec04b0bcf 100644 --- a/pandas/tests/io/test_s3.py +++ b/pandas/tests/io/test_s3.py @@ -1,5 +1,4 @@ from io import BytesIO -import os import pytest @@ -34,17 +33,16 @@ def test_read_without_creds_from_pub_bucket(): @td.skip_if_no("s3fs") @pytest.mark.network @tm.network -def test_read_with_creds_from_pub_bucket(): +def test_read_with_creds_from_pub_bucket(monkeypatch): # Ensure we can read from a public bucket with credentials # GH 34626 # Use Amazon Open Data Registry - https://registry.opendata.aws/gdelt - with tm.ensure_safe_environment_variables(): - # temporary workaround as moto fails for botocore >= 1.11 otherwise, - # see https://github.com/spulec/moto/issues/1924 & 1952 - os.environ.setdefault("AWS_ACCESS_KEY_ID", "foobar_key") - os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "foobar_secret") - df = read_csv( - "s3://gdelt-open-data/events/1981.csv", nrows=5, sep="\t", header=None - ) - assert len(df) == 5 + # temporary workaround as moto fails for botocore >= 1.11 otherwise, + # see https://github.com/spulec/moto/issues/1924 & 1952 + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "foobar_key") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "foobar_secret") + df = read_csv( + "s3://gdelt-open-data/events/1981.csv", nrows=5, sep="\t", header=None + ) + assert len(df) == 5
null
https://api.github.com/repos/pandas-dev/pandas/pulls/53563
2023-06-08T16:37:26Z
2023-06-09T20:17:57Z
2023-06-09T20:17:57Z
2023-06-09T20:18:00Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 9e50b93e173c4..f2d6a2b222a3c 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -265,35 +265,27 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.api.indexers.VariableOffsetWindowIndexer \ pandas.core.groupby.DataFrameGroupBy.diff \ pandas.core.groupby.DataFrameGroupBy.ffill \ - pandas.core.groupby.DataFrameGroupBy.max \ pandas.core.groupby.DataFrameGroupBy.median \ - pandas.core.groupby.DataFrameGroupBy.min \ pandas.core.groupby.DataFrameGroupBy.ohlc \ pandas.core.groupby.DataFrameGroupBy.pct_change \ - pandas.core.groupby.DataFrameGroupBy.prod \ pandas.core.groupby.DataFrameGroupBy.sem \ pandas.core.groupby.DataFrameGroupBy.shift \ pandas.core.groupby.DataFrameGroupBy.size \ pandas.core.groupby.DataFrameGroupBy.skew \ pandas.core.groupby.DataFrameGroupBy.std \ - pandas.core.groupby.DataFrameGroupBy.sum \ pandas.core.groupby.DataFrameGroupBy.var \ pandas.core.groupby.SeriesGroupBy.diff \ pandas.core.groupby.SeriesGroupBy.fillna \ pandas.core.groupby.SeriesGroupBy.ffill \ - pandas.core.groupby.SeriesGroupBy.max \ pandas.core.groupby.SeriesGroupBy.median \ - pandas.core.groupby.SeriesGroupBy.min \ pandas.core.groupby.SeriesGroupBy.nunique \ pandas.core.groupby.SeriesGroupBy.ohlc \ pandas.core.groupby.SeriesGroupBy.pct_change \ - pandas.core.groupby.SeriesGroupBy.prod \ pandas.core.groupby.SeriesGroupBy.sem \ pandas.core.groupby.SeriesGroupBy.shift \ pandas.core.groupby.SeriesGroupBy.size \ pandas.core.groupby.SeriesGroupBy.skew \ pandas.core.groupby.SeriesGroupBy.std \ - pandas.core.groupby.SeriesGroupBy.sum \ pandas.core.groupby.SeriesGroupBy.var \ pandas.core.groupby.SeriesGroupBy.hist \ pandas.core.groupby.DataFrameGroupBy.plot \ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 341e177a4a9ad..c96310c51b2a2 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -341,6 +341,10 @@ class providing the base-class of operations. ------- Series or DataFrame Computed {fname} of values within each group. + +Examples +-------- +{example} """ _pipe_template = """ @@ -2550,7 +2554,46 @@ def size(self) -> DataFrame | Series: return result @final - @doc(_groupby_agg_method_template, fname="sum", no=False, mc=0) + @doc( + _groupby_agg_method_template, + fname="sum", + no=False, + mc=0, + example=dedent( + """\ + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 4], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 4 + dtype: int64 + >>> ser.groupby(level=0).sum() + a 3 + b 7 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tiger", "leopard", "cheetah", "lion"]) + >>> df + a b c + tiger 1 8 2 + leopard 1 2 5 + cheetah 2 5 8 + lion 2 6 9 + >>> df.groupby("a").sum() + b c + a + 1 10 7 + 2 11 17""" + ), + ) def sum( self, numeric_only: bool = False, @@ -2580,14 +2623,92 @@ def sum( return self._reindex_output(result, fill_value=0) @final - @doc(_groupby_agg_method_template, fname="prod", no=False, mc=0) + @doc( + _groupby_agg_method_template, + fname="prod", + no=False, + mc=0, + example=dedent( + """\ + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 4], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 4 + dtype: int64 + >>> ser.groupby(level=0).prod() + a 2 + b 12 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tiger", "leopard", "cheetah", "lion"]) + >>> df + a b c + tiger 1 8 2 + leopard 1 2 5 + cheetah 2 5 8 + lion 2 6 9 + >>> df.groupby("a").prod() + b c + a + 1 16 10 + 2 30 72""" + ), + ) def prod(self, numeric_only: bool = False, min_count: int = 0): return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="prod", npfunc=np.prod ) @final - @doc(_groupby_agg_method_template, fname="min", no=False, mc=-1) + @doc( + _groupby_agg_method_template, + fname="min", + no=False, + mc=-1, + example=dedent( + """\ + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 4], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 4 + dtype: int64 + >>> ser.groupby(level=0).min() + a 1 + b 3 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tiger", "leopard", "cheetah", "lion"]) + >>> df + a b c + tiger 1 8 2 + leopard 1 2 5 + cheetah 2 5 8 + lion 2 6 9 + >>> df.groupby("a").min() + b c + a + 1 2 2 + 2 5 8""" + ), + ) def min( self, numeric_only: bool = False, @@ -2608,7 +2729,46 @@ def min( ) @final - @doc(_groupby_agg_method_template, fname="max", no=False, mc=-1) + @doc( + _groupby_agg_method_template, + fname="max", + no=False, + mc=-1, + example=dedent( + """\ + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b', 'b'] + >>> ser = pd.Series([1, 2, 3, 4], index=lst) + >>> ser + a 1 + a 2 + b 3 + b 4 + dtype: int64 + >>> ser.groupby(level=0).max() + a 2 + b 4 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 2, 5], [2, 5, 8], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["tiger", "leopard", "cheetah", "lion"]) + >>> df + a b c + tiger 1 8 2 + leopard 1 2 5 + cheetah 2 5 8 + lion 2 6 9 + >>> df.groupby("a").max() + b c + a + 1 8 5 + 2 6 9""" + ), + ) def max( self, numeric_only: bool = False,
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53561
2023-06-08T12:45:44Z
2023-06-08T16:18:42Z
2023-06-08T16:18:42Z
2023-06-08T17:09:18Z
Update 02_read_write.rst
diff --git a/doc/source/getting_started/intro_tutorials/02_read_write.rst b/doc/source/getting_started/intro_tutorials/02_read_write.rst index dbb1be8c4d875..832c2cc25712f 100644 --- a/doc/source/getting_started/intro_tutorials/02_read_write.rst +++ b/doc/source/getting_started/intro_tutorials/02_read_write.rst @@ -99,9 +99,9 @@ strings (``object``). .. note:: When asking for the ``dtypes``, no brackets are used! ``dtypes`` is an attribute of a ``DataFrame`` and ``Series``. Attributes - of ``DataFrame`` or ``Series`` do not need brackets. Attributes - represent a characteristic of a ``DataFrame``/``Series``, whereas a - method (which requires brackets) *do* something with the + of a ``DataFrame`` or ``Series`` do not need brackets. Attributes + represent a characteristic of a ``DataFrame``/``Series``, whereas + methods (which require brackets) *do* something with the ``DataFrame``/``Series`` as introduced in the :ref:`first tutorial <10min_tut_01_tableoriented>`. .. raw:: html
Grammatical error corrected.
https://api.github.com/repos/pandas-dev/pandas/pulls/53559
2023-06-08T07:51:11Z
2023-06-08T15:13:01Z
2023-06-08T15:13:01Z
2023-06-08T15:14:17Z
DEPR: deprecate unit parameters ’T’, 't', 'L', and 'l'
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index d9cdc8beaebea..5fd6953d0443a 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -295,10 +295,10 @@ Deprecations - Deprecated option "mode.use_inf_as_na", convert inf entries to ``NaN`` before instead (:issue:`51684`) - Deprecated parameter ``obj`` in :meth:`GroupBy.get_group` (:issue:`53545`) - Deprecated positional indexing on :class:`Series` with :meth:`Series.__getitem__` and :meth:`Series.__setitem__`, in a future version ``ser[item]`` will *always* interpret ``item`` as a label, not a position (:issue:`50617`) +- Deprecated strings ``T``, ``t``, ``L`` and ``l`` denoting units in :func:`to_timedelta` (:issue:`52536`) - Deprecated the "method" and "limit" keywords on :meth:`Series.fillna`, :meth:`DataFrame.fillna`, :meth:`SeriesGroupBy.fillna`, :meth:`DataFrameGroupBy.fillna`, and :meth:`Resampler.fillna`, use ``obj.bfill()`` or ``obj.ffill()`` instead (:issue:`53394`) - Deprecated the ``method`` and ``limit`` keywords in :meth:`DataFrame.replace` and :meth:`Series.replace` (:issue:`33302`) - Deprecated values "pad", "ffill", "bfill", "backfill" for :meth:`Series.interpolate` and :meth:`DataFrame.interpolate`, use ``obj.ffill()`` or ``obj.bfill()`` instead (:issue:`53581`) -- .. --------------------------------------------------------------------------- .. _whatsnew_210.performance: diff --git a/pandas/_libs/tslibs/timedeltas.pyi b/pandas/_libs/tslibs/timedeltas.pyi index 0d5afbfe963f1..448aed0eebe4c 100644 --- a/pandas/_libs/tslibs/timedeltas.pyi +++ b/pandas/_libs/tslibs/timedeltas.pyi @@ -37,6 +37,7 @@ UnitChoices = Literal[ "minute", "min", "minutes", + "T", "t", "s", "seconds", @@ -47,6 +48,7 @@ UnitChoices = Literal[ "millisecond", "milli", "millis", + "L", "l", "us", "microseconds", diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index ad366e58c2f06..95946f0a159fd 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -7,6 +7,7 @@ TYPE_CHECKING, overload, ) +import warnings import numpy as np @@ -19,6 +20,7 @@ Timedelta, parse_timedelta_unit, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_list_like from pandas.core.dtypes.generic import ( @@ -118,6 +120,9 @@ def to_timedelta( Must not be specified when `arg` context strings and ``errors="raise"``. + .. deprecated:: 2.1.0 + Units 'T' and 'L' are deprecated and will be removed in a future version. + errors : {'ignore', 'raise', 'coerce'}, default 'raise' - If 'raise', then invalid parsing will raise an exception. - If 'coerce', then invalid parsing will be set as NaT. @@ -169,6 +174,13 @@ def to_timedelta( TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq=None) """ + if unit in {"T", "t", "L", "l"}: + warnings.warn( + f"Unit '{unit}' is deprecated and will be removed in a future version.", + FutureWarning, + stacklevel=find_stack_level(), + ) + if unit is not None: unit = parse_timedelta_unit(unit) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/pandas/tests/indexes/timedeltas/test_timedelta_range.py index 05fdddd7a4f4f..72bdc6da47d94 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta_range.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta_range.py @@ -38,10 +38,27 @@ def test_timedelta_range(self): result = timedelta_range("1 days, 00:00:02", periods=5, freq="2D") tm.assert_index_equal(result, expected) - expected = to_timedelta(np.arange(50), unit="T") * 30 - result = timedelta_range("0 days", freq="30T", periods=50) + expected = to_timedelta(np.arange(50), unit="min") * 30 + result = timedelta_range("0 days", freq="30min", periods=50) tm.assert_index_equal(result, expected) + @pytest.mark.parametrize( + "depr_unit, unit", + [ + ("T", "minute"), + ("t", "minute"), + ("L", "millisecond"), + ("l", "millisecond"), + ], + ) + def test_timedelta_units_T_L_deprecated(self, depr_unit, unit): + depr_msg = f"Unit '{depr_unit}' is deprecated." + + expected = to_timedelta(np.arange(5), unit=unit) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = to_timedelta(np.arange(5), unit=depr_unit) + tm.assert_index_equal(result, expected) + @pytest.mark.parametrize( "periods, freq", [(3, "2D"), (5, "D"), (6, "19H12T"), (7, "16H"), (9, "12H")] ) diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py index 79e024ef84c90..d87e6ca2f69b9 100644 --- a/pandas/tests/resample/test_timedelta.py +++ b/pandas/tests/resample/test_timedelta.py @@ -48,17 +48,17 @@ def test_resample_as_freq_with_subperiod(): def test_resample_with_timedeltas(): expected = DataFrame({"A": np.arange(1480)}) expected = expected.groupby(expected.index // 30).sum() - expected.index = timedelta_range("0 days", freq="30T", periods=50) + expected.index = timedelta_range("0 days", freq="30min", periods=50) df = DataFrame( - {"A": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit="T") + {"A": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit="min") ) - result = df.resample("30T").sum() + result = df.resample("30min").sum() tm.assert_frame_equal(result, expected) s = df["A"] - result = s.resample("30T").sum() + result = s.resample("30min").sum() tm.assert_series_equal(result, expected["A"]) diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 4cb77b2f1d065..722a68a1dce71 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -492,11 +492,9 @@ def test_nat_converters(self): "minute", "min", "minutes", - "t", "Minute", "Min", "Minutes", - "T", ] ] + [ @@ -520,13 +518,11 @@ def test_nat_converters(self): "millisecond", "milli", "millis", - "l", "MS", "Milliseconds", "Millisecond", "Milli", "Millis", - "L", ] ] + [
- [x] closes #52536 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Added upper case ’T’ for minutes in `UnitChoices` list. Now mypy doesn’t raise an error. Update: Deprecated unit parameters ’T’, 't', 'L', 'l', and fixed test.
https://api.github.com/repos/pandas-dev/pandas/pulls/53557
2023-06-07T22:44:08Z
2023-06-20T11:07:31Z
2023-06-20T11:07:31Z
2023-06-20T11:07:32Z
ENH: Numba groupby support multiple labels
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 6bb972c21d927..a58406eb30976 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -99,6 +99,7 @@ Other enhancements - :meth:`Categorical.from_codes` has gotten a ``validate`` parameter (:issue:`50975`) - :meth:`DataFrame.stack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`) - :meth:`DataFrame.unstack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`) +- :meth:`DataFrameGroupby.agg` and :meth:`DataFrameGroupby.transform` now support grouping by multiple keys when the index is not a :class:`MultiIndex` for ``engine="numba"`` (:issue:`53486`) - :meth:`SeriesGroupby.agg` and :meth:`DataFrameGroupby.agg` now support passing in multiple functions for ``engine="numba"`` (:issue:`53486`) - Added ``engine_kwargs`` parameter to :meth:`DataFrame.to_excel` (:issue:`53220`) - Added a new parameter ``by_row`` to :meth:`Series.apply`. When set to ``False`` the supplied callables will always operate on the whole Series (:issue:`53400`). diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 6ea5fc437f5a2..594c025a9a77f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1325,13 +1325,14 @@ def _numba_prep(self, data: DataFrame): sorted_ids = self.grouper._sorted_ids sorted_data = data.take(sorted_index, axis=self.axis).to_numpy() - if len(self.grouper.groupings) > 1: - raise NotImplementedError( - "More than 1 grouping labels are not supported with engine='numba'" - ) # GH 46867 index_data = data.index if isinstance(index_data, MultiIndex): + if len(self.grouper.groupings) > 1: + raise NotImplementedError( + "Grouping with more than 1 grouping labels and " + "a MultiIndex is not supported with engine='numba'" + ) group_key = self.grouper.groupings[0].name index_data = index_data.get_level_values(group_key) sorted_index_data = index_data.take(sorted_index).to_numpy() diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index a82c4d0d8ffbc..d585cc1648c5a 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -339,7 +339,44 @@ def numba_func(values, index): df = DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) engine_kwargs = {"nopython": nopython, "nogil": nogil, "parallel": parallel} - with pytest.raises(NotImplementedError, match="More than 1 grouping labels"): + with pytest.raises(NotImplementedError, match="more than 1 grouping labels"): df.groupby(["A", "B"]).agg( numba_func, engine="numba", engine_kwargs=engine_kwargs ) + + +@td.skip_if_no("numba") +def test_multilabel_numba_vs_cython(numba_supported_reductions): + reduction, kwargs = numba_supported_reductions + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.randn(8), + "D": np.random.randn(8), + } + ) + gb = df.groupby(["A", "B"]) + res_agg = gb.agg(reduction, engine="numba", **kwargs) + expected_agg = gb.agg(reduction, engine="cython", **kwargs) + tm.assert_frame_equal(res_agg, expected_agg) + # Test that calling the aggregation directly also works + direct_res = getattr(gb, reduction)(engine="numba", **kwargs) + direct_expected = getattr(gb, reduction)(engine="cython", **kwargs) + tm.assert_frame_equal(direct_res, direct_expected) + + +@td.skip_if_no("numba") +def test_multilabel_udf_numba_vs_cython(): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.randn(8), + "D": np.random.randn(8), + } + ) + gb = df.groupby(["A", "B"]) + result = gb.agg(lambda values, index: values.min(), engine="numba") + expected = gb.agg(lambda x: x.min(), engine="cython") + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index 0264d2a09778f..00ff391199652 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -1,3 +1,4 @@ +import numpy as np import pytest from pandas.errors import NumbaUtilError @@ -224,7 +225,48 @@ def numba_func(values, index): df = DataFrame([{"A": 1, "B": 2, "C": 3}]).set_index(["A", "B"]) engine_kwargs = {"nopython": nopython, "nogil": nogil, "parallel": parallel} - with pytest.raises(NotImplementedError, match="More than 1 grouping labels"): + with pytest.raises(NotImplementedError, match="more than 1 grouping labels"): df.groupby(["A", "B"]).transform( numba_func, engine="numba", engine_kwargs=engine_kwargs ) + + +@td.skip_if_no("numba") +@pytest.mark.xfail( + reason="Groupby transform doesn't support strings as function inputs yet with numba" +) +def test_multilabel_numba_vs_cython(numba_supported_reductions): + reduction, kwargs = numba_supported_reductions + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.randn(8), + "D": np.random.randn(8), + } + ) + gb = df.groupby(["A", "B"]) + res_agg = gb.transform(reduction, engine="numba", **kwargs) + expected_agg = gb.transform(reduction, engine="cython", **kwargs) + tm.assert_frame_equal(res_agg, expected_agg) + + +@td.skip_if_no("numba") +def test_multilabel_udf_numba_vs_cython(): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.randn(8), + "D": np.random.randn(8), + } + ) + gb = df.groupby(["A", "B"]) + result = gb.transform( + lambda values, index: (values - values.min()) / (values.max() - values.min()), + engine="numba", + ) + expected = gb.transform( + lambda x: (x - x.min()) / (x.max() - x.min()), engine="cython" + ) + tm.assert_frame_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. @mroeschke Looks like you disabled this in #47057, but it seems to work fine at least for the non-MI index case. Did you only mean to disable multiple labels for the MI case? Just wanted to make sure I'm not missing anything.
https://api.github.com/repos/pandas-dev/pandas/pulls/53556
2023-06-07T16:30:30Z
2023-06-07T21:34:39Z
2023-06-07T21:34:39Z
2023-06-07T22:23:37Z
Backport PR #53435 on branch 2.0.x (DOC: Update release process)
diff --git a/doc/source/development/maintaining.rst b/doc/source/development/maintaining.rst index 994dfde0894f3..f7665dbed6499 100644 --- a/doc/source/development/maintaining.rst +++ b/doc/source/development/maintaining.rst @@ -368,11 +368,14 @@ Prerequisites In order to be able to release a new pandas version, the next permissions are needed: -- Merge rights to the `pandas <https://github.com/pandas-dev/pandas/>`_, - `pandas-wheels <https://github.com/MacPython/pandas-wheels>`_, and +- Merge rights to the `pandas <https://github.com/pandas-dev/pandas/>`_ and `pandas-feedstock <https://github.com/conda-forge/pandas-feedstock/>`_ repositories. -- Permissions to push to main in the pandas repository, to push the new tags. -- `Write permissions to PyPI <https://github.com/conda-forge/pandas-feedstock/pulls>`_ + For the latter, open a PR adding your GitHub username to the conda-forge recipe. +- Permissions to push to ``main`` in the pandas repository, to push the new tags. +- `Write permissions to PyPI <https://github.com/conda-forge/pandas-feedstock/pulls>`_. +- Access to our website / documentation server. Share your public key with the + infrastructure committee to be added to the ``authorized_keys`` file of the main + server user. - Access to the social media accounts, to publish the announcements. Pre-release @@ -438,10 +441,10 @@ which will be triggered when the tag is pushed. 4. Create a `new GitHub release <https://github.com/pandas-dev/pandas/releases/new>`_: - - Title: ``Pandas <version>`` - Tag: ``<version>`` - - Files: ``pandas-<version>.tar.gz`` source distribution just generated + - Title: ``Pandas <version>`` - Description: Copy the description of the last release of the same kind (release candidate, major/minor or patch release) + - Files: ``pandas-<version>.tar.gz`` source distribution just generated - Set as a pre-release: Only check for a release candidate - Set as the latest release: Leave checked, unless releasing a patch release for an older version (e.g. releasing 1.4.5 after 1.5 has been released) @@ -449,6 +452,9 @@ which will be triggered when the tag is pushed. 5. The GitHub release will after some hours trigger an `automated conda-forge PR <https://github.com/conda-forge/pandas-feedstock/pulls>`_. Merge it once the CI is green, and it will generate the conda-forge packages. + In case a manual PR needs to be done, the version, sha256 and build fields are the + ones that usually need to be changed. If anything else in the recipe has changed since + the last release, those changes should be available in ``ci/meta.yaml``. 6. Packages for supported versions in PyPI are built in the `MacPython repo <https://github.com/MacPython/pandas-wheels>`_. @@ -475,8 +481,16 @@ which will be triggered when the tag is pushed. Post-Release ```````````` -1. Update symlink to stable documentation by logging in to our web server, and - editing ``/var/www/html/pandas-docs/stable`` to point to ``version/<latest-version>``. +1. Update symlinks to stable documentation by logging in to our web server, and + editing ``/var/www/html/pandas-docs/stable`` to point to ``version/<latest-version>`` + for major and minor releases, or ``version/<minor>`` to ``version/<patch>`` for + patch releases. The exact instructions are (replace the example version numbers by + the appropriate ones for the version you are releasing): + + - Log in to the server and use the correct user. + - `cd /var/www/html/pandas-docs/` + - `ln -sfn version/2.1 stable` (for a major or minor release) + - `ln -sfn version/2.0.3 version/2.0` (for a patch release) 2. If releasing a major or minor release, open a PR in our source code to update ``web/pandas/versions.json``, to have the desired versions in the documentation @@ -488,13 +502,16 @@ Post-Release 5. Open a PR with the placeholder for the release notes of the next version. See for example `the PR for 1.5.3 <https://github.com/pandas-dev/pandas/pull/49843/files>`_. + Note that the template to use depends on whether it is a major, minor or patch release. 6. Announce the new release in the official channels (use previous announcements for reference): - The pandas-dev and pydata mailing lists - - Twitter, Mastodon and Telegram + - Twitter, Mastodon, Telegram and LinkedIn +7. Update this release instructions to fix anything incorrect and to update about any + change since the last release. .. _governance documents: https://github.com/pandas-dev/pandas-governance .. _list of permissions: https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization
Backport PR #53435: DOC: Update release process
https://api.github.com/repos/pandas-dev/pandas/pulls/53555
2023-06-07T15:09:28Z
2023-06-07T16:32:26Z
2023-06-07T16:32:25Z
2023-06-07T16:32:26Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 304b4616355db..4d4efe4e1704c 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -263,11 +263,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.window.ewm.ExponentialMovingWindow.cov \ pandas.api.indexers.BaseIndexer \ pandas.api.indexers.VariableOffsetWindowIndexer \ - pandas.core.groupby.DataFrameGroupBy.count \ - pandas.core.groupby.DataFrameGroupBy.cummax \ - pandas.core.groupby.DataFrameGroupBy.cummin \ - pandas.core.groupby.DataFrameGroupBy.cumprod \ - pandas.core.groupby.DataFrameGroupBy.cumsum \ pandas.core.groupby.DataFrameGroupBy.diff \ pandas.core.groupby.DataFrameGroupBy.ffill \ pandas.core.groupby.DataFrameGroupBy.max \ @@ -283,11 +278,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.groupby.DataFrameGroupBy.std \ pandas.core.groupby.DataFrameGroupBy.sum \ pandas.core.groupby.DataFrameGroupBy.var \ - pandas.core.groupby.SeriesGroupBy.count \ - pandas.core.groupby.SeriesGroupBy.cummax \ - pandas.core.groupby.SeriesGroupBy.cummin \ - pandas.core.groupby.SeriesGroupBy.cumprod \ - pandas.core.groupby.SeriesGroupBy.cumsum \ pandas.core.groupby.SeriesGroupBy.diff \ pandas.core.groupby.SeriesGroupBy.ffill \ pandas.core.groupby.SeriesGroupBy.max \ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 5d15be19f34f7..aa933e86a5cf4 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2028,7 +2028,7 @@ def all(self, skipna: bool = True): @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def count(self) -> NDFrameT: """ Compute count of group, excluding missing values. @@ -2037,6 +2037,38 @@ def count(self) -> NDFrameT: ------- Series or DataFrame Count of values within each group. + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, np.nan], index=lst) + >>> ser + a 1.0 + a 2.0 + b NaN + dtype: float64 + >>> ser.groupby(level=0).count() + a 2 + b 0 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, np.nan, 3], [1, np.nan, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["cow", "horse", "bull"]) + >>> df + a b c + cow 1 NaN 3 + horse 1 NaN 6 + bull 7 8.0 9 + >>> df.groupby("a").count() + b c + a + 1 0 2 + 7 1 1 """ data = self._get_data_to_aggregate() ids, _, ngroups = self.grouper.group_info @@ -3890,7 +3922,7 @@ def rank( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def cumprod( self, axis: Axis | lib.NoDefault = lib.no_default, *args, **kwargs ) -> NDFrameT: @@ -3900,6 +3932,41 @@ def cumprod( Returns ------- Series or DataFrame + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([6, 2, 0], index=lst) + >>> ser + a 6 + a 2 + b 0 + dtype: int64 + >>> ser.groupby(level=0).cumprod() + a 6 + a 12 + b 0 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 2, 5], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["cow", "horse", "bull"]) + >>> df + a b c + cow 1 8 2 + horse 1 2 5 + bull 2 6 9 + >>> df.groupby("a").groups + {1: ['cow', 'horse'], 2: ['bull']} + >>> df.groupby("a").cumprod() + b c + cow 8 2 + horse 16 10 + bull 6 9 """ nv.validate_groupby_func("cumprod", args, kwargs, ["numeric_only", "skipna"]) if axis is not lib.no_default: @@ -3916,7 +3983,7 @@ def cumprod( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def cumsum( self, axis: Axis | lib.NoDefault = lib.no_default, *args, **kwargs ) -> NDFrameT: @@ -3926,6 +3993,41 @@ def cumsum( Returns ------- Series or DataFrame + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([6, 2, 0], index=lst) + >>> ser + a 6 + a 2 + b 0 + dtype: int64 + >>> ser.groupby(level=0).cumsum() + a 6 + a 8 + b 0 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 2, 5], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["fox", "gorilla", "lion"]) + >>> df + a b c + fox 1 8 2 + gorilla 1 2 5 + lion 2 6 9 + >>> df.groupby("a").groups + {1: ['fox', 'gorilla'], 2: ['lion']} + >>> df.groupby("a").cumsum() + b c + fox 8 2 + gorilla 10 7 + lion 6 9 """ nv.validate_groupby_func("cumsum", args, kwargs, ["numeric_only", "skipna"]) if axis is not lib.no_default: @@ -3942,7 +4044,7 @@ def cumsum( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def cummin( self, axis: AxisInt | lib.NoDefault = lib.no_default, @@ -3955,6 +4057,47 @@ def cummin( Returns ------- Series or DataFrame + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([1, 6, 2, 3, 0, 4], index=lst) + >>> ser + a 1 + a 6 + a 2 + b 3 + b 0 + b 4 + dtype: int64 + >>> ser.groupby(level=0).cummin() + a 1 + a 1 + a 1 + b 3 + b 0 + b 0 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 0, 2], [1, 1, 5], [6, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["snake", "rabbit", "turtle"]) + >>> df + a b c + snake 1 0 2 + rabbit 1 1 5 + turtle 6 6 9 + >>> df.groupby("a").groups + {1: ['snake', 'rabbit'], 6: ['turtle']} + >>> df.groupby("a").cummin() + b c + snake 0 2 + rabbit 0 2 + turtle 6 9 """ skipna = kwargs.get("skipna", True) if axis is not lib.no_default: @@ -3976,7 +4119,7 @@ def cummin( @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def cummax( self, axis: AxisInt | lib.NoDefault = lib.no_default, @@ -3989,6 +4132,47 @@ def cummax( Returns ------- Series or DataFrame + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'a', 'b', 'b', 'b'] + >>> ser = pd.Series([1, 6, 2, 3, 1, 4], index=lst) + >>> ser + a 1 + a 6 + a 2 + b 3 + b 1 + b 4 + dtype: int64 + >>> ser.groupby(level=0).cummax() + a 1 + a 6 + a 6 + b 3 + b 3 + b 4 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 8, 2], [1, 1, 0], [2, 6, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["cow", "horse", "bull"]) + >>> df + a b c + cow 1 8 2 + horse 1 1 0 + bull 2 6 9 + >>> df.groupby("a").groups + {1: ['cow', 'horse'], 2: ['bull']} + >>> df.groupby("a").cummax() + b c + cow 8 2 + horse 8 2 + bull 6 9 """ skipna = kwargs.get("skipna", True) if axis is not lib.no_default:
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53554
2023-06-07T14:49:25Z
2023-06-07T20:04:03Z
2023-06-07T20:04:03Z
2023-06-08T08:46:03Z
TST: Add test for timedelta of fraction GH#9048
diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index 92db9af275340..828f991eccfa6 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -293,6 +293,11 @@ def test_to_timedelta_numeric_ea(self, any_numeric_ea_dtype): expected = Series([pd.Timedelta(1, unit="ns"), pd.NaT]) tm.assert_series_equal(result, expected) + def test_to_timedelta_fraction(self): + result = to_timedelta(1.0 / 3, unit="h") + expected = pd.Timedelta("0 days 00:19:59.999999998") + assert result == expected + def test_from_numeric_arrow_dtype(any_numeric_ea_dtype): # GH 52425
- [ ] closes #9048 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53552
2023-06-07T10:18:30Z
2023-06-07T15:40:49Z
2023-06-07T15:40:49Z
2023-06-07T22:41:11Z
TST: Add test for complex categories GH#16399
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index 155c61508b706..07a4e06db2e74 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -1174,6 +1174,15 @@ def test_cast_string_to_complex(): tm.assert_frame_equal(result, expected) +def test_categorical_complex(): + result = Categorical([1, 2 + 2j]) + expected = Categorical([1.0 + 0.0j, 2.0 + 2.0j]) + tm.assert_categorical_equal(result, expected) + result = Categorical([1, 2, 2 + 2j]) + expected = Categorical([1.0 + 0.0j, 2.0 + 0.0j, 2.0 + 2.0j]) + tm.assert_categorical_equal(result, expected) + + def test_multi_column_dtype_assignment(): # GH #27583 df = pd.DataFrame({"a": [0.0], "b": 0.0})
- [ ] closes #16399 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53551
2023-06-07T06:48:40Z
2023-06-07T15:44:41Z
2023-06-07T15:44:41Z
2023-06-07T22:41:07Z
TST: Use fixtures instead of TestPlotBase
diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 921f2b3ef3368..8b357754085c8 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -11,9 +11,6 @@ import numpy as np -from pandas.util._decorators import cache_readonly -import pandas.util._test_decorators as td - from pandas.core.dtypes.api import is_list_like import pandas as pd @@ -24,492 +21,475 @@ from matplotlib.axes import Axes -@td.skip_if_no_mpl -class TestPlotBase: +def _check_legend_labels(axes, labels=None, visible=True): + """ + Check each axes has expected legend labels + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + labels : list-like + expected legend labels + visible : bool + expected legend visibility. labels are checked only when visible is + True + """ + if visible and (labels is None): + raise ValueError("labels must be specified when visible is True") + axes = _flatten_visible(axes) + for ax in axes: + if visible: + assert ax.get_legend() is not None + _check_text_labels(ax.get_legend().get_texts(), labels) + else: + assert ax.get_legend() is None + + +def _check_legend_marker(ax, expected_markers=None, visible=True): + """ + Check ax has expected legend markers + + Parameters + ---------- + ax : matplotlib Axes object + expected_markers : list-like + expected legend markers + visible : bool + expected legend visibility. labels are checked only when visible is + True + """ + if visible and (expected_markers is None): + raise ValueError("Markers must be specified when visible is True") + if visible: + handles, _ = ax.get_legend_handles_labels() + markers = [handle.get_marker() for handle in handles] + assert markers == expected_markers + else: + assert ax.get_legend() is None + + +def _check_data(xp, rs): + """ + Check each axes has identical lines + + Parameters + ---------- + xp : matplotlib Axes object + rs : matplotlib Axes object + """ + xp_lines = xp.get_lines() + rs_lines = rs.get_lines() + + assert len(xp_lines) == len(rs_lines) + for xpl, rsl in zip(xp_lines, rs_lines): + xpdata = xpl.get_xydata() + rsdata = rsl.get_xydata() + tm.assert_almost_equal(xpdata, rsdata) + + tm.close() + + +def _check_visible(collections, visible=True): + """ + Check each artist is visible or not + + Parameters + ---------- + collections : matplotlib Artist or its list-like + target Artist or its list or collection + visible : bool + expected visibility + """ + from matplotlib.collections import Collection + + if not isinstance(collections, Collection) and not is_list_like(collections): + collections = [collections] + + for patch in collections: + assert patch.get_visible() == visible + + +def _check_patches_all_filled(axes: Axes | Sequence[Axes], filled: bool = True) -> None: """ - This is a common base class used for various plotting tests + Check for each artist whether it is filled or not + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + filled : bool + expected filling """ - def setup_method(self): - import matplotlib as mpl + axes = _flatten_visible(axes) + for ax in axes: + for patch in ax.patches: + assert patch.fill == filled - mpl.rcdefaults() - def teardown_method(self): - tm.close() +def _get_colors_mapped(series, colors): + unique = series.unique() + # unique and colors length can be differed + # depending on slice value + mapped = dict(zip(unique, colors)) + return [mapped[v] for v in series.values] - @cache_readonly - def plt(self): - import matplotlib.pyplot as plt - return plt +def _check_colors(collections, linecolors=None, facecolors=None, mapping=None): + """ + Check each artist has expected line colors and face colors - @cache_readonly - def colorconverter(self): - from matplotlib import colors + Parameters + ---------- + collections : list-like + list or collection of target artist + linecolors : list-like which has the same length as collections + list of expected line colors + facecolors : list-like which has the same length as collections + list of expected face colors + mapping : Series + Series used for color grouping key + used for andrew_curves, parallel_coordinates, radviz test + """ + from matplotlib import colors + from matplotlib.collections import ( + Collection, + LineCollection, + PolyCollection, + ) + from matplotlib.lines import Line2D + + conv = colors.ColorConverter + if linecolors is not None: + if mapping is not None: + linecolors = _get_colors_mapped(mapping, linecolors) + linecolors = linecolors[: len(collections)] + + assert len(collections) == len(linecolors) + for patch, color in zip(collections, linecolors): + if isinstance(patch, Line2D): + result = patch.get_color() + # Line2D may contains string color expression + result = conv.to_rgba(result) + elif isinstance(patch, (PolyCollection, LineCollection)): + result = tuple(patch.get_edgecolor()[0]) + else: + result = patch.get_edgecolor() - return colors.colorConverter + expected = conv.to_rgba(color) + assert result == expected - def _check_legend_labels(self, axes, labels=None, visible=True): - """ - Check each axes has expected legend labels + if facecolors is not None: + if mapping is not None: + facecolors = _get_colors_mapped(mapping, facecolors) + facecolors = facecolors[: len(collections)] - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - labels : list-like - expected legend labels - visible : bool - expected legend visibility. labels are checked only when visible is - True - """ - if visible and (labels is None): - raise ValueError("labels must be specified when visible is True") - axes = self._flatten_visible(axes) - for ax in axes: - if visible: - assert ax.get_legend() is not None - self._check_text_labels(ax.get_legend().get_texts(), labels) + assert len(collections) == len(facecolors) + for patch, color in zip(collections, facecolors): + if isinstance(patch, Collection): + # returned as list of np.array + result = patch.get_facecolor()[0] else: - assert ax.get_legend() is None - - def _check_legend_marker(self, ax, expected_markers=None, visible=True): - """ - Check ax has expected legend markers - - Parameters - ---------- - ax : matplotlib Axes object - expected_markers : list-like - expected legend markers - visible : bool - expected legend visibility. labels are checked only when visible is - True - """ - if visible and (expected_markers is None): - raise ValueError("Markers must be specified when visible is True") - if visible: - handles, _ = ax.get_legend_handles_labels() - markers = [handle.get_marker() for handle in handles] - assert markers == expected_markers - else: - assert ax.get_legend() is None + result = patch.get_facecolor() - def _check_data(self, xp, rs): - """ - Check each axes has identical lines - - Parameters - ---------- - xp : matplotlib Axes object - rs : matplotlib Axes object - """ - xp_lines = xp.get_lines() - rs_lines = rs.get_lines() - - assert len(xp_lines) == len(rs_lines) - for xpl, rsl in zip(xp_lines, rs_lines): - xpdata = xpl.get_xydata() - rsdata = rsl.get_xydata() - tm.assert_almost_equal(xpdata, rsdata) - - tm.close() - - def _check_visible(self, collections, visible=True): - """ - Check each artist is visible or not - - Parameters - ---------- - collections : matplotlib Artist or its list-like - target Artist or its list or collection - visible : bool - expected visibility - """ - from matplotlib.collections import Collection - - if not isinstance(collections, Collection) and not is_list_like(collections): - collections = [collections] - - for patch in collections: - assert patch.get_visible() == visible - - def _check_patches_all_filled( - self, axes: Axes | Sequence[Axes], filled: bool = True - ) -> None: - """ - Check for each artist whether it is filled or not - - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - filled : bool - expected filling - """ - - axes = self._flatten_visible(axes) - for ax in axes: - for patch in ax.patches: - assert patch.fill == filled - - def _get_colors_mapped(self, series, colors): - unique = series.unique() - # unique and colors length can be differed - # depending on slice value - mapped = dict(zip(unique, colors)) - return [mapped[v] for v in series.values] - - def _check_colors( - self, collections, linecolors=None, facecolors=None, mapping=None - ): - """ - Check each artist has expected line colors and face colors - - Parameters - ---------- - collections : list-like - list or collection of target artist - linecolors : list-like which has the same length as collections - list of expected line colors - facecolors : list-like which has the same length as collections - list of expected face colors - mapping : Series - Series used for color grouping key - used for andrew_curves, parallel_coordinates, radviz test - """ - from matplotlib.collections import ( - Collection, - LineCollection, - PolyCollection, - ) - from matplotlib.lines import Line2D - - conv = self.colorconverter - if linecolors is not None: - if mapping is not None: - linecolors = self._get_colors_mapped(mapping, linecolors) - linecolors = linecolors[: len(collections)] - - assert len(collections) == len(linecolors) - for patch, color in zip(collections, linecolors): - if isinstance(patch, Line2D): - result = patch.get_color() - # Line2D may contains string color expression - result = conv.to_rgba(result) - elif isinstance(patch, (PolyCollection, LineCollection)): - result = tuple(patch.get_edgecolor()[0]) - else: - result = patch.get_edgecolor() - - expected = conv.to_rgba(color) - assert result == expected - - if facecolors is not None: - if mapping is not None: - facecolors = self._get_colors_mapped(mapping, facecolors) - facecolors = facecolors[: len(collections)] - - assert len(collections) == len(facecolors) - for patch, color in zip(collections, facecolors): - if isinstance(patch, Collection): - # returned as list of np.array - result = patch.get_facecolor()[0] - else: - result = patch.get_facecolor() - - if isinstance(result, np.ndarray): - result = tuple(result) - - expected = conv.to_rgba(color) - assert result == expected - - def _check_text_labels(self, texts, expected): - """ - Check each text has expected labels - - Parameters - ---------- - texts : matplotlib Text object, or its list-like - target text, or its list - expected : str or list-like which has the same length as texts - expected text label, or its list - """ - if not is_list_like(texts): - assert texts.get_text() == expected - else: - labels = [t.get_text() for t in texts] - assert len(labels) == len(expected) - for label, e in zip(labels, expected): - assert label == e - - def _check_ticks_props( - self, axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None - ): - """ - Check each axes has expected tick properties - - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - xlabelsize : number - expected xticks font size - xrot : number - expected xticks rotation - ylabelsize : number - expected yticks font size - yrot : number - expected yticks rotation - """ - from matplotlib.ticker import NullFormatter - - axes = self._flatten_visible(axes) - for ax in axes: - if xlabelsize is not None or xrot is not None: - if isinstance(ax.xaxis.get_minor_formatter(), NullFormatter): - # If minor ticks has NullFormatter, rot / fontsize are not - # retained - labels = ax.get_xticklabels() - else: - labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True) - - for label in labels: - if xlabelsize is not None: - tm.assert_almost_equal(label.get_fontsize(), xlabelsize) - if xrot is not None: - tm.assert_almost_equal(label.get_rotation(), xrot) - - if ylabelsize is not None or yrot is not None: - if isinstance(ax.yaxis.get_minor_formatter(), NullFormatter): - labels = ax.get_yticklabels() - else: - labels = ax.get_yticklabels() + ax.get_yticklabels(minor=True) - - for label in labels: - if ylabelsize is not None: - tm.assert_almost_equal(label.get_fontsize(), ylabelsize) - if yrot is not None: - tm.assert_almost_equal(label.get_rotation(), yrot) - - def _check_ax_scales(self, axes, xaxis="linear", yaxis="linear"): - """ - Check each axes has expected scales - - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - xaxis : {'linear', 'log'} - expected xaxis scale - yaxis : {'linear', 'log'} - expected yaxis scale - """ - axes = self._flatten_visible(axes) - for ax in axes: - assert ax.xaxis.get_scale() == xaxis - assert ax.yaxis.get_scale() == yaxis - - def _check_axes_shape(self, axes, axes_num=None, layout=None, figsize=None): - """ - Check expected number of axes is drawn in expected layout - - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - axes_num : number - expected number of axes. Unnecessary axes should be set to - invisible. - layout : tuple - expected layout, (expected number of rows , columns) - figsize : tuple - expected figsize. default is matplotlib default - """ - from pandas.plotting._matplotlib.tools import flatten_axes - - if figsize is None: - figsize = (6.4, 4.8) - visible_axes = self._flatten_visible(axes) - - if axes_num is not None: - assert len(visible_axes) == axes_num - for ax in visible_axes: - # check something drawn on visible axes - assert len(ax.get_children()) > 0 - - if layout is not None: - result = self._get_axes_layout(flatten_axes(axes)) - assert result == layout - - tm.assert_numpy_array_equal( - visible_axes[0].figure.get_size_inches(), - np.array(figsize, dtype=np.float64), - ) - - def _get_axes_layout(self, axes): + if isinstance(result, np.ndarray): + result = tuple(result) + + expected = conv.to_rgba(color) + assert result == expected + + +def _check_text_labels(texts, expected): + """ + Check each text has expected labels + + Parameters + ---------- + texts : matplotlib Text object, or its list-like + target text, or its list + expected : str or list-like which has the same length as texts + expected text label, or its list + """ + if not is_list_like(texts): + assert texts.get_text() == expected + else: + labels = [t.get_text() for t in texts] + assert len(labels) == len(expected) + for label, e in zip(labels, expected): + assert label == e + + +def _check_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None): + """ + Check each axes has expected tick properties + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + xlabelsize : number + expected xticks font size + xrot : number + expected xticks rotation + ylabelsize : number + expected yticks font size + yrot : number + expected yticks rotation + """ + from matplotlib.ticker import NullFormatter + + axes = _flatten_visible(axes) + for ax in axes: + if xlabelsize is not None or xrot is not None: + if isinstance(ax.xaxis.get_minor_formatter(), NullFormatter): + # If minor ticks has NullFormatter, rot / fontsize are not + # retained + labels = ax.get_xticklabels() + else: + labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True) + + for label in labels: + if xlabelsize is not None: + tm.assert_almost_equal(label.get_fontsize(), xlabelsize) + if xrot is not None: + tm.assert_almost_equal(label.get_rotation(), xrot) + + if ylabelsize is not None or yrot is not None: + if isinstance(ax.yaxis.get_minor_formatter(), NullFormatter): + labels = ax.get_yticklabels() + else: + labels = ax.get_yticklabels() + ax.get_yticklabels(minor=True) + + for label in labels: + if ylabelsize is not None: + tm.assert_almost_equal(label.get_fontsize(), ylabelsize) + if yrot is not None: + tm.assert_almost_equal(label.get_rotation(), yrot) + + +def _check_ax_scales(axes, xaxis="linear", yaxis="linear"): + """ + Check each axes has expected scales + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + xaxis : {'linear', 'log'} + expected xaxis scale + yaxis : {'linear', 'log'} + expected yaxis scale + """ + axes = _flatten_visible(axes) + for ax in axes: + assert ax.xaxis.get_scale() == xaxis + assert ax.yaxis.get_scale() == yaxis + + +def _check_axes_shape(axes, axes_num=None, layout=None, figsize=None): + """ + Check expected number of axes is drawn in expected layout + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + axes_num : number + expected number of axes. Unnecessary axes should be set to + invisible. + layout : tuple + expected layout, (expected number of rows , columns) + figsize : tuple + expected figsize. default is matplotlib default + """ + from pandas.plotting._matplotlib.tools import flatten_axes + + if figsize is None: + figsize = (6.4, 4.8) + visible_axes = _flatten_visible(axes) + + if axes_num is not None: + assert len(visible_axes) == axes_num + for ax in visible_axes: + # check something drawn on visible axes + assert len(ax.get_children()) > 0 + + if layout is not None: x_set = set() y_set = set() - for ax in axes: + for ax in flatten_axes(axes): # check axes coordinates to estimate layout points = ax.get_position().get_points() x_set.add(points[0][0]) y_set.add(points[0][1]) - return (len(y_set), len(x_set)) - - def _flatten_visible(self, axes): - """ - Flatten axes, and filter only visible - - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - - """ - from pandas.plotting._matplotlib.tools import flatten_axes - - axes = flatten_axes(axes) - axes = [ax for ax in axes if ax.get_visible()] - return axes - - def _check_has_errorbars(self, axes, xerr=0, yerr=0): - """ - Check axes has expected number of errorbars - - Parameters - ---------- - axes : matplotlib Axes object, or its list-like - xerr : number - expected number of x errorbar - yerr : number - expected number of y errorbar - """ - axes = self._flatten_visible(axes) - for ax in axes: - containers = ax.containers - xerr_count = 0 - yerr_count = 0 - for c in containers: - has_xerr = getattr(c, "has_xerr", False) - has_yerr = getattr(c, "has_yerr", False) - if has_xerr: - xerr_count += 1 - if has_yerr: - yerr_count += 1 - assert xerr == xerr_count - assert yerr == yerr_count - - def _check_box_return_type( - self, returned, return_type, expected_keys=None, check_ax_title=True - ): - """ - Check box returned type is correct - - Parameters - ---------- - returned : object to be tested, returned from boxplot - return_type : str - return_type passed to boxplot - expected_keys : list-like, optional - group labels in subplot case. If not passed, - the function checks assuming boxplot uses single ax - check_ax_title : bool - Whether to check the ax.title is the same as expected_key - Intended to be checked by calling from ``boxplot``. - Normal ``plot`` doesn't attach ``ax.title``, it must be disabled. - """ - from matplotlib.axes import Axes - - types = {"dict": dict, "axes": Axes, "both": tuple} - if expected_keys is None: - # should be fixed when the returning default is changed - if return_type is None: - return_type = "dict" - - assert isinstance(returned, types[return_type]) - if return_type == "both": - assert isinstance(returned.ax, Axes) - assert isinstance(returned.lines, dict) - else: - # should be fixed when the returning default is changed - if return_type is None: - for r in self._flatten_visible(returned): - assert isinstance(r, Axes) - return - - assert isinstance(returned, Series) - - assert sorted(returned.keys()) == sorted(expected_keys) - for key, value in returned.items(): - assert isinstance(value, types[return_type]) - # check returned dict has correct mapping - if return_type == "axes": - if check_ax_title: - assert value.get_title() == key - elif return_type == "both": - if check_ax_title: - assert value.ax.get_title() == key - assert isinstance(value.ax, Axes) - assert isinstance(value.lines, dict) - elif return_type == "dict": - line = value["medians"][0] - axes = line.axes - if check_ax_title: - assert axes.get_title() == key - else: - raise AssertionError - - def _check_grid_settings(self, obj, kinds, kws={}): - # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792 - - import matplotlib as mpl - - def is_grid_on(): - xticks = self.plt.gca().xaxis.get_major_ticks() - yticks = self.plt.gca().yaxis.get_major_ticks() - xoff = all(not g.gridline.get_visible() for g in xticks) - yoff = all(not g.gridline.get_visible() for g in yticks) - - return not (xoff and yoff) - - spndx = 1 - for kind in kinds: - self.plt.subplot(1, 4 * len(kinds), spndx) + result = (len(y_set), len(x_set)) + assert result == layout + + tm.assert_numpy_array_equal( + visible_axes[0].figure.get_size_inches(), + np.array(figsize, dtype=np.float64), + ) + + +def _flatten_visible(axes): + """ + Flatten axes, and filter only visible + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + + """ + from pandas.plotting._matplotlib.tools import flatten_axes + + axes = flatten_axes(axes) + axes = [ax for ax in axes if ax.get_visible()] + return axes + + +def _check_has_errorbars(axes, xerr=0, yerr=0): + """ + Check axes has expected number of errorbars + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + xerr : number + expected number of x errorbar + yerr : number + expected number of y errorbar + """ + axes = _flatten_visible(axes) + for ax in axes: + containers = ax.containers + xerr_count = 0 + yerr_count = 0 + for c in containers: + has_xerr = getattr(c, "has_xerr", False) + has_yerr = getattr(c, "has_yerr", False) + if has_xerr: + xerr_count += 1 + if has_yerr: + yerr_count += 1 + assert xerr == xerr_count + assert yerr == yerr_count + + +def _check_box_return_type( + returned, return_type, expected_keys=None, check_ax_title=True +): + """ + Check box returned type is correct + + Parameters + ---------- + returned : object to be tested, returned from boxplot + return_type : str + return_type passed to boxplot + expected_keys : list-like, optional + group labels in subplot case. If not passed, + the function checks assuming boxplot uses single ax + check_ax_title : bool + Whether to check the ax.title is the same as expected_key + Intended to be checked by calling from ``boxplot``. + Normal ``plot`` doesn't attach ``ax.title``, it must be disabled. + """ + from matplotlib.axes import Axes + + types = {"dict": dict, "axes": Axes, "both": tuple} + if expected_keys is None: + # should be fixed when the returning default is changed + if return_type is None: + return_type = "dict" + + assert isinstance(returned, types[return_type]) + if return_type == "both": + assert isinstance(returned.ax, Axes) + assert isinstance(returned.lines, dict) + else: + # should be fixed when the returning default is changed + if return_type is None: + for r in _flatten_visible(returned): + assert isinstance(r, Axes) + return + + assert isinstance(returned, Series) + + assert sorted(returned.keys()) == sorted(expected_keys) + for key, value in returned.items(): + assert isinstance(value, types[return_type]) + # check returned dict has correct mapping + if return_type == "axes": + if check_ax_title: + assert value.get_title() == key + elif return_type == "both": + if check_ax_title: + assert value.ax.get_title() == key + assert isinstance(value.ax, Axes) + assert isinstance(value.lines, dict) + elif return_type == "dict": + line = value["medians"][0] + axes = line.axes + if check_ax_title: + assert axes.get_title() == key + else: + raise AssertionError + + +def _check_grid_settings(obj, kinds, kws={}): + # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792 + + import matplotlib as mpl + + def is_grid_on(): + xticks = mpl.pyplot.gca().xaxis.get_major_ticks() + yticks = mpl.pyplot.gca().yaxis.get_major_ticks() + xoff = all(not g.gridline.get_visible() for g in xticks) + yoff = all(not g.gridline.get_visible() for g in yticks) + + return not (xoff and yoff) + + spndx = 1 + for kind in kinds: + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) + spndx += 1 + mpl.rc("axes", grid=False) + obj.plot(kind=kind, **kws) + assert not is_grid_on() + mpl.pyplot.clf() + + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) + spndx += 1 + mpl.rc("axes", grid=True) + obj.plot(kind=kind, grid=False, **kws) + assert not is_grid_on() + mpl.pyplot.clf() + + if kind not in ["pie", "hexbin", "scatter"]: + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) spndx += 1 - mpl.rc("axes", grid=False) + mpl.rc("axes", grid=True) obj.plot(kind=kind, **kws) - assert not is_grid_on() - self.plt.clf() + assert is_grid_on() + mpl.pyplot.clf() - self.plt.subplot(1, 4 * len(kinds), spndx) + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) spndx += 1 - mpl.rc("axes", grid=True) - obj.plot(kind=kind, grid=False, **kws) - assert not is_grid_on() - self.plt.clf() - - if kind not in ["pie", "hexbin", "scatter"]: - self.plt.subplot(1, 4 * len(kinds), spndx) - spndx += 1 - mpl.rc("axes", grid=True) - obj.plot(kind=kind, **kws) - assert is_grid_on() - self.plt.clf() - - self.plt.subplot(1, 4 * len(kinds), spndx) - spndx += 1 - mpl.rc("axes", grid=False) - obj.plot(kind=kind, grid=True, **kws) - assert is_grid_on() - self.plt.clf() - - def _unpack_cycler(self, rcParams, field="color"): - """ - Auxiliary function for correctly unpacking cycler after MPL >= 1.5 - """ - return [v[field] for v in rcParams["axes.prop_cycle"]] - - def get_x_axis(self, ax): - return ax._shared_axes["x"] - - def get_y_axis(self, ax): - return ax._shared_axes["y"] + mpl.rc("axes", grid=False) + obj.plot(kind=kind, grid=True, **kws) + assert is_grid_on() + mpl.pyplot.clf() + + +def _unpack_cycler(rcParams, field="color"): + """ + Auxiliary function for correctly unpacking cycler after MPL >= 1.5 + """ + return [v[field] for v in rcParams["axes.prop_cycle"]] + + +def get_x_axis(ax): + return ax._shared_axes["x"] + + +def get_y_axis(ax): + return ax._shared_axes["y"] def _check_plot_works(f, default_axes=False, **kwargs): diff --git a/pandas/tests/plotting/conftest.py b/pandas/tests/plotting/conftest.py index 14c413f96c4ba..aa9952db17b74 100644 --- a/pandas/tests/plotting/conftest.py +++ b/pandas/tests/plotting/conftest.py @@ -7,6 +7,20 @@ ) +@pytest.fixture(autouse=True) +def reset_rcParams(): + mpl = pytest.importorskip("matplotlib") + with mpl.rc_context(): + yield + + +@pytest.fixture(autouse=True) +def close_all_figures(): + yield + plt = pytest.importorskip("matplotlib.pyplot") + plt.close("all") + + @pytest.fixture def hist_df(): n = 100 diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index ded3c1142f27b..77c11a5b11360 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -29,15 +29,27 @@ ) import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_ax_scales, + _check_axes_shape, + _check_box_return_type, + _check_colors, + _check_data, + _check_grid_settings, + _check_has_errorbars, + _check_legend_labels, _check_plot_works, + _check_text_labels, + _check_ticks_props, + _check_visible, + get_y_axis, ) from pandas.io.formats.printing import pprint_thing +mpl = pytest.importorskip("matplotlib") -@td.skip_if_no_mpl -class TestDataFramePlots(TestPlotBase): + +class TestDataFramePlots: @pytest.mark.xfail(reason="Api changed in 3.6.0") @pytest.mark.slow def test_plot(self): @@ -46,7 +58,7 @@ def test_plot(self): # _check_plot_works adds an ax so use default_axes=True to avoid warning axes = _check_plot_works(df.plot, default_axes=True, subplots=True) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) axes = _check_plot_works( df.plot, @@ -54,7 +66,7 @@ def test_plot(self): subplots=True, layout=(-1, 2), ) - self._check_axes_shape(axes, axes_num=4, layout=(2, 2)) + _check_axes_shape(axes, axes_num=4, layout=(2, 2)) axes = _check_plot_works( df.plot, @@ -62,8 +74,8 @@ def test_plot(self): subplots=True, use_index=False, ) - self._check_ticks_props(axes, xrot=0) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_ticks_props(axes, xrot=0) + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) df = DataFrame({"x": [1, 2], "y": [3, 4]}) msg = "'Line2D' object has no property 'blarg'" @@ -73,7 +85,7 @@ def test_plot(self): df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10])) ax = _check_plot_works(df.plot, use_index=True) - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) _check_plot_works(df.plot, yticks=[1, 5, 10]) _check_plot_works(df.plot, xticks=[1, 5, 10]) _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100)) @@ -86,25 +98,25 @@ def test_plot(self): # present). see: https://github.com/pandas-dev/pandas/issues/9737 axes = df.plot(subplots=True, title="blah") - self._check_axes_shape(axes, axes_num=3, layout=(3, 1)) + _check_axes_shape(axes, axes_num=3, layout=(3, 1)) # axes[0].figure.savefig("test.png") for ax in axes[:2]: - self._check_visible(ax.xaxis) # xaxis must be visible for grid - self._check_visible(ax.get_xticklabels(), visible=False) - self._check_visible(ax.get_xticklabels(minor=True), visible=False) - self._check_visible([ax.xaxis.get_label()], visible=False) + _check_visible(ax.xaxis) # xaxis must be visible for grid + _check_visible(ax.get_xticklabels(), visible=False) + _check_visible(ax.get_xticklabels(minor=True), visible=False) + _check_visible([ax.xaxis.get_label()], visible=False) for ax in [axes[2]]: - self._check_visible(ax.xaxis) - self._check_visible(ax.get_xticklabels()) - self._check_visible([ax.xaxis.get_label()]) - self._check_ticks_props(ax, xrot=0) + _check_visible(ax.xaxis) + _check_visible(ax.get_xticklabels()) + _check_visible([ax.xaxis.get_label()]) + _check_ticks_props(ax, xrot=0) _check_plot_works(df.plot, title="blah") tuples = zip(string.ascii_letters[:10], range(10)) df = DataFrame(np.random.rand(10, 3), index=MultiIndex.from_tuples(tuples)) ax = _check_plot_works(df.plot, use_index=True) - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) # unicode index = MultiIndex.from_tuples( @@ -130,13 +142,13 @@ def test_plot(self): # Test with single column df = DataFrame({"x": np.random.rand(10)}) axes = _check_plot_works(df.plot.bar, subplots=True) - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) axes = _check_plot_works(df.plot.bar, subplots=True, layout=(-1, 1)) - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) # When ax is supplied and required number of axes is 1, # passed ax should be used: - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() axes = df.plot.bar(subplots=True, ax=ax) assert len(axes) == 1 result = ax.axes @@ -190,7 +202,7 @@ def test_nonnumeric_exclude(self): def test_implicit_label(self): df = DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"]) ax = df.plot(x="a", y="b") - self._check_text_labels(ax.xaxis.get_label(), "a") + _check_text_labels(ax.xaxis.get_label(), "a") def test_donot_overwrite_index_name(self): # GH 8494 @@ -202,23 +214,23 @@ def test_donot_overwrite_index_name(self): def test_plot_xy(self): # columns.inferred_type == 'string' df = tm.makeTimeDataFrame() - self._check_data(df.plot(x=0, y=1), df.set_index("A")["B"].plot()) - self._check_data(df.plot(x=0), df.set_index("A").plot()) - self._check_data(df.plot(y=0), df.B.plot()) - self._check_data(df.plot(x="A", y="B"), df.set_index("A").B.plot()) - self._check_data(df.plot(x="A"), df.set_index("A").plot()) - self._check_data(df.plot(y="B"), df.B.plot()) + _check_data(df.plot(x=0, y=1), df.set_index("A")["B"].plot()) + _check_data(df.plot(x=0), df.set_index("A").plot()) + _check_data(df.plot(y=0), df.B.plot()) + _check_data(df.plot(x="A", y="B"), df.set_index("A").B.plot()) + _check_data(df.plot(x="A"), df.set_index("A").plot()) + _check_data(df.plot(y="B"), df.B.plot()) # columns.inferred_type == 'integer' df.columns = np.arange(1, len(df.columns) + 1) - self._check_data(df.plot(x=1, y=2), df.set_index(1)[2].plot()) - self._check_data(df.plot(x=1), df.set_index(1).plot()) - self._check_data(df.plot(y=1), df[1].plot()) + _check_data(df.plot(x=1, y=2), df.set_index(1)[2].plot()) + _check_data(df.plot(x=1), df.set_index(1).plot()) + _check_data(df.plot(y=1), df[1].plot()) # figsize and title ax = df.plot(x=1, y=2, title="Test", figsize=(16, 8)) - self._check_text_labels(ax.title, "Test") - self._check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16.0, 8.0)) + _check_text_labels(ax.title, "Test") + _check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16.0, 8.0)) # columns.inferred_type == 'mixed' # TODO add MultiIndex test @@ -230,15 +242,15 @@ def test_logscales(self, input_log, expected_log): df = DataFrame({"a": np.arange(100)}, index=np.arange(100)) ax = df.plot(logy=input_log) - self._check_ax_scales(ax, yaxis=expected_log) + _check_ax_scales(ax, yaxis=expected_log) assert ax.get_yscale() == expected_log ax = df.plot(logx=input_log) - self._check_ax_scales(ax, xaxis=expected_log) + _check_ax_scales(ax, xaxis=expected_log) assert ax.get_xscale() == expected_log ax = df.plot(loglog=input_log) - self._check_ax_scales(ax, xaxis=expected_log, yaxis=expected_log) + _check_ax_scales(ax, xaxis=expected_log, yaxis=expected_log) assert ax.get_xscale() == expected_log assert ax.get_yscale() == expected_log @@ -256,14 +268,14 @@ def test_xcompat(self): ax = df.plot(x_compat=True) lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) - self._check_ticks_props(ax, xrot=30) + _check_ticks_props(ax, xrot=30) tm.close() plotting.plot_params["xaxis.compat"] = True ax = df.plot() lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) - self._check_ticks_props(ax, xrot=30) + _check_ticks_props(ax, xrot=30) tm.close() plotting.plot_params["x_compat"] = False @@ -279,14 +291,14 @@ def test_xcompat(self): ax = df.plot() lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) - self._check_ticks_props(ax, xrot=30) + _check_ticks_props(ax, xrot=30) tm.close() ax = df.plot() lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) def test_period_compat(self): # GH 9012 @@ -298,7 +310,7 @@ def test_period_compat(self): ) df.plot() - self.plt.axhline(y=0) + mpl.pyplot.axhline(y=0) tm.close() def test_unsorted_index(self): @@ -465,7 +477,7 @@ def test_line_lim(self): assert xmax >= lines[0].get_data()[0][-1] axes = df.plot(secondary_y=True, subplots=True) - self._check_axes_shape(axes, axes_num=3, layout=(3, 1)) + _check_axes_shape(axes, axes_num=3, layout=(3, 1)) for ax in axes: assert hasattr(ax, "left_ax") assert not hasattr(ax, "right_ax") @@ -500,13 +512,13 @@ def test_area_lim(self, stacked): def test_area_sharey_dont_overwrite(self): # GH37942 df = DataFrame(np.random.rand(4, 2), columns=["x", "y"]) - fig, (ax1, ax2) = self.plt.subplots(1, 2, sharey=True) + fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2, sharey=True) df.plot(ax=ax1, kind="area") df.plot(ax=ax2, kind="area") - assert self.get_y_axis(ax1).joined(ax1, ax2) - assert self.get_y_axis(ax2).joined(ax1, ax2) + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) def test_bar_linewidth(self): df = DataFrame(np.random.randn(5, 5)) @@ -523,7 +535,7 @@ def test_bar_linewidth(self): # subplots axes = df.plot.bar(linewidth=2, subplots=True) - self._check_axes_shape(axes, axes_num=5, layout=(5, 1)) + _check_axes_shape(axes, axes_num=5, layout=(5, 1)) for ax in axes: for r in ax.patches: assert r.get_linewidth() == 2 @@ -656,7 +668,7 @@ def test_plot_scatter(self): # GH 6951 axes = df.plot(x="x", y="y", kind="scatter", subplots=True) - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) def test_raise_error_on_datetime_time_data(self): # GH 8113, datetime.time type is not supported by matplotlib in scatter @@ -751,7 +763,7 @@ def test_plot_scatter_with_c(self): # verify that we can still plot a solid color ax = df.plot.scatter(x=0, y=1, c="red") assert ax.collections[0].colorbar is None - self._check_colors(ax.collections, facecolors=["r"]) + _check_colors(ax.collections, facecolors=["r"]) # Ensure that we can pass an np.array straight through to matplotlib, # this functionality was accidentally removed previously. @@ -825,16 +837,16 @@ def test_plot_bar(self): df = DataFrame({"a": [0, 1], "b": [1, 0]}) ax = _check_plot_works(df.plot.bar) - self._check_ticks_props(ax, xrot=90) + _check_ticks_props(ax, xrot=90) ax = df.plot.bar(rot=35, fontsize=10) - self._check_ticks_props(ax, xrot=35, xlabelsize=10, ylabelsize=10) + _check_ticks_props(ax, xrot=35, xlabelsize=10, ylabelsize=10) ax = _check_plot_works(df.plot.barh) - self._check_ticks_props(ax, yrot=0) + _check_ticks_props(ax, yrot=0) ax = df.plot.barh(rot=55, fontsize=11) - self._check_ticks_props(ax, yrot=55, ylabelsize=11, xlabelsize=11) + _check_ticks_props(ax, yrot=55, ylabelsize=11, xlabelsize=11) def test_boxplot(self, hist_df): df = hist_df @@ -843,7 +855,7 @@ def test_boxplot(self, hist_df): labels = [pprint_thing(c) for c in numeric_cols] ax = _check_plot_works(df.plot.box) - self._check_text_labels(ax.get_xticklabels(), labels) + _check_text_labels(ax.get_xticklabels(), labels) tm.assert_numpy_array_equal( ax.xaxis.get_ticklocs(), np.arange(1, len(numeric_cols) + 1) ) @@ -851,7 +863,7 @@ def test_boxplot(self, hist_df): tm.close() axes = series.plot.box(rot=40) - self._check_ticks_props(axes, xrot=40, yrot=0) + _check_ticks_props(axes, xrot=40, yrot=0) tm.close() ax = _check_plot_works(series.plot.box) @@ -860,7 +872,7 @@ def test_boxplot(self, hist_df): ax = df.plot.box(positions=positions) numeric_cols = df._get_numeric_data().columns labels = [pprint_thing(c) for c in numeric_cols] - self._check_text_labels(ax.get_xticklabels(), labels) + _check_text_labels(ax.get_xticklabels(), labels) tm.assert_numpy_array_equal(ax.xaxis.get_ticklocs(), positions) assert len(ax.lines) == 7 * len(numeric_cols) @@ -871,8 +883,8 @@ def test_boxplot_vertical(self, hist_df): # if horizontal, yticklabels are rotated ax = df.plot.box(rot=50, fontsize=8, vert=False) - self._check_ticks_props(ax, xrot=0, yrot=50, ylabelsize=8) - self._check_text_labels(ax.get_yticklabels(), labels) + _check_ticks_props(ax, xrot=0, yrot=50, ylabelsize=8) + _check_text_labels(ax.get_yticklabels(), labels) assert len(ax.lines) == 7 * len(numeric_cols) axes = _check_plot_works( @@ -882,15 +894,15 @@ def test_boxplot_vertical(self, hist_df): vert=False, logx=True, ) - self._check_axes_shape(axes, axes_num=3, layout=(1, 3)) - self._check_ax_scales(axes, xaxis="log") + _check_axes_shape(axes, axes_num=3, layout=(1, 3)) + _check_ax_scales(axes, xaxis="log") for ax, label in zip(axes, labels): - self._check_text_labels(ax.get_yticklabels(), [label]) + _check_text_labels(ax.get_yticklabels(), [label]) assert len(ax.lines) == 7 positions = np.array([3, 2, 8]) ax = df.plot.box(positions=positions, vert=False) - self._check_text_labels(ax.get_yticklabels(), labels) + _check_text_labels(ax.get_yticklabels(), labels) tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), positions) assert len(ax.lines) == 7 * len(numeric_cols) @@ -905,27 +917,27 @@ def test_boxplot_return_type(self): df.plot.box(return_type="not_a_type") result = df.plot.box(return_type="dict") - self._check_box_return_type(result, "dict") + _check_box_return_type(result, "dict") result = df.plot.box(return_type="axes") - self._check_box_return_type(result, "axes") + _check_box_return_type(result, "axes") result = df.plot.box() # default axes - self._check_box_return_type(result, "axes") + _check_box_return_type(result, "axes") result = df.plot.box(return_type="both") - self._check_box_return_type(result, "both") + _check_box_return_type(result, "both") @td.skip_if_no_scipy def test_kde_df(self): df = DataFrame(np.random.randn(100, 4)) ax = _check_plot_works(df.plot, kind="kde") expected = [pprint_thing(c) for c in df.columns] - self._check_legend_labels(ax, labels=expected) - self._check_ticks_props(ax, xrot=0) + _check_legend_labels(ax, labels=expected) + _check_ticks_props(ax, xrot=0) ax = df.plot(kind="kde", rot=20, fontsize=5) - self._check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5) + _check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5) axes = _check_plot_works( df.plot, @@ -933,10 +945,10 @@ def test_kde_df(self): kind="kde", subplots=True, ) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) axes = df.plot(kind="kde", logy=True, subplots=True) - self._check_ax_scales(axes, yaxis="log") + _check_ax_scales(axes, yaxis="log") @td.skip_if_no_scipy def test_kde_missing_vals(self): @@ -952,7 +964,7 @@ def test_hist_df(self): ax = _check_plot_works(df.plot.hist) expected = [pprint_thing(c) for c in df.columns] - self._check_legend_labels(ax, labels=expected) + _check_legend_labels(ax, labels=expected) axes = _check_plot_works( df.plot.hist, @@ -960,11 +972,11 @@ def test_hist_df(self): subplots=True, logy=True, ) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) - self._check_ax_scales(axes, yaxis="log") + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_ax_scales(axes, yaxis="log") axes = series.plot.hist(rot=40) - self._check_ticks_props(axes, xrot=40, yrot=0) + _check_ticks_props(axes, xrot=40, yrot=0) tm.close() ax = series.plot.hist(cumulative=True, bins=4, density=True) @@ -981,7 +993,7 @@ def test_hist_df(self): # if horizontal, yticklabels are rotated axes = df.plot.hist(rot=50, fontsize=8, orientation="horizontal") - self._check_ticks_props(axes, xrot=0, yrot=50, ylabelsize=8) + _check_ticks_props(axes, xrot=0, yrot=50, ylabelsize=8) @pytest.mark.parametrize( "weights", [0.1 * np.ones(shape=(100,)), 0.1 * np.ones(shape=(100, 2))] @@ -1293,7 +1305,7 @@ def test_y_listlike(self, x, y, lbl, colors): ax = df.plot(x=x, y=y, label=lbl, color=colors) assert len(ax.lines) == len(y) - self._check_colors(ax.get_lines(), linecolors=colors) + _check_colors(ax.get_lines(), linecolors=colors) @pytest.mark.parametrize("x,y,colnames", [(0, 1, ["A", "B"]), (1, 0, [0, 1])]) def test_xy_args_integer(self, x, y, colnames): @@ -1321,7 +1333,7 @@ def test_hexbin_basic(self): # is colorbar assert len(axes[0].figure.axes) == 2 # return value is single axes - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) def test_hexbin_with_c(self): df = DataFrame( @@ -1368,10 +1380,10 @@ def test_pie_df(self): df.plot.pie() ax = _check_plot_works(df.plot.pie, y="Y") - self._check_text_labels(ax.texts, df.index) + _check_text_labels(ax.texts, df.index) ax = _check_plot_works(df.plot.pie, y=2) - self._check_text_labels(ax.texts, df.index) + _check_text_labels(ax.texts, df.index) axes = _check_plot_works( df.plot.pie, @@ -1380,7 +1392,7 @@ def test_pie_df(self): ) assert len(axes) == len(df.columns) for ax in axes: - self._check_text_labels(ax.texts, df.index) + _check_text_labels(ax.texts, df.index) for ax, ylabel in zip(axes, df.columns): assert ax.get_ylabel() == ylabel @@ -1396,14 +1408,14 @@ def test_pie_df(self): assert len(axes) == len(df.columns) for ax in axes: - self._check_text_labels(ax.texts, labels) - self._check_colors(ax.patches, facecolors=color_args) + _check_text_labels(ax.texts, labels) + _check_colors(ax.patches, facecolors=color_args) def test_pie_df_nan(self): df = DataFrame(np.random.rand(4, 4)) for i in range(4): df.iloc[i, i] = np.nan - fig, axes = self.plt.subplots(ncols=4) + fig, axes = mpl.pyplot.subplots(ncols=4) # GH 37668 kwargs = {"normalize": True} @@ -1434,25 +1446,25 @@ def test_errorbar_plot(self): # check line plots ax = _check_plot_works(df.plot, yerr=df_err, logy=True) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(df.plot, yerr=df_err, logx=True, logy=True) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(df.plot, yerr=df_err, loglog=True) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works( (df + 1).plot, yerr=df_err, xerr=df_err, kind="bar", log=True ) - self._check_has_errorbars(ax, xerr=2, yerr=2) + _check_has_errorbars(ax, xerr=2, yerr=2) # yerr is raw error values ax = _check_plot_works(df["y"].plot, yerr=np.ones(12) * 0.4) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(df.plot, yerr=np.ones((2, 12)) * 0.4) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) # yerr is column name for yerr in ["yerr", "誤差"]: @@ -1460,10 +1472,10 @@ def test_errorbar_plot(self): s_df[yerr] = np.ones(12) * 0.2 ax = _check_plot_works(s_df.plot, yerr=yerr) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(s_df.plot, y="y", x="x", yerr=yerr) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) with tm.external_error_raised(ValueError): df.plot(yerr=np.random.randn(11)) @@ -1481,19 +1493,19 @@ def test_errorbar_plot_different_kinds(self, kind): df_err = DataFrame(d_err) ax = _check_plot_works(df.plot, yerr=df_err["x"], kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(df.plot, yerr=d_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(df.plot, yerr=df_err, xerr=df_err, kind=kind) - self._check_has_errorbars(ax, xerr=2, yerr=2) + _check_has_errorbars(ax, xerr=2, yerr=2) ax = _check_plot_works(df.plot, yerr=df_err["x"], xerr=df_err["x"], kind=kind) - self._check_has_errorbars(ax, xerr=2, yerr=2) + _check_has_errorbars(ax, xerr=2, yerr=2) ax = _check_plot_works(df.plot, xerr=0.2, yerr=0.2, kind=kind) - self._check_has_errorbars(ax, xerr=2, yerr=2) + _check_has_errorbars(ax, xerr=2, yerr=2) axes = _check_plot_works( df.plot, @@ -1503,7 +1515,7 @@ def test_errorbar_plot_different_kinds(self, kind): subplots=True, kind=kind, ) - self._check_has_errorbars(axes, xerr=1, yerr=1) + _check_has_errorbars(axes, xerr=1, yerr=1) @pytest.mark.xfail(reason="Iterator is consumed", raises=ValueError) def test_errorbar_plot_iterator(self): @@ -1513,16 +1525,16 @@ def test_errorbar_plot_iterator(self): # yerr is iterator ax = _check_plot_works(df.plot, yerr=itertools.repeat(0.1, len(df))) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) def test_errorbar_with_integer_column_names(self): # test with integer column names df = DataFrame(np.abs(np.random.randn(10, 2))) df_err = DataFrame(np.abs(np.random.randn(10, 2))) ax = _check_plot_works(df.plot, yerr=df_err) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(df.plot, y=0, yerr=1) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) @pytest.mark.slow def test_errorbar_with_partial_columns(self): @@ -1531,13 +1543,13 @@ def test_errorbar_with_partial_columns(self): kinds = ["line", "bar"] for kind in kinds: ax = _check_plot_works(df.plot, yerr=df_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ix = date_range("1/1/2000", periods=10, freq="M") df.set_index(ix, inplace=True) df_err.set_index(ix, inplace=True) ax = _check_plot_works(df.plot, yerr=df_err, kind="line") - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) d = {"x": np.arange(12), "y": np.arange(12, 0, -1)} df = DataFrame(d) @@ -1545,7 +1557,7 @@ def test_errorbar_with_partial_columns(self): df_err = DataFrame(d_err) for err in [d_err, df_err]: ax = _check_plot_works(df.plot, yerr=err) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) @pytest.mark.parametrize("kind", ["line", "bar", "barh"]) def test_errorbar_timeseries(self, kind): @@ -1558,19 +1570,19 @@ def test_errorbar_timeseries(self, kind): tdf_err = DataFrame(d_err, index=ix) ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(tdf.plot, yerr=d_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) ax = _check_plot_works(tdf.plot, y="y", yerr=tdf_err["x"], kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(tdf.plot, y="y", yerr="x", kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=2) + _check_has_errorbars(ax, xerr=0, yerr=2) axes = _check_plot_works( tdf.plot, @@ -1579,7 +1591,7 @@ def test_errorbar_timeseries(self, kind): yerr=tdf_err, subplots=True, ) - self._check_has_errorbars(axes, xerr=0, yerr=1) + _check_has_errorbars(axes, xerr=0, yerr=1) def test_errorbar_asymmetrical(self): np.random.seed(0) @@ -1623,14 +1635,14 @@ def test_errorbar_scatter(self): ) ax = _check_plot_works(df.plot.scatter, x="x", y="y") - self._check_has_errorbars(ax, xerr=0, yerr=0) + _check_has_errorbars(ax, xerr=0, yerr=0) ax = _check_plot_works(df.plot.scatter, x="x", y="y", xerr=df_err) - self._check_has_errorbars(ax, xerr=1, yerr=0) + _check_has_errorbars(ax, xerr=1, yerr=0) ax = _check_plot_works(df.plot.scatter, x="x", y="y", yerr=df_err) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(df.plot.scatter, x="x", y="y", xerr=df_err, yerr=df_err) - self._check_has_errorbars(ax, xerr=1, yerr=1) + _check_has_errorbars(ax, xerr=1, yerr=1) def _check_errorbar_color(containers, expected, has_err="has_xerr"): lines = [] @@ -1641,21 +1653,19 @@ def _check_errorbar_color(containers, expected, has_err="has_xerr"): else: lines.append(el) err_lines = [x for x in lines if x in ax.collections] - self._check_colors( - err_lines, linecolors=np.array([expected] * len(err_lines)) - ) + _check_colors(err_lines, linecolors=np.array([expected] * len(err_lines))) # GH 8081 df = DataFrame( np.abs(np.random.randn(10, 5)), columns=["a", "b", "c", "d", "e"] ) ax = df.plot.scatter(x="a", y="b", xerr="d", yerr="e", c="red") - self._check_has_errorbars(ax, xerr=1, yerr=1) + _check_has_errorbars(ax, xerr=1, yerr=1) _check_errorbar_color(ax.containers, "red", has_err="has_xerr") _check_errorbar_color(ax.containers, "red", has_err="has_yerr") ax = df.plot.scatter(x="a", y="b", yerr="e", color="green") - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) _check_errorbar_color(ax.containers, "green", has_err="has_yerr") def test_scatter_unknown_colormap(self): @@ -1685,13 +1695,13 @@ def test_sharex_and_ax(self): def _check(axes): for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) for ax in [axes[0], axes[2]]: - self._check_visible(ax.get_xticklabels(), visible=False) - self._check_visible(ax.get_xticklabels(minor=True), visible=False) + _check_visible(ax.get_xticklabels(), visible=False) + _check_visible(ax.get_xticklabels(minor=True), visible=False) for ax in [axes[1], axes[3]]: - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) for ax in axes: df.plot(x="a", y="b", title="title", ax=ax, sharex=True) @@ -1713,9 +1723,9 @@ def _check(axes): gs.tight_layout(plt.gcf()) for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_yticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() def test_sharey_and_ax(self): @@ -1738,12 +1748,12 @@ def test_sharey_and_ax(self): def _check(axes): for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) for ax in [axes[0], axes[1]]: - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) for ax in [axes[2], axes[3]]: - self._check_visible(ax.get_yticklabels(), visible=False) + _check_visible(ax.get_yticklabels(), visible=False) for ax in axes: df.plot(x="a", y="b", title="title", ax=ax, sharey=True) @@ -1767,9 +1777,9 @@ def _check(axes): gs.tight_layout(plt.gcf()) for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_yticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) @td.skip_if_no_scipy def test_memory_leak(self): @@ -1835,9 +1845,9 @@ def _get_horizontal_grid(): ax2 = df.plot(ax=ax2) assert len(ax2.lines) == 2 for ax in [ax1, ax2]: - self._check_visible(ax.get_yticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() # subplots=True @@ -1846,9 +1856,9 @@ def _get_horizontal_grid(): assert len(ax1.lines) == 1 assert len(ax2.lines) == 1 for ax in axes: - self._check_visible(ax.get_yticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() # vertical / subplots / sharex=True / sharey=True @@ -1859,12 +1869,12 @@ def _get_horizontal_grid(): assert len(axes[1].lines) == 1 for ax in [ax1, ax2]: # yaxis are visible because there is only one column - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) # xaxis of axes0 (top) are hidden - self._check_visible(axes[0].get_xticklabels(), visible=False) - self._check_visible(axes[0].get_xticklabels(minor=True), visible=False) - self._check_visible(axes[1].get_xticklabels(), visible=True) - self._check_visible(axes[1].get_xticklabels(minor=True), visible=True) + _check_visible(axes[0].get_xticklabels(), visible=False) + _check_visible(axes[0].get_xticklabels(minor=True), visible=False) + _check_visible(axes[1].get_xticklabels(), visible=True) + _check_visible(axes[1].get_xticklabels(minor=True), visible=True) tm.close() # horizontal / subplots / sharex=True / sharey=True @@ -1873,13 +1883,13 @@ def _get_horizontal_grid(): axes = df.plot(subplots=True, ax=[ax1, ax2], sharex=True, sharey=True) assert len(axes[0].lines) == 1 assert len(axes[1].lines) == 1 - self._check_visible(axes[0].get_yticklabels(), visible=True) + _check_visible(axes[0].get_yticklabels(), visible=True) # yaxis of axes1 (right) are hidden - self._check_visible(axes[1].get_yticklabels(), visible=False) + _check_visible(axes[1].get_yticklabels(), visible=False) for ax in [ax1, ax2]: # xaxis are visible because there is only one column - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() # boxed @@ -1898,9 +1908,9 @@ def _get_boxed_grid(): for ax in axes: assert len(ax.lines) == 1 # axis are visible because these are not shared - self._check_visible(ax.get_yticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() # subplots / sharex=True / sharey=True @@ -1910,20 +1920,20 @@ def _get_boxed_grid(): for ax in axes: assert len(ax.lines) == 1 for ax in [axes[0], axes[2]]: # left column - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) for ax in [axes[1], axes[3]]: # right column - self._check_visible(ax.get_yticklabels(), visible=False) + _check_visible(ax.get_yticklabels(), visible=False) for ax in [axes[0], axes[1]]: # top row - self._check_visible(ax.get_xticklabels(), visible=False) - self._check_visible(ax.get_xticklabels(minor=True), visible=False) + _check_visible(ax.get_xticklabels(), visible=False) + _check_visible(ax.get_xticklabels(minor=True), visible=False) for ax in [axes[2], axes[3]]: # bottom row - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() def test_df_grid_settings(self): # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792 - self._check_grid_settings( + _check_grid_settings( DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}), plotting.PlotAccessor._dataframe_kinds, kws={"x": "a", "y": "b"}, @@ -1932,19 +1942,19 @@ def test_df_grid_settings(self): def test_plain_axes(self): # supplied ax itself is a SubplotAxes, but figure contains also # a plain Axes object (GH11556) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() fig.add_axes([0.2, 0.2, 0.2, 0.2]) Series(np.random.rand(10)).plot(ax=ax) # supplied ax itself is a plain Axes, but because the cmap keyword # a new ax is created for the colorbar -> also multiples axes (GH11520) df = DataFrame({"a": np.random.randn(8), "b": np.random.randn(8)}) - fig = self.plt.figure() + fig = mpl.pyplot.figure() ax = fig.add_axes((0, 0, 1, 1)) df.plot(kind="scatter", ax=ax, x="a", y="b", c="a", cmap="hsv") # other examples - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) @@ -1952,7 +1962,7 @@ def test_plain_axes(self): Series(np.random.rand(10)).plot(ax=ax) Series(np.random.rand(10)).plot(ax=cax) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() from mpl_toolkits.axes_grid1.inset_locator import inset_axes iax = inset_axes(ax, width="30%", height=1.0, loc=3) @@ -1973,7 +1983,7 @@ def test_secondary_axis_font_size(self, method): kwargs = {"secondary_y": sy, "fontsize": fontsize, "mark_right": True} ax = getattr(df.plot, method)(**kwargs) - self._check_ticks_props(axes=ax.right_ax, ylabelsize=fontsize) + _check_ticks_props(axes=ax.right_ax, ylabelsize=fontsize) def test_x_string_values_ticks(self): # Test if string plot index have a fixed xtick position @@ -2022,7 +2032,7 @@ def test_xlim_plot_line(self, kind): def test_xlim_plot_line_correctly_in_mixed_plot_type(self): # test if xlim is set correctly when ax contains multiple different kinds # of plots, GH 27686 - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() indexes = ["k1", "k2", "k3", "k4"] df = DataFrame( @@ -2080,7 +2090,7 @@ def test_group_subplot(self, kind): expected_labels = (["b", "e"], ["c", "d"], ["a"]) for ax, labels in zip(axes, expected_labels): if kind != "pie": - self._check_legend_labels(ax, labels=labels) + _check_legend_labels(ax, labels=labels) if kind == "line": assert len(ax.lines) == len(labels) diff --git a/pandas/tests/plotting/frame/test_frame_color.py b/pandas/tests/plotting/frame/test_frame_color.py index b9e24ff52070e..e7370375ba27b 100644 --- a/pandas/tests/plotting/frame/test_frame_color.py +++ b/pandas/tests/plotting/frame/test_frame_color.py @@ -10,14 +10,16 @@ from pandas import DataFrame import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_colors, _check_plot_works, + _unpack_cycler, ) from pandas.util.version import Version +mpl = pytest.importorskip("matplotlib") -@td.skip_if_no_mpl -class TestDataFrameColor(TestPlotBase): + +class TestDataFrameColor: @pytest.mark.parametrize( "color", ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"] ) @@ -84,16 +86,16 @@ def test_color_and_marker(self, color, expected): def test_bar_colors(self): import matplotlib.pyplot as plt - default_colors = self._unpack_cycler(plt.rcParams) + default_colors = _unpack_cycler(plt.rcParams) df = DataFrame(np.random.randn(5, 5)) ax = df.plot.bar() - self._check_colors(ax.patches[::5], facecolors=default_colors[:5]) + _check_colors(ax.patches[::5], facecolors=default_colors[:5]) tm.close() custom_colors = "rgcby" ax = df.plot.bar(color=custom_colors) - self._check_colors(ax.patches[::5], facecolors=custom_colors) + _check_colors(ax.patches[::5], facecolors=custom_colors) tm.close() from matplotlib import cm @@ -101,21 +103,21 @@ def test_bar_colors(self): # Test str -> colormap functionality ax = df.plot.bar(colormap="jet") rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)] - self._check_colors(ax.patches[::5], facecolors=rgba_colors) + _check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() # Test colormap functionality ax = df.plot.bar(colormap=cm.jet) rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)] - self._check_colors(ax.patches[::5], facecolors=rgba_colors) + _check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() ax = df.loc[:, [0]].plot.bar(color="DodgerBlue") - self._check_colors([ax.patches[0]], facecolors=["DodgerBlue"]) + _check_colors([ax.patches[0]], facecolors=["DodgerBlue"]) tm.close() ax = df.plot(kind="bar", color="green") - self._check_colors(ax.patches[::5], facecolors=["green"] * 5) + _check_colors(ax.patches[::5], facecolors=["green"] * 5) tm.close() def test_bar_user_colors(self): @@ -206,12 +208,12 @@ def test_scatter_colors(self): with pytest.raises(TypeError, match="Specify exactly one of `c` and `color`"): df.plot.scatter(x="a", y="b", c="c", color="green") - default_colors = self._unpack_cycler(self.plt.rcParams) + default_colors = _unpack_cycler(mpl.pyplot.rcParams) ax = df.plot.scatter(x="a", y="b", c="c") tm.assert_numpy_array_equal( ax.collections[0].get_facecolor()[0], - np.array(self.colorconverter.to_rgba(default_colors[0])), + np.array(mpl.colors.ColorConverter.to_rgba(default_colors[0])), ) ax = df.plot.scatter(x="a", y="b", color="white") @@ -241,7 +243,7 @@ def test_line_colors(self): df = DataFrame(np.random.randn(5, 5)) ax = df.plot(color=custom_colors) - self._check_colors(ax.get_lines(), linecolors=custom_colors) + _check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() @@ -255,27 +257,27 @@ def test_line_colors(self): ax = df.plot(colormap="jet") rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] - self._check_colors(ax.get_lines(), linecolors=rgba_colors) + _check_colors(ax.get_lines(), linecolors=rgba_colors) tm.close() ax = df.plot(colormap=cm.jet) rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] - self._check_colors(ax.get_lines(), linecolors=rgba_colors) + _check_colors(ax.get_lines(), linecolors=rgba_colors) tm.close() # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') ax = df.loc[:, [0]].plot(color="DodgerBlue") - self._check_colors(ax.lines, linecolors=["DodgerBlue"]) + _check_colors(ax.lines, linecolors=["DodgerBlue"]) ax = df.plot(color="red") - self._check_colors(ax.get_lines(), linecolors=["red"] * 5) + _check_colors(ax.get_lines(), linecolors=["red"] * 5) tm.close() # GH 10299 custom_colors = ["#FF0000", "#0000FF", "#FFFF00", "#000000", "#FFFFFF"] ax = df.plot(color=custom_colors) - self._check_colors(ax.get_lines(), linecolors=custom_colors) + _check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() def test_dont_modify_colors(self): @@ -287,68 +289,68 @@ def test_line_colors_and_styles_subplots(self): # GH 9894 from matplotlib import cm - default_colors = self._unpack_cycler(self.plt.rcParams) + default_colors = _unpack_cycler(mpl.pyplot.rcParams) df = DataFrame(np.random.randn(5, 5)) axes = df.plot(subplots=True) for ax, c in zip(axes, list(default_colors)): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() # single color char axes = df.plot(subplots=True, color="k") for ax in axes: - self._check_colors(ax.get_lines(), linecolors=["k"]) + _check_colors(ax.get_lines(), linecolors=["k"]) tm.close() # single color str axes = df.plot(subplots=True, color="green") for ax in axes: - self._check_colors(ax.get_lines(), linecolors=["green"]) + _check_colors(ax.get_lines(), linecolors=["green"]) tm.close() custom_colors = "rgcby" axes = df.plot(color=custom_colors, subplots=True) for ax, c in zip(axes, list(custom_colors)): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() axes = df.plot(color=list(custom_colors), subplots=True) for ax, c in zip(axes, list(custom_colors)): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() # GH 10299 custom_colors = ["#FF0000", "#0000FF", "#FFFF00", "#000000", "#FFFFFF"] axes = df.plot(color=custom_colors, subplots=True) for ax, c in zip(axes, list(custom_colors)): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] for cmap in ["jet", cm.jet]: axes = df.plot(colormap=cmap, subplots=True) for ax, c in zip(axes, rgba_colors): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') axes = df.loc[:, [0]].plot(color="DodgerBlue", subplots=True) - self._check_colors(axes[0].lines, linecolors=["DodgerBlue"]) + _check_colors(axes[0].lines, linecolors=["DodgerBlue"]) # single character style axes = df.plot(style="r", subplots=True) for ax in axes: - self._check_colors(ax.get_lines(), linecolors=["r"]) + _check_colors(ax.get_lines(), linecolors=["r"]) tm.close() # list of styles styles = list("rgcby") axes = df.plot(style=styles, subplots=True) for ax, c in zip(axes, styles): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() def test_area_colors(self): @@ -359,12 +361,12 @@ def test_area_colors(self): df = DataFrame(np.random.rand(5, 5)) ax = df.plot.area(color=custom_colors) - self._check_colors(ax.get_lines(), linecolors=custom_colors) + _check_colors(ax.get_lines(), linecolors=custom_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] - self._check_colors(poly, facecolors=custom_colors) + _check_colors(poly, facecolors=custom_colors) handles, labels = ax.get_legend_handles_labels() - self._check_colors(handles, facecolors=custom_colors) + _check_colors(handles, facecolors=custom_colors) for h in handles: assert h.get_alpha() is None @@ -372,40 +374,40 @@ def test_area_colors(self): ax = df.plot.area(colormap="jet") jet_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] - self._check_colors(ax.get_lines(), linecolors=jet_colors) + _check_colors(ax.get_lines(), linecolors=jet_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] - self._check_colors(poly, facecolors=jet_colors) + _check_colors(poly, facecolors=jet_colors) handles, labels = ax.get_legend_handles_labels() - self._check_colors(handles, facecolors=jet_colors) + _check_colors(handles, facecolors=jet_colors) for h in handles: assert h.get_alpha() is None tm.close() # When stacked=False, alpha is set to 0.5 ax = df.plot.area(colormap=cm.jet, stacked=False) - self._check_colors(ax.get_lines(), linecolors=jet_colors) + _check_colors(ax.get_lines(), linecolors=jet_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] jet_with_alpha = [(c[0], c[1], c[2], 0.5) for c in jet_colors] - self._check_colors(poly, facecolors=jet_with_alpha) + _check_colors(poly, facecolors=jet_with_alpha) handles, labels = ax.get_legend_handles_labels() linecolors = jet_with_alpha - self._check_colors(handles[: len(jet_colors)], linecolors=linecolors) + _check_colors(handles[: len(jet_colors)], linecolors=linecolors) for h in handles: assert h.get_alpha() == 0.5 def test_hist_colors(self): - default_colors = self._unpack_cycler(self.plt.rcParams) + default_colors = _unpack_cycler(mpl.pyplot.rcParams) df = DataFrame(np.random.randn(5, 5)) ax = df.plot.hist() - self._check_colors(ax.patches[::10], facecolors=default_colors[:5]) + _check_colors(ax.patches[::10], facecolors=default_colors[:5]) tm.close() custom_colors = "rgcby" ax = df.plot.hist(color=custom_colors) - self._check_colors(ax.patches[::10], facecolors=custom_colors) + _check_colors(ax.patches[::10], facecolors=custom_colors) tm.close() from matplotlib import cm @@ -413,20 +415,20 @@ def test_hist_colors(self): # Test str -> colormap functionality ax = df.plot.hist(colormap="jet") rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)] - self._check_colors(ax.patches[::10], facecolors=rgba_colors) + _check_colors(ax.patches[::10], facecolors=rgba_colors) tm.close() # Test colormap functionality ax = df.plot.hist(colormap=cm.jet) rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)] - self._check_colors(ax.patches[::10], facecolors=rgba_colors) + _check_colors(ax.patches[::10], facecolors=rgba_colors) tm.close() ax = df.loc[:, [0]].plot.hist(color="DodgerBlue") - self._check_colors([ax.patches[0]], facecolors=["DodgerBlue"]) + _check_colors([ax.patches[0]], facecolors=["DodgerBlue"]) ax = df.plot(kind="hist", color="green") - self._check_colors(ax.patches[::10], facecolors=["green"] * 5) + _check_colors(ax.patches[::10], facecolors=["green"] * 5) tm.close() @td.skip_if_no_scipy @@ -437,94 +439,92 @@ def test_kde_colors(self): df = DataFrame(np.random.rand(5, 5)) ax = df.plot.kde(color=custom_colors) - self._check_colors(ax.get_lines(), linecolors=custom_colors) + _check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() ax = df.plot.kde(colormap="jet") rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] - self._check_colors(ax.get_lines(), linecolors=rgba_colors) + _check_colors(ax.get_lines(), linecolors=rgba_colors) tm.close() ax = df.plot.kde(colormap=cm.jet) rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] - self._check_colors(ax.get_lines(), linecolors=rgba_colors) + _check_colors(ax.get_lines(), linecolors=rgba_colors) @td.skip_if_no_scipy def test_kde_colors_and_styles_subplots(self): from matplotlib import cm - default_colors = self._unpack_cycler(self.plt.rcParams) + default_colors = _unpack_cycler(mpl.pyplot.rcParams) df = DataFrame(np.random.randn(5, 5)) axes = df.plot(kind="kde", subplots=True) for ax, c in zip(axes, list(default_colors)): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() # single color char axes = df.plot(kind="kde", color="k", subplots=True) for ax in axes: - self._check_colors(ax.get_lines(), linecolors=["k"]) + _check_colors(ax.get_lines(), linecolors=["k"]) tm.close() # single color str axes = df.plot(kind="kde", color="red", subplots=True) for ax in axes: - self._check_colors(ax.get_lines(), linecolors=["red"]) + _check_colors(ax.get_lines(), linecolors=["red"]) tm.close() custom_colors = "rgcby" axes = df.plot(kind="kde", color=custom_colors, subplots=True) for ax, c in zip(axes, list(custom_colors)): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] for cmap in ["jet", cm.jet]: axes = df.plot(kind="kde", colormap=cmap, subplots=True) for ax, c in zip(axes, rgba_colors): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') axes = df.loc[:, [0]].plot(kind="kde", color="DodgerBlue", subplots=True) - self._check_colors(axes[0].lines, linecolors=["DodgerBlue"]) + _check_colors(axes[0].lines, linecolors=["DodgerBlue"]) # single character style axes = df.plot(kind="kde", style="r", subplots=True) for ax in axes: - self._check_colors(ax.get_lines(), linecolors=["r"]) + _check_colors(ax.get_lines(), linecolors=["r"]) tm.close() # list of styles styles = list("rgcby") axes = df.plot(kind="kde", style=styles, subplots=True) for ax, c in zip(axes, styles): - self._check_colors(ax.get_lines(), linecolors=[c]) + _check_colors(ax.get_lines(), linecolors=[c]) tm.close() def test_boxplot_colors(self): - def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None): + def _check_colors_box( + bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None + ): # TODO: outside this func? if fliers_c is None: fliers_c = "k" - self._check_colors(bp["boxes"], linecolors=[box_c] * len(bp["boxes"])) - self._check_colors( - bp["whiskers"], linecolors=[whiskers_c] * len(bp["whiskers"]) - ) - self._check_colors( - bp["medians"], linecolors=[medians_c] * len(bp["medians"]) - ) - self._check_colors(bp["fliers"], linecolors=[fliers_c] * len(bp["fliers"])) - self._check_colors(bp["caps"], linecolors=[caps_c] * len(bp["caps"])) - - default_colors = self._unpack_cycler(self.plt.rcParams) + _check_colors(bp["boxes"], linecolors=[box_c] * len(bp["boxes"])) + _check_colors(bp["whiskers"], linecolors=[whiskers_c] * len(bp["whiskers"])) + _check_colors(bp["medians"], linecolors=[medians_c] * len(bp["medians"])) + _check_colors(bp["fliers"], linecolors=[fliers_c] * len(bp["fliers"])) + _check_colors(bp["caps"], linecolors=[caps_c] * len(bp["caps"])) + + default_colors = _unpack_cycler(mpl.pyplot.rcParams) df = DataFrame(np.random.randn(5, 5)) bp = df.plot.box(return_type="dict") - _check_colors( + _check_colors_box( bp, default_colors[0], default_colors[0], @@ -540,7 +540,7 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None): "caps": "#123456", } bp = df.plot.box(color=dict_colors, sym="r+", return_type="dict") - _check_colors( + _check_colors_box( bp, dict_colors["boxes"], dict_colors["whiskers"], @@ -553,7 +553,7 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None): # partial colors dict_colors = {"whiskers": "c", "medians": "m"} bp = df.plot.box(color=dict_colors, return_type="dict") - _check_colors(bp, default_colors[0], "c", "m", default_colors[0]) + _check_colors_box(bp, default_colors[0], "c", "m", default_colors[0]) tm.close() from matplotlib import cm @@ -561,21 +561,25 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None): # Test str -> colormap functionality bp = df.plot.box(colormap="jet", return_type="dict") jet_colors = [cm.jet(n) for n in np.linspace(0, 1, 3)] - _check_colors(bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0]) + _check_colors_box( + bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0] + ) tm.close() # Test colormap functionality bp = df.plot.box(colormap=cm.jet, return_type="dict") - _check_colors(bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0]) + _check_colors_box( + bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0] + ) tm.close() # string color is applied to all artists except fliers bp = df.plot.box(color="DodgerBlue", return_type="dict") - _check_colors(bp, "DodgerBlue", "DodgerBlue", "DodgerBlue", "DodgerBlue") + _check_colors_box(bp, "DodgerBlue", "DodgerBlue", "DodgerBlue", "DodgerBlue") # tuple is also applied to all artists except fliers bp = df.plot.box(color=(0, 1, 0), sym="#123456", return_type="dict") - _check_colors(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), "#123456") + _check_colors_box(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), "#123456") msg = re.escape( "color dict contains invalid key 'xxxx'. The key must be either " @@ -595,8 +599,8 @@ def test_default_color_cycle(self): df = DataFrame(np.random.randn(5, 3)) ax = df.plot() - expected = self._unpack_cycler(plt.rcParams)[:3] - self._check_colors(ax.get_lines(), linecolors=expected) + expected = _unpack_cycler(plt.rcParams)[:3] + _check_colors(ax.get_lines(), linecolors=expected) def test_no_color_bar(self): df = DataFrame( @@ -664,5 +668,5 @@ def test_dataframe_none_color(self): # GH51953 df = DataFrame([[1, 2, 3]]) ax = df.plot(color=None) - expected = self._unpack_cycler(self.plt.rcParams)[:3] - self._check_colors(ax.get_lines(), linecolors=expected) + expected = _unpack_cycler(mpl.pyplot.rcParams)[:3] + _check_colors(ax.get_lines(), linecolors=expected) diff --git a/pandas/tests/plotting/frame/test_frame_groupby.py b/pandas/tests/plotting/frame/test_frame_groupby.py index 9c148645966ad..f1924185a3df1 100644 --- a/pandas/tests/plotting/frame/test_frame_groupby.py +++ b/pandas/tests/plotting/frame/test_frame_groupby.py @@ -2,21 +2,20 @@ import pytest -import pandas.util._test_decorators as td - from pandas import DataFrame -from pandas.tests.plotting.common import TestPlotBase +from pandas.tests.plotting.common import _check_visible + +pytest.importorskip("matplotlib") -@td.skip_if_no_mpl -class TestDataFramePlotsGroupby(TestPlotBase): +class TestDataFramePlotsGroupby: def _assert_ytickslabels_visibility(self, axes, expected): for ax, exp in zip(axes, expected): - self._check_visible(ax.get_yticklabels(), visible=exp) + _check_visible(ax.get_yticklabels(), visible=exp) def _assert_xtickslabels_visibility(self, axes, expected): for ax, exp in zip(axes, expected): - self._check_visible(ax.get_xticklabels(), visible=exp) + _check_visible(ax.get_xticklabels(), visible=exp) @pytest.mark.parametrize( "kwargs, expected", diff --git a/pandas/tests/plotting/frame/test_frame_legend.py b/pandas/tests/plotting/frame/test_frame_legend.py index bad42ebc85cc8..5914300b00434 100644 --- a/pandas/tests/plotting/frame/test_frame_legend.py +++ b/pandas/tests/plotting/frame/test_frame_legend.py @@ -7,11 +7,17 @@ DataFrame, date_range, ) -from pandas.tests.plotting.common import TestPlotBase +from pandas.tests.plotting.common import ( + _check_legend_labels, + _check_legend_marker, + _check_text_labels, +) from pandas.util.version import Version +mpl = pytest.importorskip("matplotlib") + -class TestFrameLegend(TestPlotBase): +class TestFrameLegend: @pytest.mark.xfail( reason=( "Open bug in matplotlib " @@ -66,27 +72,25 @@ def test_df_legend_labels(self): for kind in kinds: ax = df.plot(kind=kind, legend=True) - self._check_legend_labels(ax, labels=df.columns) + _check_legend_labels(ax, labels=df.columns) ax = df2.plot(kind=kind, legend=False, ax=ax) - self._check_legend_labels(ax, labels=df.columns) + _check_legend_labels(ax, labels=df.columns) ax = df3.plot(kind=kind, legend=True, ax=ax) - self._check_legend_labels(ax, labels=df.columns.union(df3.columns)) + _check_legend_labels(ax, labels=df.columns.union(df3.columns)) ax = df4.plot(kind=kind, legend="reverse", ax=ax) expected = list(df.columns.union(df3.columns)) + list(reversed(df4.columns)) - self._check_legend_labels(ax, labels=expected) + _check_legend_labels(ax, labels=expected) # Secondary Y ax = df.plot(legend=True, secondary_y="b") - self._check_legend_labels(ax, labels=["a", "b (right)", "c"]) + _check_legend_labels(ax, labels=["a", "b (right)", "c"]) ax = df2.plot(legend=False, ax=ax) - self._check_legend_labels(ax, labels=["a", "b (right)", "c"]) + _check_legend_labels(ax, labels=["a", "b (right)", "c"]) ax = df3.plot(kind="bar", legend=True, secondary_y="h", ax=ax) - self._check_legend_labels( - ax, labels=["a", "b (right)", "c", "g", "h (right)", "i"] - ) + _check_legend_labels(ax, labels=["a", "b (right)", "c", "g", "h (right)", "i"]) # Time Series ind = date_range("1/1/2014", periods=3) @@ -94,55 +98,55 @@ def test_df_legend_labels(self): df2 = DataFrame(np.random.randn(3, 3), columns=["d", "e", "f"], index=ind) df3 = DataFrame(np.random.randn(3, 3), columns=["g", "h", "i"], index=ind) ax = df.plot(legend=True, secondary_y="b") - self._check_legend_labels(ax, labels=["a", "b (right)", "c"]) + _check_legend_labels(ax, labels=["a", "b (right)", "c"]) ax = df2.plot(legend=False, ax=ax) - self._check_legend_labels(ax, labels=["a", "b (right)", "c"]) + _check_legend_labels(ax, labels=["a", "b (right)", "c"]) ax = df3.plot(legend=True, ax=ax) - self._check_legend_labels(ax, labels=["a", "b (right)", "c", "g", "h", "i"]) + _check_legend_labels(ax, labels=["a", "b (right)", "c", "g", "h", "i"]) # scatter ax = df.plot.scatter(x="a", y="b", label="data1") - self._check_legend_labels(ax, labels=["data1"]) + _check_legend_labels(ax, labels=["data1"]) ax = df2.plot.scatter(x="d", y="e", legend=False, label="data2", ax=ax) - self._check_legend_labels(ax, labels=["data1"]) + _check_legend_labels(ax, labels=["data1"]) ax = df3.plot.scatter(x="g", y="h", label="data3", ax=ax) - self._check_legend_labels(ax, labels=["data1", "data3"]) + _check_legend_labels(ax, labels=["data1", "data3"]) # ensure label args pass through and # index name does not mutate # column names don't mutate df5 = df.set_index("a") ax = df5.plot(y="b") - self._check_legend_labels(ax, labels=["b"]) + _check_legend_labels(ax, labels=["b"]) ax = df5.plot(y="b", label="LABEL_b") - self._check_legend_labels(ax, labels=["LABEL_b"]) - self._check_text_labels(ax.xaxis.get_label(), "a") + _check_legend_labels(ax, labels=["LABEL_b"]) + _check_text_labels(ax.xaxis.get_label(), "a") ax = df5.plot(y="c", label="LABEL_c", ax=ax) - self._check_legend_labels(ax, labels=["LABEL_b", "LABEL_c"]) + _check_legend_labels(ax, labels=["LABEL_b", "LABEL_c"]) assert df5.columns.tolist() == ["b", "c"] def test_missing_marker_multi_plots_on_same_ax(self): # GH 18222 df = DataFrame(data=[[1, 1, 1, 1], [2, 2, 4, 8]], columns=["x", "r", "g", "b"]) - fig, ax = self.plt.subplots(nrows=1, ncols=3) + fig, ax = mpl.pyplot.subplots(nrows=1, ncols=3) # Left plot df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[0]) df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[0]) df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[0]) - self._check_legend_labels(ax[0], labels=["r", "g", "b"]) - self._check_legend_marker(ax[0], expected_markers=["o", "x", "o"]) + _check_legend_labels(ax[0], labels=["r", "g", "b"]) + _check_legend_marker(ax[0], expected_markers=["o", "x", "o"]) # Center plot df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[1]) df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[1]) df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[1]) - self._check_legend_labels(ax[1], labels=["b", "r", "g"]) - self._check_legend_marker(ax[1], expected_markers=["o", "o", "x"]) + _check_legend_labels(ax[1], labels=["b", "r", "g"]) + _check_legend_marker(ax[1], expected_markers=["o", "o", "x"]) # Right plot df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[2]) df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[2]) df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[2]) - self._check_legend_labels(ax[2], labels=["g", "b", "r"]) - self._check_legend_marker(ax[2], expected_markers=["x", "o", "o"]) + _check_legend_labels(ax[2], labels=["g", "b", "r"]) + _check_legend_marker(ax[2], expected_markers=["x", "o", "o"]) def test_legend_name(self): multi = DataFrame( @@ -153,21 +157,21 @@ def test_legend_name(self): ax = multi.plot() leg_title = ax.legend_.get_title() - self._check_text_labels(leg_title, "group,individual") + _check_text_labels(leg_title, "group,individual") df = DataFrame(np.random.randn(5, 5)) ax = df.plot(legend=True, ax=ax) leg_title = ax.legend_.get_title() - self._check_text_labels(leg_title, "group,individual") + _check_text_labels(leg_title, "group,individual") df.columns.name = "new" ax = df.plot(legend=False, ax=ax) leg_title = ax.legend_.get_title() - self._check_text_labels(leg_title, "group,individual") + _check_text_labels(leg_title, "group,individual") ax = df.plot(legend=True, ax=ax) leg_title = ax.legend_.get_title() - self._check_text_labels(leg_title, "new") + _check_text_labels(leg_title, "new") @pytest.mark.parametrize( "kind", @@ -183,7 +187,7 @@ def test_legend_name(self): def test_no_legend(self, kind): df = DataFrame(np.random.rand(3, 3), columns=["a", "b", "c"]) ax = df.plot(kind=kind, legend=False) - self._check_legend_labels(ax, visible=False) + _check_legend_labels(ax, visible=False) def test_missing_markers_legend(self): # 14958 @@ -192,8 +196,8 @@ def test_missing_markers_legend(self): df.plot(y=["B"], marker="o", linestyle="dotted", ax=ax) df.plot(y=["C"], marker="<", linestyle="dotted", ax=ax) - self._check_legend_labels(ax, labels=["A", "B", "C"]) - self._check_legend_marker(ax, expected_markers=["x", "o", "<"]) + _check_legend_labels(ax, labels=["A", "B", "C"]) + _check_legend_marker(ax, expected_markers=["x", "o", "<"]) def test_missing_markers_legend_using_style(self): # 14563 @@ -206,9 +210,9 @@ def test_missing_markers_legend_using_style(self): } ) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() for kind in "ABC": df.plot("X", kind, label=kind, ax=ax, style=".") - self._check_legend_labels(ax, labels=["A", "B", "C"]) - self._check_legend_marker(ax, expected_markers=[".", ".", "."]) + _check_legend_labels(ax, labels=["A", "B", "C"]) + _check_legend_marker(ax, expected_markers=[".", ".", "."]) diff --git a/pandas/tests/plotting/frame/test_frame_subplots.py b/pandas/tests/plotting/frame/test_frame_subplots.py index 4f55f9504f0db..336fed6293070 100644 --- a/pandas/tests/plotting/frame/test_frame_subplots.py +++ b/pandas/tests/plotting/frame/test_frame_subplots.py @@ -8,7 +8,6 @@ from pandas.compat import is_platform_linux from pandas.compat.numpy import np_version_gte1p24 -import pandas.util._test_decorators as td import pandas as pd from pandas import ( @@ -17,47 +16,55 @@ date_range, ) import pandas._testing as tm -from pandas.tests.plotting.common import TestPlotBase +from pandas.tests.plotting.common import ( + _check_axes_shape, + _check_box_return_type, + _check_legend_labels, + _check_ticks_props, + _check_visible, + _flatten_visible, +) from pandas.io.formats.printing import pprint_thing +mpl = pytest.importorskip("matplotlib") + -@td.skip_if_no_mpl -class TestDataFramePlotsSubplots(TestPlotBase): +class TestDataFramePlotsSubplots: @pytest.mark.slow def test_subplots(self): df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10])) for kind in ["bar", "barh", "line", "area"]: axes = df.plot(kind=kind, subplots=True, sharex=True, legend=True) - self._check_axes_shape(axes, axes_num=3, layout=(3, 1)) + _check_axes_shape(axes, axes_num=3, layout=(3, 1)) assert axes.shape == (3,) for ax, column in zip(axes, df.columns): - self._check_legend_labels(ax, labels=[pprint_thing(column)]) + _check_legend_labels(ax, labels=[pprint_thing(column)]) for ax in axes[:-2]: - self._check_visible(ax.xaxis) # xaxis must be visible for grid - self._check_visible(ax.get_xticklabels(), visible=False) + _check_visible(ax.xaxis) # xaxis must be visible for grid + _check_visible(ax.get_xticklabels(), visible=False) if kind != "bar": # change https://github.com/pandas-dev/pandas/issues/26714 - self._check_visible(ax.get_xticklabels(minor=True), visible=False) - self._check_visible(ax.xaxis.get_label(), visible=False) - self._check_visible(ax.get_yticklabels()) + _check_visible(ax.get_xticklabels(minor=True), visible=False) + _check_visible(ax.xaxis.get_label(), visible=False) + _check_visible(ax.get_yticklabels()) - self._check_visible(axes[-1].xaxis) - self._check_visible(axes[-1].get_xticklabels()) - self._check_visible(axes[-1].get_xticklabels(minor=True)) - self._check_visible(axes[-1].xaxis.get_label()) - self._check_visible(axes[-1].get_yticklabels()) + _check_visible(axes[-1].xaxis) + _check_visible(axes[-1].get_xticklabels()) + _check_visible(axes[-1].get_xticklabels(minor=True)) + _check_visible(axes[-1].xaxis.get_label()) + _check_visible(axes[-1].get_yticklabels()) axes = df.plot(kind=kind, subplots=True, sharex=False) for ax in axes: - self._check_visible(ax.xaxis) - self._check_visible(ax.get_xticklabels()) - self._check_visible(ax.get_xticklabels(minor=True)) - self._check_visible(ax.xaxis.get_label()) - self._check_visible(ax.get_yticklabels()) + _check_visible(ax.xaxis) + _check_visible(ax.get_xticklabels()) + _check_visible(ax.get_xticklabels(minor=True)) + _check_visible(ax.xaxis.get_label()) + _check_visible(ax.get_yticklabels()) axes = df.plot(kind=kind, subplots=True, legend=False) for ax in axes: @@ -69,31 +76,31 @@ def test_subplots_timeseries(self): for kind in ["line", "area"]: axes = df.plot(kind=kind, subplots=True, sharex=True) - self._check_axes_shape(axes, axes_num=3, layout=(3, 1)) + _check_axes_shape(axes, axes_num=3, layout=(3, 1)) for ax in axes[:-2]: # GH 7801 - self._check_visible(ax.xaxis) # xaxis must be visible for grid - self._check_visible(ax.get_xticklabels(), visible=False) - self._check_visible(ax.get_xticklabels(minor=True), visible=False) - self._check_visible(ax.xaxis.get_label(), visible=False) - self._check_visible(ax.get_yticklabels()) - - self._check_visible(axes[-1].xaxis) - self._check_visible(axes[-1].get_xticklabels()) - self._check_visible(axes[-1].get_xticklabels(minor=True)) - self._check_visible(axes[-1].xaxis.get_label()) - self._check_visible(axes[-1].get_yticklabels()) - self._check_ticks_props(axes, xrot=0) + _check_visible(ax.xaxis) # xaxis must be visible for grid + _check_visible(ax.get_xticklabels(), visible=False) + _check_visible(ax.get_xticklabels(minor=True), visible=False) + _check_visible(ax.xaxis.get_label(), visible=False) + _check_visible(ax.get_yticklabels()) + + _check_visible(axes[-1].xaxis) + _check_visible(axes[-1].get_xticklabels()) + _check_visible(axes[-1].get_xticklabels(minor=True)) + _check_visible(axes[-1].xaxis.get_label()) + _check_visible(axes[-1].get_yticklabels()) + _check_ticks_props(axes, xrot=0) axes = df.plot(kind=kind, subplots=True, sharex=False, rot=45, fontsize=7) for ax in axes: - self._check_visible(ax.xaxis) - self._check_visible(ax.get_xticklabels()) - self._check_visible(ax.get_xticklabels(minor=True)) - self._check_visible(ax.xaxis.get_label()) - self._check_visible(ax.get_yticklabels()) - self._check_ticks_props(ax, xlabelsize=7, xrot=45, ylabelsize=7) + _check_visible(ax.xaxis) + _check_visible(ax.get_xticklabels()) + _check_visible(ax.get_xticklabels(minor=True)) + _check_visible(ax.xaxis.get_label()) + _check_visible(ax.get_yticklabels()) + _check_ticks_props(ax, xlabelsize=7, xrot=45, ylabelsize=7) def test_subplots_timeseries_y_axis(self): # GH16953 @@ -185,27 +192,27 @@ def test_subplots_layout_multi_column(self): df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10])) axes = df.plot(subplots=True, layout=(2, 2)) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) assert axes.shape == (2, 2) axes = df.plot(subplots=True, layout=(-1, 2)) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) assert axes.shape == (2, 2) axes = df.plot(subplots=True, layout=(2, -1)) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) assert axes.shape == (2, 2) axes = df.plot(subplots=True, layout=(1, 4)) - self._check_axes_shape(axes, axes_num=3, layout=(1, 4)) + _check_axes_shape(axes, axes_num=3, layout=(1, 4)) assert axes.shape == (1, 4) axes = df.plot(subplots=True, layout=(-1, 4)) - self._check_axes_shape(axes, axes_num=3, layout=(1, 4)) + _check_axes_shape(axes, axes_num=3, layout=(1, 4)) assert axes.shape == (1, 4) axes = df.plot(subplots=True, layout=(4, -1)) - self._check_axes_shape(axes, axes_num=3, layout=(4, 1)) + _check_axes_shape(axes, axes_num=3, layout=(4, 1)) assert axes.shape == (4, 1) msg = "Layout of 1x1 must be larger than required size 3" @@ -230,7 +237,7 @@ def test_subplots_layout_single_column( # GH 6667 df = DataFrame(np.random.rand(10, 1), index=list(string.ascii_letters[:10])) axes = df.plot(subplots=True, **kwargs) - self._check_axes_shape( + _check_axes_shape( axes, axes_num=expected_axes_num, layout=expected_layout, @@ -251,25 +258,25 @@ def test_subplots_warnings(self): def test_subplots_multiple_axes(self): # GH 5353, 6970, GH 7069 - fig, axes = self.plt.subplots(2, 3) + fig, axes = mpl.pyplot.subplots(2, 3) df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10])) returned = df.plot(subplots=True, ax=axes[0], sharex=False, sharey=False) - self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) assert returned.shape == (3,) assert returned[0].figure is fig # draw on second row returned = df.plot(subplots=True, ax=axes[1], sharex=False, sharey=False) - self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) assert returned.shape == (3,) assert returned[0].figure is fig - self._check_axes_shape(axes, axes_num=6, layout=(2, 3)) + _check_axes_shape(axes, axes_num=6, layout=(2, 3)) tm.close() msg = "The number of passed axes must be 3, the same as the output plot" with pytest.raises(ValueError, match=msg): - fig, axes = self.plt.subplots(2, 3) + fig, axes = mpl.pyplot.subplots(2, 3) # pass different number of axes from required df.plot(subplots=True, ax=axes) @@ -277,7 +284,7 @@ def test_subplots_multiple_axes(self): # invalid lauout should not affect to input and return value # (show warning is tested in # TestDataFrameGroupByPlots.test_grouped_box_multiple_axes - fig, axes = self.plt.subplots(2, 2) + fig, axes = mpl.pyplot.subplots(2, 2) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) df = DataFrame(np.random.rand(10, 4), index=list(string.ascii_letters[:10])) @@ -285,33 +292,33 @@ def test_subplots_multiple_axes(self): returned = df.plot( subplots=True, ax=axes, layout=(2, 1), sharex=False, sharey=False ) - self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) + _check_axes_shape(returned, axes_num=4, layout=(2, 2)) assert returned.shape == (4,) returned = df.plot( subplots=True, ax=axes, layout=(2, -1), sharex=False, sharey=False ) - self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) + _check_axes_shape(returned, axes_num=4, layout=(2, 2)) assert returned.shape == (4,) returned = df.plot( subplots=True, ax=axes, layout=(-1, 2), sharex=False, sharey=False ) - self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) + _check_axes_shape(returned, axes_num=4, layout=(2, 2)) assert returned.shape == (4,) # single column - fig, axes = self.plt.subplots(1, 1) + fig, axes = mpl.pyplot.subplots(1, 1) df = DataFrame(np.random.rand(10, 1), index=list(string.ascii_letters[:10])) axes = df.plot(subplots=True, ax=[axes], sharex=False, sharey=False) - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) assert axes.shape == (1,) def test_subplots_ts_share_axes(self): # GH 3964 - fig, axes = self.plt.subplots(3, 3, sharex=True, sharey=True) - self.plt.subplots_adjust(left=0.05, right=0.95, hspace=0.3, wspace=0.3) + fig, axes = mpl.pyplot.subplots(3, 3, sharex=True, sharey=True) + mpl.pyplot.subplots_adjust(left=0.05, right=0.95, hspace=0.3, wspace=0.3) df = DataFrame( np.random.randn(10, 9), index=date_range(start="2014-07-01", freq="M", periods=10), @@ -321,21 +328,21 @@ def test_subplots_ts_share_axes(self): # Rows other than bottom should not be visible for ax in axes[0:-1].ravel(): - self._check_visible(ax.get_xticklabels(), visible=False) + _check_visible(ax.get_xticklabels(), visible=False) # Bottom row should be visible for ax in axes[-1].ravel(): - self._check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) # First column should be visible for ax in axes[[0, 1, 2], [0]].ravel(): - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) # Other columns should not be visible for ax in axes[[0, 1, 2], [1]].ravel(): - self._check_visible(ax.get_yticklabels(), visible=False) + _check_visible(ax.get_yticklabels(), visible=False) for ax in axes[[0, 1, 2], [2]].ravel(): - self._check_visible(ax.get_yticklabels(), visible=False) + _check_visible(ax.get_yticklabels(), visible=False) def test_subplots_sharex_axes_existing_axes(self): # GH 9158 @@ -345,29 +352,29 @@ def test_subplots_sharex_axes_existing_axes(self): axes = df[["A", "B"]].plot(subplots=True) df["C"].plot(ax=axes[0], secondary_y=True) - self._check_visible(axes[0].get_xticklabels(), visible=False) - self._check_visible(axes[1].get_xticklabels(), visible=True) + _check_visible(axes[0].get_xticklabels(), visible=False) + _check_visible(axes[1].get_xticklabels(), visible=True) for ax in axes.ravel(): - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) def test_subplots_dup_columns(self): # GH 10962 df = DataFrame(np.random.rand(5, 5), columns=list("aaaaa")) axes = df.plot(subplots=True) for ax in axes: - self._check_legend_labels(ax, labels=["a"]) + _check_legend_labels(ax, labels=["a"]) assert len(ax.lines) == 1 tm.close() axes = df.plot(subplots=True, secondary_y="a") for ax in axes: # (right) is only attached when subplots=False - self._check_legend_labels(ax, labels=["a"]) + _check_legend_labels(ax, labels=["a"]) assert len(ax.lines) == 1 tm.close() ax = df.plot(secondary_y="a") - self._check_legend_labels(ax, labels=["a (right)"] * 5) + _check_legend_labels(ax, labels=["a (right)"] * 5) assert len(ax.lines) == 0 assert len(ax.right_ax.lines) == 5 @@ -407,13 +414,13 @@ def test_boxplot_subplots_return_type(self, hist_df): # normal style: return_type=None result = df.plot.box(subplots=True) assert isinstance(result, Series) - self._check_box_return_type( + _check_box_return_type( result, None, expected_keys=["height", "weight", "category"] ) for t in ["dict", "axes", "both"]: returned = df.plot.box(return_type=t, subplots=True) - self._check_box_return_type( + _check_box_return_type( returned, t, expected_keys=["height", "weight", "category"], @@ -435,12 +442,12 @@ def test_df_subplots_patterns_minorticks(self): axes = df.plot(subplots=True, ax=axes) for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) # xaxis of 1st ax must be hidden - self._check_visible(axes[0].get_xticklabels(), visible=False) - self._check_visible(axes[0].get_xticklabels(minor=True), visible=False) - self._check_visible(axes[1].get_xticklabels(), visible=True) - self._check_visible(axes[1].get_xticklabels(minor=True), visible=True) + _check_visible(axes[0].get_xticklabels(), visible=False) + _check_visible(axes[0].get_xticklabels(minor=True), visible=False) + _check_visible(axes[1].get_xticklabels(), visible=True) + _check_visible(axes[1].get_xticklabels(minor=True), visible=True) tm.close() fig, axes = plt.subplots(2, 1) @@ -448,12 +455,12 @@ def test_df_subplots_patterns_minorticks(self): axes = df.plot(subplots=True, ax=axes, sharex=True) for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) # xaxis of 1st ax must be hidden - self._check_visible(axes[0].get_xticklabels(), visible=False) - self._check_visible(axes[0].get_xticklabels(minor=True), visible=False) - self._check_visible(axes[1].get_xticklabels(), visible=True) - self._check_visible(axes[1].get_xticklabels(minor=True), visible=True) + _check_visible(axes[0].get_xticklabels(), visible=False) + _check_visible(axes[0].get_xticklabels(minor=True), visible=False) + _check_visible(axes[1].get_xticklabels(), visible=True) + _check_visible(axes[1].get_xticklabels(minor=True), visible=True) tm.close() # not shared @@ -461,9 +468,9 @@ def test_df_subplots_patterns_minorticks(self): axes = df.plot(subplots=True, ax=axes) for ax in axes: assert len(ax.lines) == 1 - self._check_visible(ax.get_yticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(), visible=True) - self._check_visible(ax.get_xticklabels(minor=True), visible=True) + _check_visible(ax.get_yticklabels(), visible=True) + _check_visible(ax.get_xticklabels(), visible=True) + _check_visible(ax.get_xticklabels(minor=True), visible=True) tm.close() def test_subplots_sharex_false(self): @@ -473,7 +480,7 @@ def test_subplots_sharex_false(self): df.iloc[5:, 1] = np.nan df.iloc[:5, 0] = np.nan - figs, axs = self.plt.subplots(2, 1) + figs, axs = mpl.pyplot.subplots(2, 1) df.plot.line(ax=axs, subplots=True, sharex=False) expected_ax1 = np.arange(4.5, 10, 0.5) @@ -487,13 +494,13 @@ def test_subplots_constrained_layout(self): idx = date_range(start="now", periods=10) df = DataFrame(np.random.rand(10, 3), index=idx) kwargs = {} - if hasattr(self.plt.Figure, "get_constrained_layout"): + if hasattr(mpl.pyplot.Figure, "get_constrained_layout"): kwargs["constrained_layout"] = True - fig, axes = self.plt.subplots(2, **kwargs) + fig, axes = mpl.pyplot.subplots(2, **kwargs) with tm.assert_produces_warning(None): df.plot(ax=axes[0]) with tm.ensure_clean(return_filelike=True) as path: - self.plt.savefig(path) + mpl.pyplot.savefig(path) @pytest.mark.parametrize( "index_name, old_label, new_label", @@ -632,7 +639,7 @@ def _check_bar_alignment( grid=True, ) - axes = self._flatten_visible(axes) + axes = _flatten_visible(axes) for ax in axes: if kind == "bar": diff --git a/pandas/tests/plotting/frame/test_hist_box_by.py b/pandas/tests/plotting/frame/test_hist_box_by.py index 999118144b58d..c8b71c04001e5 100644 --- a/pandas/tests/plotting/frame/test_hist_box_by.py +++ b/pandas/tests/plotting/frame/test_hist_box_by.py @@ -3,15 +3,17 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - from pandas import DataFrame import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_axes_shape, _check_plot_works, + get_x_axis, + get_y_axis, ) +pytest.importorskip("matplotlib") + @pytest.fixture def hist_df(): @@ -22,8 +24,7 @@ def hist_df(): return df -@td.skip_if_no_mpl -class TestHistWithBy(TestPlotBase): +class TestHistWithBy: @pytest.mark.slow @pytest.mark.parametrize( "by, column, titles, legends", @@ -172,7 +173,7 @@ def test_hist_plot_layout_with_by(self, by, column, layout, axes_num, hist_df): axes = _check_plot_works( hist_df.plot.hist, column=column, by=by, layout=layout ) - self._check_axes_shape(axes, axes_num=axes_num, layout=layout) + _check_axes_shape(axes, axes_num=axes_num, layout=layout) @pytest.mark.parametrize( "msg, by, layout", @@ -194,16 +195,16 @@ def test_axis_share_x_with_by(self, hist_df): ax1, ax2, ax3 = hist_df.plot.hist(column="A", by="C", sharex=True) # share x - assert self.get_x_axis(ax1).joined(ax1, ax2) - assert self.get_x_axis(ax2).joined(ax1, ax2) - assert self.get_x_axis(ax3).joined(ax1, ax3) - assert self.get_x_axis(ax3).joined(ax2, ax3) + assert get_x_axis(ax1).joined(ax1, ax2) + assert get_x_axis(ax2).joined(ax1, ax2) + assert get_x_axis(ax3).joined(ax1, ax3) + assert get_x_axis(ax3).joined(ax2, ax3) # don't share y - assert not self.get_y_axis(ax1).joined(ax1, ax2) - assert not self.get_y_axis(ax2).joined(ax1, ax2) - assert not self.get_y_axis(ax3).joined(ax1, ax3) - assert not self.get_y_axis(ax3).joined(ax2, ax3) + assert not get_y_axis(ax1).joined(ax1, ax2) + assert not get_y_axis(ax2).joined(ax1, ax2) + assert not get_y_axis(ax3).joined(ax1, ax3) + assert not get_y_axis(ax3).joined(ax2, ax3) @pytest.mark.slow def test_axis_share_y_with_by(self, hist_df): @@ -211,26 +212,25 @@ def test_axis_share_y_with_by(self, hist_df): ax1, ax2, ax3 = hist_df.plot.hist(column="A", by="C", sharey=True) # share y - assert self.get_y_axis(ax1).joined(ax1, ax2) - assert self.get_y_axis(ax2).joined(ax1, ax2) - assert self.get_y_axis(ax3).joined(ax1, ax3) - assert self.get_y_axis(ax3).joined(ax2, ax3) + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) + assert get_y_axis(ax3).joined(ax1, ax3) + assert get_y_axis(ax3).joined(ax2, ax3) # don't share x - assert not self.get_x_axis(ax1).joined(ax1, ax2) - assert not self.get_x_axis(ax2).joined(ax1, ax2) - assert not self.get_x_axis(ax3).joined(ax1, ax3) - assert not self.get_x_axis(ax3).joined(ax2, ax3) + assert not get_x_axis(ax1).joined(ax1, ax2) + assert not get_x_axis(ax2).joined(ax1, ax2) + assert not get_x_axis(ax3).joined(ax1, ax3) + assert not get_x_axis(ax3).joined(ax2, ax3) @pytest.mark.parametrize("figsize", [(12, 8), (20, 10)]) def test_figure_shape_hist_with_by(self, figsize, hist_df): # GH 15079 axes = hist_df.plot.hist(column="A", by="C", figsize=figsize) - self._check_axes_shape(axes, axes_num=3, figsize=figsize) + _check_axes_shape(axes, axes_num=3, figsize=figsize) -@td.skip_if_no_mpl -class TestBoxWithBy(TestPlotBase): +class TestBoxWithBy: @pytest.mark.parametrize( "by, column, titles, xticklabels", [ @@ -360,7 +360,7 @@ def test_box_plot_layout_with_by(self, by, column, layout, axes_num, hist_df): axes = _check_plot_works( hist_df.plot.box, default_axes=True, column=column, by=by, layout=layout ) - self._check_axes_shape(axes, axes_num=axes_num, layout=layout) + _check_axes_shape(axes, axes_num=axes_num, layout=layout) @pytest.mark.parametrize( "msg, by, layout", @@ -380,4 +380,4 @@ def test_box_plot_invalid_layout_with_by_raises(self, msg, by, layout, hist_df): def test_figure_shape_hist_with_by(self, figsize, hist_df): # GH 15079 axes = hist_df.plot.box(column="A", by="C", figsize=figsize) - self._check_axes_shape(axes, axes_num=1, figsize=figsize) + _check_axes_shape(axes, axes_num=1, figsize=figsize) diff --git a/pandas/tests/plotting/test_backend.py b/pandas/tests/plotting/test_backend.py index c087d3be293e7..c0ad8e0c9608d 100644 --- a/pandas/tests/plotting/test_backend.py +++ b/pandas/tests/plotting/test_backend.py @@ -7,8 +7,12 @@ import pandas -dummy_backend = types.ModuleType("pandas_dummy_backend") -setattr(dummy_backend, "plot", lambda *args, **kwargs: "used_dummy") + +@pytest.fixture +def dummy_backend(): + db = types.ModuleType("pandas_dummy_backend") + setattr(db, "plot", lambda *args, **kwargs: "used_dummy") + return db @pytest.fixture @@ -26,7 +30,7 @@ def test_backend_is_not_module(): assert pandas.options.plotting.backend == "matplotlib" -def test_backend_is_correct(monkeypatch, restore_backend): +def test_backend_is_correct(monkeypatch, restore_backend, dummy_backend): monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) pandas.set_option("plotting.backend", "pandas_dummy_backend") @@ -36,7 +40,7 @@ def test_backend_is_correct(monkeypatch, restore_backend): ) -def test_backend_can_be_set_in_plot_call(monkeypatch, restore_backend): +def test_backend_can_be_set_in_plot_call(monkeypatch, restore_backend, dummy_backend): monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) df = pandas.DataFrame([1, 2, 3]) @@ -44,7 +48,7 @@ def test_backend_can_be_set_in_plot_call(monkeypatch, restore_backend): assert df.plot(backend="pandas_dummy_backend") == "used_dummy" -def test_register_entrypoint(restore_backend, tmp_path, monkeypatch): +def test_register_entrypoint(restore_backend, tmp_path, monkeypatch, dummy_backend): monkeypatch.syspath_prepend(tmp_path) monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) @@ -86,7 +90,7 @@ def test_no_matplotlib_ok(): pandas.plotting._core._get_plot_backend("matplotlib") -def test_extra_kinds_ok(monkeypatch, restore_backend): +def test_extra_kinds_ok(monkeypatch, restore_backend, dummy_backend): # https://github.com/pandas-dev/pandas/pull/28647 monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) pandas.set_option("plotting.backend", "pandas_dummy_backend") diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 9bbc8f42b6704..c9531969f9961 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -6,8 +6,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - from pandas import ( DataFrame, MultiIndex, @@ -18,15 +16,19 @@ ) import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_axes_shape, + _check_box_return_type, _check_plot_works, + _check_ticks_props, + _check_visible, ) from pandas.io.formats.printing import pprint_thing +mpl = pytest.importorskip("matplotlib") + -@td.skip_if_no_mpl -class TestDataFramePlots(TestPlotBase): +class TestDataFramePlots: def test_stacked_boxplot_set_axis(self): # GH2980 import matplotlib.pyplot as plt @@ -82,18 +84,18 @@ def test_boxplot_legacy2(self): # When ax is supplied and required number of axes is 1, # passed ax should be used: - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() axes = df.boxplot("Col1", by="X", ax=ax) ax_axes = ax.axes assert ax_axes is axes - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() axes = df.groupby("Y").boxplot(ax=ax, return_type="axes") ax_axes = ax.axes assert ax_axes is axes["A"] # Multiple columns with an ax argument should use same figure - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() with tm.assert_produces_warning(UserWarning): axes = df.boxplot( column=["Col1", "Col2"], by="X", ax=ax, return_type="axes" @@ -102,7 +104,7 @@ def test_boxplot_legacy2(self): # When by is None, check that all relevant lines are present in the # dict - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() d = df.boxplot(ax=ax, return_type="dict") lines = list(itertools.chain.from_iterable(d.values())) assert len(ax.get_lines()) == len(lines) @@ -110,7 +112,7 @@ def test_boxplot_legacy2(self): def test_boxplot_return_type_none(self, hist_df): # GH 12216; return_type=None & by=None -> axes result = hist_df.boxplot() - assert isinstance(result, self.plt.Axes) + assert isinstance(result, mpl.pyplot.Axes) def test_boxplot_return_type_legacy(self): # API change in https://github.com/pandas-dev/pandas/pull/7096 @@ -125,19 +127,19 @@ def test_boxplot_return_type_legacy(self): df.boxplot(return_type="NOT_A_TYPE") result = df.boxplot() - self._check_box_return_type(result, "axes") + _check_box_return_type(result, "axes") with tm.assert_produces_warning(False): result = df.boxplot(return_type="dict") - self._check_box_return_type(result, "dict") + _check_box_return_type(result, "dict") with tm.assert_produces_warning(False): result = df.boxplot(return_type="axes") - self._check_box_return_type(result, "axes") + _check_box_return_type(result, "axes") with tm.assert_produces_warning(False): result = df.boxplot(return_type="both") - self._check_box_return_type(result, "both") + _check_box_return_type(result, "both") def test_boxplot_axis_limits(self, hist_df): def _check_ax_limits(col, ax): @@ -178,9 +180,7 @@ def test_figsize(self): def test_fontsize(self): df = DataFrame({"a": [1, 2, 3, 4, 5, 6]}) - self._check_ticks_props( - df.boxplot("a", fontsize=16), xlabelsize=16, ylabelsize=16 - ) + _check_ticks_props(df.boxplot("a", fontsize=16), xlabelsize=16, ylabelsize=16) def test_boxplot_numeric_data(self): # GH 22799 @@ -317,24 +317,23 @@ def test_boxplot_group_xlabel_ylabel(self, vert): for subplot in ax: assert subplot.get_xlabel() == xlabel assert subplot.get_ylabel() == ylabel - self.plt.close() + mpl.pyplot.close() ax = df.boxplot(by="group", vert=vert) for subplot in ax: target_label = subplot.get_xlabel() if vert else subplot.get_ylabel() assert target_label == pprint_thing(["group"]) - self.plt.close() + mpl.pyplot.close() -@td.skip_if_no_mpl -class TestDataFrameGroupByPlots(TestPlotBase): +class TestDataFrameGroupByPlots: def test_boxplot_legacy1(self, hist_df): grouped = hist_df.groupby(by="gender") with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(grouped.boxplot, return_type="axes") - self._check_axes_shape(list(axes.values), axes_num=2, layout=(1, 2)) + _check_axes_shape(list(axes.values), axes_num=2, layout=(1, 2)) axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes") - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) @pytest.mark.slow def test_boxplot_legacy2(self): @@ -343,10 +342,10 @@ def test_boxplot_legacy2(self): grouped = df.groupby(level=1) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(grouped.boxplot, return_type="axes") - self._check_axes_shape(list(axes.values), axes_num=10, layout=(4, 3)) + _check_axes_shape(list(axes.values), axes_num=10, layout=(4, 3)) axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes") - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) def test_boxplot_legacy3(self): tuples = zip(string.ascii_letters[:10], range(10)) @@ -356,9 +355,9 @@ def test_boxplot_legacy3(self): grouped = df.unstack(level=1).groupby(level=0, axis=1) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(grouped.boxplot, return_type="axes") - self._check_axes_shape(list(axes.values), axes_num=3, layout=(2, 2)) + _check_axes_shape(list(axes.values), axes_num=3, layout=(2, 2)) axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes") - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) def test_grouped_plot_fignums(self): n = 10 @@ -369,12 +368,12 @@ def test_grouped_plot_fignums(self): gb = df.groupby("gender") res = gb.plot() - assert len(self.plt.get_fignums()) == 2 + assert len(mpl.pyplot.get_fignums()) == 2 assert len(res) == 2 tm.close() res = gb.boxplot(return_type="axes") - assert len(self.plt.get_fignums()) == 1 + assert len(mpl.pyplot.get_fignums()) == 1 assert len(res) == 2 tm.close() @@ -389,13 +388,13 @@ def test_grouped_box_return_type(self, hist_df): # old style: return_type=None result = df.boxplot(by="gender") assert isinstance(result, np.ndarray) - self._check_box_return_type( + _check_box_return_type( result, None, expected_keys=["height", "weight", "category"] ) # now for groupby result = df.groupby("gender").boxplot(return_type="dict") - self._check_box_return_type(result, "dict", expected_keys=["Male", "Female"]) + _check_box_return_type(result, "dict", expected_keys=["Male", "Female"]) columns2 = "X B C D A G Y N Q O".split() df2 = DataFrame(np.random.randn(50, 10), columns=columns2) @@ -404,18 +403,18 @@ def test_grouped_box_return_type(self, hist_df): for t in ["dict", "axes", "both"]: returned = df.groupby("classroom").boxplot(return_type=t) - self._check_box_return_type(returned, t, expected_keys=["A", "B", "C"]) + _check_box_return_type(returned, t, expected_keys=["A", "B", "C"]) returned = df.boxplot(by="classroom", return_type=t) - self._check_box_return_type( + _check_box_return_type( returned, t, expected_keys=["height", "weight", "category"] ) returned = df2.groupby("category").boxplot(return_type=t) - self._check_box_return_type(returned, t, expected_keys=categories2) + _check_box_return_type(returned, t, expected_keys=categories2) returned = df2.boxplot(by="category", return_type=t) - self._check_box_return_type(returned, t, expected_keys=columns2) + _check_box_return_type(returned, t, expected_keys=columns2) @pytest.mark.slow def test_grouped_box_layout(self, hist_df): @@ -442,37 +441,37 @@ def test_grouped_box_layout(self, hist_df): _check_plot_works( df.groupby("gender").boxplot, column="height", return_type="dict" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=2, layout=(1, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=2, layout=(1, 2)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): _check_plot_works( df.groupby("category").boxplot, column="height", return_type="dict" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(2, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(2, 2)) # GH 6769 with tm.assert_produces_warning(UserWarning, check_stacklevel=False): _check_plot_works( df.groupby("classroom").boxplot, column="height", return_type="dict" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2)) # GH 5897 axes = df.boxplot( column=["height", "weight", "category"], by="gender", return_type="axes" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2)) for ax in [axes["height"]]: - self._check_visible(ax.get_xticklabels(), visible=False) - self._check_visible([ax.xaxis.get_label()], visible=False) + _check_visible(ax.get_xticklabels(), visible=False) + _check_visible([ax.xaxis.get_label()], visible=False) for ax in [axes["weight"], axes["category"]]: - self._check_visible(ax.get_xticklabels()) - self._check_visible([ax.xaxis.get_label()]) + _check_visible(ax.get_xticklabels()) + _check_visible([ax.xaxis.get_label()]) df.groupby("classroom").boxplot( column=["height", "weight", "category"], return_type="dict" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): _check_plot_works( @@ -481,7 +480,7 @@ def test_grouped_box_layout(self, hist_df): layout=(3, 2), return_type="dict", ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(3, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(3, 2)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): _check_plot_works( df.groupby("category").boxplot, @@ -489,23 +488,23 @@ def test_grouped_box_layout(self, hist_df): layout=(3, -1), return_type="dict", ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(3, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(3, 2)) df.boxplot(column=["height", "weight", "category"], by="gender", layout=(4, 1)) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(4, 1)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(4, 1)) df.boxplot(column=["height", "weight", "category"], by="gender", layout=(-1, 1)) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(3, 1)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(3, 1)) df.groupby("classroom").boxplot( column=["height", "weight", "category"], layout=(1, 4), return_type="dict" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(1, 4)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(1, 4)) df.groupby("classroom").boxplot( column=["height", "weight", "category"], layout=(1, -1), return_type="dict" ) - self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(1, 3)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(1, 3)) @pytest.mark.slow def test_grouped_box_multiple_axes(self, hist_df): @@ -518,11 +517,11 @@ def test_grouped_box_multiple_axes(self, hist_df): # location should be changed if other test is added # which has earlier alphabetical order with tm.assert_produces_warning(UserWarning): - fig, axes = self.plt.subplots(2, 2) + fig, axes = mpl.pyplot.subplots(2, 2) df.groupby("category").boxplot(column="height", return_type="axes", ax=axes) - self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(2, 2)) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(2, 2)) - fig, axes = self.plt.subplots(2, 3) + fig, axes = mpl.pyplot.subplots(2, 3) with tm.assert_produces_warning(UserWarning): returned = df.boxplot( column=["height", "weight", "category"], @@ -531,7 +530,7 @@ def test_grouped_box_multiple_axes(self, hist_df): ax=axes[0], ) returned = np.array(list(returned.values)) - self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[0]) assert returned[0].figure is fig @@ -541,20 +540,20 @@ def test_grouped_box_multiple_axes(self, hist_df): column=["height", "weight", "category"], return_type="axes", ax=axes[1] ) returned = np.array(list(returned.values)) - self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[1]) assert returned[0].figure is fig msg = "The number of passed axes must be 3, the same as the output plot" with pytest.raises(ValueError, match=msg): - fig, axes = self.plt.subplots(2, 3) + fig, axes = mpl.pyplot.subplots(2, 3) # pass different number of axes from required with tm.assert_produces_warning(UserWarning): axes = df.groupby("classroom").boxplot(ax=axes) def test_fontsize(self): df = DataFrame({"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]}) - self._check_ticks_props( + _check_ticks_props( df.boxplot("a", by="b", fontsize=16), xlabelsize=16, ylabelsize=16 ) diff --git a/pandas/tests/plotting/test_common.py b/pandas/tests/plotting/test_common.py index faf8278675566..20daf59356248 100644 --- a/pandas/tests/plotting/test_common.py +++ b/pandas/tests/plotting/test_common.py @@ -1,17 +1,16 @@ import pytest -import pandas.util._test_decorators as td - from pandas import DataFrame from pandas.tests.plotting.common import ( - TestPlotBase, _check_plot_works, + _check_ticks_props, _gen_two_subplots, ) +plt = pytest.importorskip("matplotlib.pyplot") + -@td.skip_if_no_mpl -class TestCommon(TestPlotBase): +class TestCommon: def test__check_ticks_props(self): # GH 34768 df = DataFrame({"b": [0, 1, 0], "a": [1, 2, 3]}) @@ -19,16 +18,16 @@ def test__check_ticks_props(self): ax.yaxis.set_tick_params(rotation=30) msg = "expected 0.00000 but got " with pytest.raises(AssertionError, match=msg): - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) with pytest.raises(AssertionError, match=msg): - self._check_ticks_props(ax, xlabelsize=0) + _check_ticks_props(ax, xlabelsize=0) with pytest.raises(AssertionError, match=msg): - self._check_ticks_props(ax, yrot=0) + _check_ticks_props(ax, yrot=0) with pytest.raises(AssertionError, match=msg): - self._check_ticks_props(ax, ylabelsize=0) + _check_ticks_props(ax, ylabelsize=0) def test__gen_two_subplots_with_ax(self): - fig = self.plt.gcf() + fig = plt.gcf() gen = _gen_two_subplots(f=lambda **kwargs: None, fig=fig, ax="test") # On the first yield, no subplot should be added since ax was passed next(gen) @@ -42,7 +41,7 @@ def test__gen_two_subplots_with_ax(self): assert subplot_geometry == [2, 1, 2] def test_colorbar_layout(self): - fig = self.plt.figure() + fig = plt.figure() axes = fig.subplot_mosaic( """ diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index dacc0cbea7c9e..dda71328d4e6c 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -37,13 +37,14 @@ period_range, ) from pandas.core.indexes.timedeltas import timedelta_range -from pandas.tests.plotting.common import TestPlotBase +from pandas.tests.plotting.common import _check_ticks_props from pandas.tseries.offsets import WeekOfMonth +mpl = pytest.importorskip("matplotlib") -@td.skip_if_no_mpl -class TestTSPlot(TestPlotBase): + +class TestTSPlot: @pytest.mark.filterwarnings("ignore::UserWarning") def test_ts_plot_with_tz(self, tz_aware_fixture): # GH2877, GH17173, GH31205, GH31580 @@ -60,7 +61,7 @@ def test_ts_plot_with_tz(self, tz_aware_fixture): def test_fontsize_set_correctly(self): # For issue #8765 df = DataFrame(np.random.randn(10, 9), index=range(10)) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(fontsize=2, ax=ax) for label in ax.get_xticklabels() + ax.get_yticklabels(): assert label.get_fontsize() == 2 @@ -95,10 +96,10 @@ def test_nonnumeric_exclude(self): idx = date_range("1/1/1987", freq="A", periods=3) df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(ax=ax) # it works assert len(ax.get_lines()) == 1 # B was plotted - self.plt.close(fig) + mpl.pyplot.close(fig) msg = "no numeric data to plot" with pytest.raises(TypeError, match=msg): @@ -108,7 +109,7 @@ def test_nonnumeric_exclude(self): def test_tsplot_period(self, freq): idx = period_range("12/31/1999", freq=freq, periods=100) ser = Series(np.random.randn(len(idx)), idx) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() _check_plot_works(ser.plot, ax=ax) @pytest.mark.parametrize( @@ -117,12 +118,12 @@ def test_tsplot_period(self, freq): def test_tsplot_datetime(self, freq): idx = date_range("12/31/1999", freq=freq, periods=100) ser = Series(np.random.randn(len(idx)), idx) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() _check_plot_works(ser.plot, ax=ax) def test_tsplot(self): ts = tm.makeTimeSeries() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ts.plot(style="k", ax=ax) color = (0.0, 0.0, 0.0, 1) assert color == ax.get_lines()[0].get_color() @@ -143,7 +144,7 @@ def test_both_style_and_color(self): @pytest.mark.parametrize("freq", ["ms", "us"]) def test_high_freq(self, freq): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() rng = date_range("1/1/2012", periods=100, freq=freq) ser = Series(np.random.randn(len(rng)), rng) _check_plot_works(ser.plot, ax=ax) @@ -164,7 +165,7 @@ def check_format_of_first_point(ax, expected_string): assert expected_string == ax.format_coord(first_x, first_y) annual = Series(1, index=date_range("2014-01-01", periods=3, freq="A-DEC")) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() annual.plot(ax=ax) check_format_of_first_point(ax, "t = 2014 y = 1.000000") @@ -239,7 +240,7 @@ def test_line_plot_inferred_freq(self, freq): _check_plot_works(ser.plot) def test_fake_inferred_business(self): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() rng = date_range("2001-1-1", "2001-1-10") ts = Series(range(len(rng)), index=rng) ts = concat([ts[:3], ts[5:]]) @@ -266,7 +267,7 @@ def test_uhf(self): idx = date_range("2012-6-22 21:59:51.960928", freq="L", periods=500) df = DataFrame(np.random.randn(len(idx), 2), index=idx) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() df.plot(ax=ax) axis = ax.get_xaxis() @@ -283,14 +284,14 @@ def test_irreg_hf(self): df = DataFrame(np.random.randn(len(idx), 2), index=idx) irreg = df.iloc[[0, 1, 3, 4]] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() irreg.plot(ax=ax) diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() sec = 1.0 / 24 / 60 / 60 assert (np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() df2 = df.copy() df2.index = df.index.astype(object) df2.plot(ax=ax) @@ -301,7 +302,7 @@ def test_irregular_datetime64_repr_bug(self): ser = tm.makeTimeSeries() ser = ser.iloc[[0, 1, 2, 7]] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ret = ser.plot(ax=ax) assert ret is not None @@ -311,7 +312,7 @@ def test_irregular_datetime64_repr_bug(self): def test_business_freq(self): bts = tm.makePeriodSeries() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) assert ax.get_lines()[0].get_xydata()[0, 0] == bts.index[0].ordinal idx = ax.get_lines()[0].get_xdata() @@ -320,7 +321,7 @@ def test_business_freq(self): def test_business_freq_convert(self): bts = tm.makeTimeSeries(300).asfreq("BM") ts = bts.to_period("M") - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) assert ax.get_lines()[0].get_xydata()[0, 0] == ts.index[0].ordinal idx = ax.get_lines()[0].get_xdata() @@ -330,7 +331,7 @@ def test_freq_with_no_period_alias(self): # GH34487 freq = WeekOfMonth() bts = tm.makeTimeSeries(5).asfreq(freq) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) idx = ax.get_lines()[0].get_xdata() @@ -342,14 +343,14 @@ def test_nonzero_base(self): # GH2571 idx = date_range("2012-12-20", periods=24, freq="H") + timedelta(minutes=30) df = DataFrame(np.arange(24), index=idx) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() df.plot(ax=ax) rs = ax.get_lines()[0].get_xdata() assert not Index(rs).is_normalized def test_dataframe(self): bts = DataFrame({"a": tm.makeTimeSeries()}) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) idx = ax.get_lines()[0].get_xdata() tm.assert_index_equal(bts.index.to_period(), PeriodIndex(idx)) @@ -376,14 +377,14 @@ def _test(ax): assert int(result[0]) == expected[0].ordinal assert int(result[1]) == expected[1].ordinal fig = ax.get_figure() - self.plt.close(fig) + mpl.pyplot.close(fig) ser = tm.makeTimeSeries() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) _test(ax) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() df = DataFrame({"a": ser, "b": ser + 1}) df.plot(ax=ax) _test(ax) @@ -413,7 +414,7 @@ def test_finder_daily(self): for n in day_lst: rng = bdate_range("1999-1-1", periods=n) ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs1.append(xaxis.get_majorticklocs()[0]) @@ -421,7 +422,7 @@ def test_finder_daily(self): vmin, vmax = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs2.append(xaxis.get_majorticklocs()[0]) - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) assert rs1 == xpl1 assert rs2 == xpl2 @@ -435,7 +436,7 @@ def test_finder_quarterly(self): for n in yrs: rng = period_range("1987Q2", periods=int(n * 4), freq="Q") ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs1.append(xaxis.get_majorticklocs()[0]) @@ -443,7 +444,7 @@ def test_finder_quarterly(self): (vmin, vmax) = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs2.append(xaxis.get_majorticklocs()[0]) - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) assert rs1 == xpl1 assert rs2 == xpl2 @@ -457,7 +458,7 @@ def test_finder_monthly(self): for n in yrs: rng = period_range("1987Q2", periods=int(n * 12), freq="M") ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs1.append(xaxis.get_majorticklocs()[0]) @@ -465,7 +466,7 @@ def test_finder_monthly(self): vmin, vmax = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs2.append(xaxis.get_majorticklocs()[0]) - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) assert rs1 == xpl1 assert rs2 == xpl2 @@ -473,7 +474,7 @@ def test_finder_monthly(self): def test_finder_monthly_long(self): rng = period_range("1988Q1", periods=24 * 12, freq="M") ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] @@ -487,11 +488,11 @@ def test_finder_annual(self): for nyears in [5, 10, 19, 49, 99, 199, 599, 1001]: rng = period_range("1987", periods=nyears, freq="A") ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs.append(xaxis.get_majorticklocs()[0]) - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) assert rs == xp @@ -500,7 +501,7 @@ def test_finder_minutely(self): nminutes = 50 * 24 * 60 rng = date_range("1/1/1999", freq="Min", periods=nminutes) ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] @@ -512,7 +513,7 @@ def test_finder_hourly(self): nhours = 23 rng = date_range("1/1/1999", freq="H", periods=nhours) ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] @@ -523,7 +524,7 @@ def test_finder_hourly(self): def test_gaps(self): ts = tm.makeTimeSeries() ts.iloc[5:25] = np.nan - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ts.plot(ax=ax) lines = ax.get_lines() assert len(lines) == 1 @@ -535,13 +536,13 @@ def test_gaps(self): assert isinstance(data, np.ma.core.MaskedArray) mask = data.mask assert mask[5:25, 1].all() - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) # irregular ts = tm.makeTimeSeries() ts = ts.iloc[[0, 1, 2, 5, 7, 9, 12, 15, 20]] ts.iloc[2:5] = np.nan - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot(ax=ax) lines = ax.get_lines() assert len(lines) == 1 @@ -553,13 +554,13 @@ def test_gaps(self): assert isinstance(data, np.ma.core.MaskedArray) mask = data.mask assert mask[2:5, 1].all() - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) # non-ts idx = [0, 1, 2, 5, 7, 9, 12, 15, 20] ser = Series(np.random.randn(len(idx)), idx) ser.iloc[2:5] = np.nan - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ser.plot(ax=ax) lines = ax.get_lines() assert len(lines) == 1 @@ -574,7 +575,7 @@ def test_gaps(self): def test_gap_upsample(self): low = tm.makeTimeSeries() low.iloc[5:25] = np.nan - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(ax=ax) idxh = date_range(low.index[0], low.index[-1], freq="12h") @@ -595,7 +596,7 @@ def test_gap_upsample(self): def test_secondary_y(self): ser = Series(np.random.randn(10)) ser2 = Series(np.random.randn(10)) - fig, _ = self.plt.subplots() + fig, _ = mpl.pyplot.subplots() ax = ser.plot(secondary_y=True) assert hasattr(ax, "left_ax") assert not hasattr(ax, "right_ax") @@ -605,12 +606,12 @@ def test_secondary_y(self): tm.assert_series_equal(ser, xp) assert ax.get_yaxis().get_ticks_position() == "right" assert not axes[0].get_yaxis().get_visible() - self.plt.close(fig) + mpl.pyplot.close(fig) - _, ax2 = self.plt.subplots() + _, ax2 = mpl.pyplot.subplots() ser2.plot(ax=ax2) assert ax2.get_yaxis().get_ticks_position() == "left" - self.plt.close(ax2.get_figure()) + mpl.pyplot.close(ax2.get_figure()) ax = ser2.plot() ax2 = ser.plot(secondary_y=True) @@ -624,7 +625,7 @@ def test_secondary_y_ts(self): idx = date_range("1/1/2000", periods=10) ser = Series(np.random.randn(10), idx) ser2 = Series(np.random.randn(10), idx) - fig, _ = self.plt.subplots() + fig, _ = mpl.pyplot.subplots() ax = ser.plot(secondary_y=True) assert hasattr(ax, "left_ax") assert not hasattr(ax, "right_ax") @@ -634,12 +635,12 @@ def test_secondary_y_ts(self): tm.assert_series_equal(ser, xp) assert ax.get_yaxis().get_ticks_position() == "right" assert not axes[0].get_yaxis().get_visible() - self.plt.close(fig) + mpl.pyplot.close(fig) - _, ax2 = self.plt.subplots() + _, ax2 = mpl.pyplot.subplots() ser2.plot(ax=ax2) assert ax2.get_yaxis().get_ticks_position() == "left" - self.plt.close(ax2.get_figure()) + mpl.pyplot.close(ax2.get_figure()) ax = ser2.plot() ax2 = ser.plot(secondary_y=True) @@ -648,7 +649,7 @@ def test_secondary_y_ts(self): @td.skip_if_no_scipy def test_secondary_kde(self): ser = Series(np.random.randn(10)) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() ax = ser.plot(secondary_y=True, kind="density", ax=ax) assert hasattr(ax, "left_ax") assert not hasattr(ax, "right_ax") @@ -657,7 +658,7 @@ def test_secondary_kde(self): def test_secondary_bar(self): ser = Series(np.random.randn(10)) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() ser.plot(secondary_y=True, kind="bar", ax=ax) axes = fig.get_axes() assert axes[1].get_yaxis().get_ticks_position() == "right" @@ -682,7 +683,7 @@ def test_mixed_freq_regular_first(self): s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]] # it works! - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s1.plot(ax=ax) ax2 = s2.plot(style="g", ax=ax) @@ -701,7 +702,7 @@ def test_mixed_freq_regular_first(self): def test_mixed_freq_irregular_first(self): s1 = tm.makeTimeSeries() s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s2.plot(style="g", ax=ax) s1.plot(ax=ax) assert not hasattr(ax, "freq") @@ -715,7 +716,7 @@ def test_mixed_freq_regular_first_df(self): # GH 9852 s1 = tm.makeTimeSeries().to_frame() s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s1.plot(ax=ax) ax2 = s2.plot(style="g", ax=ax) lines = ax2.get_lines() @@ -732,7 +733,7 @@ def test_mixed_freq_irregular_first_df(self): # GH 9852 s1 = tm.makeTimeSeries().to_frame() s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s2.plot(style="g", ax=ax) s1.plot(ax=ax) assert not hasattr(ax, "freq") @@ -747,7 +748,7 @@ def test_mixed_freq_hf_first(self): idxl = date_range("1/1/1999", periods=12, freq="M") high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() high.plot(ax=ax) low.plot(ax=ax) for line in ax.get_lines(): @@ -760,7 +761,7 @@ def test_mixed_freq_alignment(self): ts = Series(ts_data, index=ts_ind) ts2 = ts.asfreq("T").interpolate() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot(ax=ax) ts2.plot(style="r", ax=ax) @@ -771,20 +772,20 @@ def test_mixed_freq_lf_first(self): idxl = date_range("1/1/1999", periods=12, freq="M") high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(legend=True, ax=ax) high.plot(legend=True, ax=ax) for line in ax.get_lines(): assert PeriodIndex(data=line.get_xdata()).freq == "D" leg = ax.get_legend() assert len(leg.texts) == 2 - self.plt.close(ax.get_figure()) + mpl.pyplot.close(ax.get_figure()) idxh = date_range("1/1/1999", periods=240, freq="T") idxl = date_range("1/1/1999", periods=4, freq="H") high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(ax=ax) high.plot(ax=ax) for line in ax.get_lines(): @@ -795,7 +796,7 @@ def test_mixed_freq_irreg_period(self): irreg = ts.iloc[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]] rng = period_range("1/3/2000", periods=30, freq="B") ps = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() irreg.plot(ax=ax) ps.plot(ax=ax) @@ -806,7 +807,7 @@ def test_mixed_freq_shared_ax(self): s1 = Series(range(len(idx1)), idx1) s2 = Series(range(len(idx2)), idx2) - fig, (ax1, ax2) = self.plt.subplots(nrows=2, sharex=True) + fig, (ax1, ax2) = mpl.pyplot.subplots(nrows=2, sharex=True) s1.plot(ax=ax1) s2.plot(ax=ax2) @@ -815,7 +816,7 @@ def test_mixed_freq_shared_ax(self): assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0] # using twinx - fig, ax1 = self.plt.subplots() + fig, ax1 = mpl.pyplot.subplots() ax2 = ax1.twinx() s1.plot(ax=ax1) s2.plot(ax=ax2) @@ -832,7 +833,7 @@ def test_mixed_freq_shared_ax(self): # ax2.lines[0].get_xydata()[0, 0]) def test_nat_handling(self): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() dti = DatetimeIndex(["2015-01-01", NaT, "2015-01-03"]) s = Series(range(len(dti)), dti) @@ -847,7 +848,7 @@ def test_to_weekly_resampling(self): idxl = date_range("1/1/1999", periods=12, freq="M") high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() high.plot(ax=ax) low.plot(ax=ax) for line in ax.get_lines(): @@ -858,7 +859,7 @@ def test_from_weekly_resampling(self): idxl = date_range("1/1/1999", periods=12, freq="M") high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(ax=ax) high.plot(ax=ax) @@ -884,7 +885,7 @@ def test_from_resampling_area_line_mixed(self): # low to high for kind1, kind2 in [("line", "area"), ("area", "line")]: - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(kind=kind1, stacked=True, ax=ax) high.plot(kind=kind2, stacked=True, ax=ax) @@ -927,7 +928,7 @@ def test_from_resampling_area_line_mixed(self): # high to low for kind1, kind2 in [("line", "area"), ("area", "line")]: - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() high.plot(kind=kind1, stacked=True, ax=ax) low.plot(kind=kind2, stacked=True, ax=ax) @@ -974,7 +975,7 @@ def test_mixed_freq_second_millisecond(self): high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) # high to low - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() high.plot(ax=ax) low.plot(ax=ax) assert len(ax.get_lines()) == 2 @@ -983,7 +984,7 @@ def test_mixed_freq_second_millisecond(self): tm.close() # low to high - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(ax=ax) high.plot(ax=ax) assert len(ax.get_lines()) == 2 @@ -1000,7 +1001,7 @@ def test_irreg_dtypes(self): idx = date_range("1/1/2000", periods=10) idx = idx[[0, 2, 5, 9]].astype(object) df = DataFrame(np.random.randn(len(idx), 3), idx) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() _check_plot_works(df.plot, ax=ax) def test_time(self): @@ -1010,7 +1011,7 @@ def test_time(self): df = DataFrame( {"a": np.random.randn(len(ts)), "b": np.random.randn(len(ts))}, index=ts ) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(ax=ax) # verify tick labels @@ -1034,7 +1035,7 @@ def test_time_change_xlim(self): df = DataFrame( {"a": np.random.randn(len(ts)), "b": np.random.randn(len(ts))}, index=ts ) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(ax=ax) # verify tick labels @@ -1075,7 +1076,7 @@ def test_time_musec(self): df = DataFrame( {"a": np.random.randn(len(ts)), "b": np.random.randn(len(ts))}, index=ts ) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() ax = df.plot(ax=ax) # verify tick labels @@ -1104,7 +1105,7 @@ def test_secondary_upsample(self): idxl = date_range("1/1/1999", periods=12, freq="M") high = Series(np.random.randn(len(idxh)), idxh) low = Series(np.random.randn(len(idxl)), idxl) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() low.plot(ax=ax) ax = high.plot(secondary_y=True, ax=ax) for line in ax.get_lines(): @@ -1115,7 +1116,7 @@ def test_secondary_upsample(self): assert PeriodIndex(line.get_xdata()).freq == "D" def test_secondary_legend(self): - fig = self.plt.figure() + fig = mpl.pyplot.figure() ax = fig.add_subplot(211) # ts @@ -1134,9 +1135,9 @@ def test_secondary_legend(self): # TODO: color cycle problems assert len(colors) == 4 - self.plt.close(fig) + mpl.pyplot.close(fig) - fig = self.plt.figure() + fig = mpl.pyplot.figure() ax = fig.add_subplot(211) df.plot(secondary_y=["A", "C"], mark_right=False, ax=ax) leg = ax.get_legend() @@ -1145,23 +1146,23 @@ def test_secondary_legend(self): assert leg.get_texts()[1].get_text() == "B" assert leg.get_texts()[2].get_text() == "C" assert leg.get_texts()[3].get_text() == "D" - self.plt.close(fig) + mpl.pyplot.close(fig) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(kind="bar", secondary_y=["A"], ax=ax) leg = ax.get_legend() assert leg.get_texts()[0].get_text() == "A (right)" assert leg.get_texts()[1].get_text() == "B" - self.plt.close(fig) + mpl.pyplot.close(fig) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(kind="bar", secondary_y=["A"], mark_right=False, ax=ax) leg = ax.get_legend() assert leg.get_texts()[0].get_text() == "A" assert leg.get_texts()[1].get_text() == "B" - self.plt.close(fig) + mpl.pyplot.close(fig) - fig = self.plt.figure() + fig = mpl.pyplot.figure() ax = fig.add_subplot(211) df = tm.makeTimeDataFrame() ax = df.plot(secondary_y=["C", "D"], ax=ax) @@ -1174,11 +1175,11 @@ def test_secondary_legend(self): # TODO: color cycle problems assert len(colors) == 4 - self.plt.close(fig) + mpl.pyplot.close(fig) # non-ts df = tm.makeDataFrame() - fig = self.plt.figure() + fig = mpl.pyplot.figure() ax = fig.add_subplot(211) ax = df.plot(secondary_y=["A", "B"], ax=ax) leg = ax.get_legend() @@ -1190,9 +1191,9 @@ def test_secondary_legend(self): # TODO: color cycle problems assert len(colors) == 4 - self.plt.close() + mpl.pyplot.close() - fig = self.plt.figure() + fig = mpl.pyplot.figure() ax = fig.add_subplot(211) ax = df.plot(secondary_y=["C", "D"], ax=ax) leg = ax.get_legend() @@ -1209,7 +1210,7 @@ def test_secondary_legend(self): def test_format_date_axis(self): rng = date_range("1/1/2012", periods=12, freq="M") df = DataFrame(np.random.randn(len(rng), 3), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot(ax=ax) xaxis = ax.get_xaxis() for line in xaxis.get_ticklabels(): @@ -1219,7 +1220,7 @@ def test_format_date_axis(self): def test_ax_plot(self): x = date_range(start="2012-01-02", periods=10, freq="D") y = list(range(len(x))) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() lines = ax.plot(x, y, label="Y") tm.assert_index_equal(DatetimeIndex(lines[0].get_xdata()), x) @@ -1230,7 +1231,7 @@ def test_mpl_nopandas(self): kw = {"fmt": "-", "lw": 4} - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax.plot_date([x.toordinal() for x in dates], values1, **kw) ax.plot_date([x.toordinal() for x in dates], values2, **kw) @@ -1249,7 +1250,7 @@ def test_irregular_ts_shared_ax_xlim(self): ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]] # plot the left section of the irregular series, then the right section - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ts_irregular[:5].plot(ax=ax) ts_irregular[5:].plot(ax=ax) @@ -1265,7 +1266,7 @@ def test_secondary_y_non_ts_xlim(self): s1 = Series(1, index=index_1) s2 = Series(2, index=index_2) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s1.plot(ax=ax) left_before, right_before = ax.get_xlim() s2.plot(secondary_y=True, ax=ax) @@ -1281,7 +1282,7 @@ def test_secondary_y_regular_ts_xlim(self): s1 = Series(1, index=index_1) s2 = Series(2, index=index_2) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s1.plot(ax=ax) left_before, right_before = ax.get_xlim() s2.plot(secondary_y=True, ax=ax) @@ -1295,7 +1296,7 @@ def test_secondary_y_mixed_freq_ts_xlim(self): rng = date_range("2000-01-01", periods=10000, freq="min") ts = Series(1, index=rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ts.plot(ax=ax) left_before, right_before = ax.get_xlim() ts.resample("D").mean().plot(secondary_y=True, ax=ax) @@ -1312,7 +1313,7 @@ def test_secondary_y_irregular_ts_xlim(self): ts = tm.makeTimeSeries()[:20] ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ts_irregular[:5].plot(ax=ax) # plot higher-x values on secondary axis ts_irregular[5:].plot(secondary_y=True, ax=ax) @@ -1326,7 +1327,7 @@ def test_secondary_y_irregular_ts_xlim(self): def test_plot_outofbounds_datetime(self): # 2579 - checking this does not raise values = [date(1677, 1, 1), date(1677, 1, 2)] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax.plot(values) values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)] @@ -1337,9 +1338,9 @@ def test_format_timedelta_ticks_narrow(self): rng = timedelta_range("0", periods=10, freq="ns") df = DataFrame(np.random.randn(len(rng), 3), rng) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() df.plot(fontsize=2, ax=ax) - self.plt.draw() + mpl.pyplot.draw() labels = ax.get_xticklabels() result_labels = [x.get_text() for x in labels] @@ -1361,9 +1362,9 @@ def test_format_timedelta_ticks_wide(self): rng = timedelta_range("0", periods=10, freq="1 d") df = DataFrame(np.random.randn(len(rng), 3), rng) - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() ax = df.plot(fontsize=2, ax=ax) - self.plt.draw() + mpl.pyplot.draw() labels = ax.get_xticklabels() result_labels = [x.get_text() for x in labels] @@ -1373,19 +1374,19 @@ def test_format_timedelta_ticks_wide(self): def test_timedelta_plot(self): # test issue #8711 s = Series(range(5), timedelta_range("1day", periods=5)) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() _check_plot_works(s.plot, ax=ax) # test long period index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 d") s = Series(np.random.randn(len(index)), index) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() _check_plot_works(s.plot, ax=ax) # test short period index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 ns") s = Series(np.random.randn(len(index)), index) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() _check_plot_works(s.plot, ax=ax) def test_hist(self): @@ -1394,7 +1395,7 @@ def test_hist(self): x = rng w1 = np.arange(0, 1, 0.1) w2 = np.arange(0, 1, 0.1)[::-1] - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax.hist([x, x], weights=[w1, w2]) def test_overlapping_datetime(self): @@ -1418,7 +1419,7 @@ def test_overlapping_datetime(self): # plot first series, then add the second series to those axes, # then try adding the first series again - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s1.plot(ax=ax) s2.plot(ax=ax) s1.plot(ax=ax) @@ -1440,9 +1441,9 @@ def test_matplotlib_scatter_datetime64(self): # https://github.com/matplotlib/matplotlib/issues/11391 df = DataFrame(np.random.RandomState(0).rand(10, 2), columns=["x", "y"]) df["time"] = date_range("2018-01-01", periods=10, freq="D") - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() ax.scatter(x="time", y="y", data=df) - self.plt.draw() + mpl.pyplot.draw() label = ax.get_xticklabels()[0] expected = "2018-01-01" assert label.get_text() == expected @@ -1453,25 +1454,25 @@ def test_check_xticks_rot(self): x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-03"]) df = DataFrame({"x": x, "y": [1, 2, 3]}) axes = df.plot(x="x", y="y") - self._check_ticks_props(axes, xrot=0) + _check_ticks_props(axes, xrot=0) # irregular time series x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"]) df = DataFrame({"x": x, "y": [1, 2, 3]}) axes = df.plot(x="x", y="y") - self._check_ticks_props(axes, xrot=30) + _check_ticks_props(axes, xrot=30) # use timeseries index or not axes = df.set_index("x").plot(y="y", use_index=True) - self._check_ticks_props(axes, xrot=30) + _check_ticks_props(axes, xrot=30) axes = df.set_index("x").plot(y="y", use_index=False) - self._check_ticks_props(axes, xrot=0) + _check_ticks_props(axes, xrot=0) # separate subplots axes = df.plot(x="x", y="y", subplots=True, sharex=True) - self._check_ticks_props(axes, xrot=30) + _check_ticks_props(axes, xrot=30) axes = df.plot(x="x", y="y", subplots=True, sharex=False) - self._check_ticks_props(axes, xrot=0) + _check_ticks_props(axes, xrot=0) def _check_plot_works(f, freq=None, series=None, *args, **kwargs): diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index 8cde3062d09f9..43e35e94164c3 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -4,19 +4,21 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - from pandas import ( DataFrame, Index, Series, ) import pandas._testing as tm -from pandas.tests.plotting.common import TestPlotBase +from pandas.tests.plotting.common import ( + _check_axes_shape, + _check_legend_labels, +) + +pytest.importorskip("matplotlib") -@td.skip_if_no_mpl -class TestDataFrameGroupByPlots(TestPlotBase): +class TestDataFrameGroupByPlots: def test_series_groupby_plotting_nominally_works(self): n = 10 weight = Series(np.random.normal(166, 20, size=n)) @@ -80,11 +82,9 @@ def test_groupby_hist_frame_with_legend(self, column, expected_axes_num): g = df.groupby("c") for axes in g.hist(legend=True, column=column): - self._check_axes_shape( - axes, axes_num=expected_axes_num, layout=expected_layout - ) + _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) for ax, expected_label in zip(axes[0], expected_labels): - self._check_legend_labels(ax, expected_label) + _check_legend_labels(ax, expected_label) @pytest.mark.parametrize("column", [None, "b"]) def test_groupby_hist_frame_with_legend_raises(self, column): @@ -103,8 +103,8 @@ def test_groupby_hist_series_with_legend(self): g = df.groupby("c") for ax in g["a"].hist(legend=True): - self._check_axes_shape(ax, axes_num=1, layout=(1, 1)) - self._check_legend_labels(ax, ["1", "2"]) + _check_axes_shape(ax, axes_num=1, layout=(1, 1)) + _check_legend_labels(ax, ["1", "2"]) def test_groupby_hist_series_with_legend_raises(self): # GH 6279 - SeriesGroupBy histogram with legend and label raises diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 3392c309e0329..d798ac9a88085 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -14,18 +14,27 @@ ) import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_ax_scales, + _check_axes_shape, + _check_colors, + _check_legend_labels, + _check_patches_all_filled, _check_plot_works, + _check_text_labels, + _check_ticks_props, + get_x_axis, + get_y_axis, ) +mpl = pytest.importorskip("matplotlib") + @pytest.fixture def ts(): return tm.makeTimeSeries(name="ts") -@td.skip_if_no_mpl -class TestSeriesPlots(TestPlotBase): +class TestSeriesPlots: def test_hist_legacy(self, ts): _check_plot_works(ts.hist) _check_plot_works(ts.hist, grid=False) @@ -36,13 +45,13 @@ def test_hist_legacy(self, ts): with tm.assert_produces_warning(UserWarning, check_stacklevel=False): _check_plot_works(ts.hist, by=ts.index.month, bins=5) - fig, ax = self.plt.subplots(1, 1) + fig, ax = mpl.pyplot.subplots(1, 1) _check_plot_works(ts.hist, ax=ax, default_axes=True) _check_plot_works(ts.hist, ax=ax, figure=fig, default_axes=True) _check_plot_works(ts.hist, figure=fig, default_axes=True) tm.close() - fig, (ax1, ax2) = self.plt.subplots(1, 2) + fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2) _check_plot_works(ts.hist, figure=fig, ax=ax1, default_axes=True) _check_plot_works(ts.hist, figure=fig, ax=ax2, default_axes=True) @@ -76,34 +85,34 @@ def test_hist_layout_with_by(self, hist_df): # though we don't explicing pass one, see GH #13188 with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1)) - self._check_axes_shape(axes, axes_num=2, layout=(2, 1)) + _check_axes_shape(axes, axes_num=2, layout=(2, 1)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.gender, layout=(3, -1)) - self._check_axes_shape(axes, axes_num=2, layout=(3, 1)) + _check_axes_shape(axes, axes_num=2, layout=(3, 1)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.category, layout=(4, 1)) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.category, layout=(2, -1)) - self._check_axes_shape(axes, axes_num=4, layout=(2, 2)) + _check_axes_shape(axes, axes_num=4, layout=(2, 2)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.category, layout=(3, -1)) - self._check_axes_shape(axes, axes_num=4, layout=(3, 2)) + _check_axes_shape(axes, axes_num=4, layout=(3, 2)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.category, layout=(-1, 4)) - self._check_axes_shape(axes, axes_num=4, layout=(1, 4)) + _check_axes_shape(axes, axes_num=4, layout=(1, 4)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.height.hist, by=df.classroom, layout=(2, 2)) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7)) - self._check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7)) + _check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7)) def test_hist_no_overlap(self): from matplotlib.pyplot import ( @@ -124,7 +133,7 @@ def test_hist_no_overlap(self): def test_hist_by_no_extra_plots(self, hist_df): df = hist_df df.height.hist(by=df.gender) - assert len(self.plt.get_fignums()) == 1 + assert len(mpl.pyplot.get_fignums()) == 1 def test_plot_fails_when_ax_differs_from_figure(self, ts): from pylab import figure @@ -149,7 +158,7 @@ def test_histtype_argument(self, histtype, expected): # GH23992 Verify functioning of histtype argument ser = Series(np.random.randint(1, 10)) ax = ser.hist(histtype=histtype) - self._check_patches_all_filled(ax, filled=expected) + _check_patches_all_filled(ax, filled=expected) @pytest.mark.parametrize( "by, expected_axes_num, expected_layout", [(None, 1, (1, 1)), ("b", 2, (1, 2))] @@ -162,8 +171,8 @@ def test_hist_with_legend(self, by, expected_axes_num, expected_layout): # Use default_axes=True when plotting method generate subplots itself axes = _check_plot_works(s.hist, default_axes=True, legend=True, by=by) - self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) - self._check_legend_labels(axes, "a") + _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) + _check_legend_labels(axes, "a") @pytest.mark.parametrize("by", [None, "b"]) def test_hist_with_legend_raises(self, by): @@ -176,61 +185,60 @@ def test_hist_with_legend_raises(self, by): s.hist(legend=True, by=by, label="c") def test_hist_kwargs(self, ts): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.hist(bins=5, ax=ax) assert len(ax.patches) == 5 - self._check_text_labels(ax.yaxis.get_label(), "Frequency") + _check_text_labels(ax.yaxis.get_label(), "Frequency") tm.close() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.hist(orientation="horizontal", ax=ax) - self._check_text_labels(ax.xaxis.get_label(), "Frequency") + _check_text_labels(ax.xaxis.get_label(), "Frequency") tm.close() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.hist(align="left", stacked=True, ax=ax) tm.close() @pytest.mark.xfail(reason="Api changed in 3.6.0") @td.skip_if_no_scipy def test_hist_kde(self, ts): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.hist(logy=True, ax=ax) - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") xlabels = ax.get_xticklabels() # ticks are values, thus ticklabels are blank - self._check_text_labels(xlabels, [""] * len(xlabels)) + _check_text_labels(xlabels, [""] * len(xlabels)) ylabels = ax.get_yticklabels() - self._check_text_labels(ylabels, [""] * len(ylabels)) + _check_text_labels(ylabels, [""] * len(ylabels)) _check_plot_works(ts.plot.kde) _check_plot_works(ts.plot.density) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.kde(logy=True, ax=ax) - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") xlabels = ax.get_xticklabels() - self._check_text_labels(xlabels, [""] * len(xlabels)) + _check_text_labels(xlabels, [""] * len(xlabels)) ylabels = ax.get_yticklabels() - self._check_text_labels(ylabels, [""] * len(ylabels)) + _check_text_labels(ylabels, [""] * len(ylabels)) @td.skip_if_no_scipy def test_hist_kde_color(self, ts): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.hist(logy=True, bins=10, color="b", ax=ax) - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") assert len(ax.patches) == 10 - self._check_colors(ax.patches, facecolors=["b"] * 10) + _check_colors(ax.patches, facecolors=["b"] * 10) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.kde(logy=True, color="r", ax=ax) - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") lines = ax.get_lines() assert len(lines) == 1 - self._check_colors(lines, ["r"]) + _check_colors(lines, ["r"]) -@td.skip_if_no_mpl -class TestDataFramePlots(TestPlotBase): +class TestDataFramePlots: @pytest.mark.slow def test_hist_df_legacy(self, hist_df): from matplotlib.patches import Rectangle @@ -250,7 +258,7 @@ def test_hist_df_legacy(self, hist_df): ) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.hist, grid=False) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) assert not axes[1, 1].get_visible() _check_plot_works(df[[2]].hist) @@ -269,7 +277,7 @@ def test_hist_df_legacy(self, hist_df): ) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.hist, layout=(4, 2)) - self._check_axes_shape(axes, axes_num=6, layout=(4, 2)) + _check_axes_shape(axes, axes_num=6, layout=(4, 2)) # make sure sharex, sharey is handled with tm.assert_produces_warning(UserWarning, check_stacklevel=False): @@ -288,16 +296,12 @@ def test_hist_df_legacy(self, hist_df): xf, yf = 20, 18 xrot, yrot = 30, 40 axes = ser.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) - self._check_ticks_props( - axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot - ) + _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) xf, yf = 20, 18 xrot, yrot = 30, 40 axes = df.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) - self._check_ticks_props( - axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot - ) + _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) tm.close() @@ -309,7 +313,7 @@ def test_hist_df_legacy(self, hist_df): tm.close() ax = ser.hist(log=True) # scale of y must be 'log' - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") tm.close() @@ -368,7 +372,7 @@ def test_hist_layout(self): for layout_test in layout_to_expected_size: axes = df.hist(layout=layout_test["layout"]) expected = layout_test["expected_size"] - self._check_axes_shape(axes, axes_num=3, layout=expected) + _check_axes_shape(axes, axes_num=3, layout=expected) # layout too small for all 4 plots msg = "Layout of 1x1 must be larger than required size 3" @@ -396,7 +400,7 @@ def test_tight_layout(self): ) # Use default_axes=True when plotting method generate subplots itself _check_plot_works(df.hist, default_axes=True) - self.plt.tight_layout() + mpl.pyplot.tight_layout() tm.close() @@ -417,7 +421,7 @@ def test_hist_subplot_xrot(self): bins=5, xrot=0, ) - self._check_ticks_props(axes, xrot=0) + _check_ticks_props(axes, xrot=0) @pytest.mark.parametrize( "column, expected", @@ -461,7 +465,7 @@ def test_histtype_argument(self, histtype, expected): # GH23992 Verify functioning of histtype argument df = DataFrame(np.random.randint(1, 10, size=(100, 2)), columns=["a", "b"]) ax = df.hist(histtype=histtype) - self._check_patches_all_filled(ax, filled=expected) + _check_patches_all_filled(ax, filled=expected) @pytest.mark.parametrize("by", [None, "c"]) @pytest.mark.parametrize("column", [None, "b"]) @@ -485,11 +489,11 @@ def test_hist_with_legend(self, by, column): column=column, ) - self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) + _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) if by is None and column is None: axes = axes[0] for expected_label, ax in zip(expected_labels, axes): - self._check_legend_labels(ax, expected_label) + _check_legend_labels(ax, expected_label) @pytest.mark.parametrize("by", [None, "c"]) @pytest.mark.parametrize("column", [None, "b"]) @@ -503,7 +507,7 @@ def test_hist_with_legend_raises(self, by, column): def test_hist_df_kwargs(self): df = DataFrame(np.random.randn(10, 2)) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot.hist(bins=5, ax=ax) assert len(ax.patches) == 10 @@ -513,11 +517,11 @@ def test_hist_df_with_nonnumerics(self): np.random.RandomState(42).randn(10, 4), columns=["A", "B", "C", "D"] ) df["E"] = ["x", "y"] * 5 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot.hist(bins=5, ax=ax) assert len(ax.patches) == 20 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot.hist(ax=ax) # bins=10 assert len(ax.patches) == 40 @@ -526,35 +530,35 @@ def test_hist_secondary_legend(self): df = DataFrame(np.random.randn(30, 4), columns=list("abcd")) # primary -> secondary - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df["a"].plot.hist(legend=True, ax=ax) df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) # both legends are drawn on left ax # left and right axis must be visible - self._check_legend_labels(ax, labels=["a", "b (right)"]) + _check_legend_labels(ax, labels=["a", "b (right)"]) assert ax.get_yaxis().get_visible() assert ax.right_ax.get_yaxis().get_visible() tm.close() # secondary -> secondary - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) # both legends are draw on left ax # left axis must be invisible, right axis must be visible - self._check_legend_labels(ax.left_ax, labels=["a (right)", "b (right)"]) + _check_legend_labels(ax.left_ax, labels=["a (right)", "b (right)"]) assert not ax.left_ax.get_yaxis().get_visible() assert ax.get_yaxis().get_visible() tm.close() # secondary -> primary - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) # right axes is returned df["b"].plot.hist(ax=ax, legend=True) # both legends are draw on left ax # left and right axis must be visible - self._check_legend_labels(ax.left_ax, labels=["a (right)", "b"]) + _check_legend_labels(ax.left_ax, labels=["a (right)", "b"]) assert ax.left_ax.get_yaxis().get_visible() assert ax.get_yaxis().get_visible() tm.close() @@ -572,11 +576,11 @@ def test_hist_with_nans_and_weights(self): from matplotlib.patches import Rectangle - _, ax0 = self.plt.subplots() + _, ax0 = mpl.pyplot.subplots() df.plot.hist(ax=ax0, weights=weights) rects = [x for x in ax0.get_children() if isinstance(x, Rectangle)] heights = [rect.get_height() for rect in rects] - _, ax1 = self.plt.subplots() + _, ax1 = mpl.pyplot.subplots() no_nan_df.plot.hist(ax=ax1, weights=no_nan_weights) no_nan_rects = [x for x in ax1.get_children() if isinstance(x, Rectangle)] no_nan_heights = [rect.get_height() for rect in no_nan_rects] @@ -586,12 +590,11 @@ def test_hist_with_nans_and_weights(self): msg = "weights must have the same shape as data, or be a single column" with pytest.raises(ValueError, match=msg): - _, ax2 = self.plt.subplots() + _, ax2 = mpl.pyplot.subplots() no_nan_df.plot.hist(ax=ax2, weights=idxerror_weights) -@td.skip_if_no_mpl -class TestDataFrameGroupByPlots(TestPlotBase): +class TestDataFrameGroupByPlots: def test_grouped_hist_legacy(self): from matplotlib.patches import Rectangle @@ -610,17 +613,17 @@ def test_grouped_hist_legacy(self): df["D"] = ["X"] * 500 axes = _grouped_hist(df.A, by=df.C) - self._check_axes_shape(axes, axes_num=4, layout=(2, 2)) + _check_axes_shape(axes, axes_num=4, layout=(2, 2)) tm.close() axes = df.hist(by=df.C) - self._check_axes_shape(axes, axes_num=4, layout=(2, 2)) + _check_axes_shape(axes, axes_num=4, layout=(2, 2)) tm.close() # group by a key with single value axes = df.hist(by="D", rot=30) - self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) - self._check_ticks_props(axes, xrot=30) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_ticks_props(axes, xrot=30) tm.close() # make sure kwargs to hist are handled @@ -643,14 +646,12 @@ def test_grouped_hist_legacy(self): rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] height = rects[-1].get_height() tm.assert_almost_equal(height, 1.0) - self._check_ticks_props( - axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot - ) + _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) tm.close() axes = _grouped_hist(df.A, by=df.C, log=True) # scale of y must be 'log' - self._check_ax_scales(axes, yaxis="log") + _check_ax_scales(axes, yaxis="log") tm.close() # propagate attr exception from matplotlib.Axes.hist @@ -670,7 +671,7 @@ def test_grouped_hist_legacy2(self): gb = df_int.groupby("gender") axes = gb.hist() assert len(axes) == 2 - assert len(self.plt.get_fignums()) == 2 + assert len(mpl.pyplot.get_fignums()) == 2 tm.close() @pytest.mark.slow @@ -692,22 +693,22 @@ def test_grouped_hist_layout(self, hist_df): axes = _check_plot_works( df.hist, column="height", by=df.gender, layout=(2, 1) ) - self._check_axes_shape(axes, axes_num=2, layout=(2, 1)) + _check_axes_shape(axes, axes_num=2, layout=(2, 1)) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works( df.hist, column="height", by=df.gender, layout=(2, -1) ) - self._check_axes_shape(axes, axes_num=2, layout=(2, 1)) + _check_axes_shape(axes, axes_num=2, layout=(2, 1)) axes = df.hist(column="height", by=df.category, layout=(4, 1)) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) axes = df.hist(column="height", by=df.category, layout=(-1, 1)) - self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) + _check_axes_shape(axes, axes_num=4, layout=(4, 1)) axes = df.hist(column="height", by=df.category, layout=(4, 2), figsize=(12, 8)) - self._check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 8)) + _check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 8)) tm.close() # GH 6769 @@ -715,34 +716,34 @@ def test_grouped_hist_layout(self, hist_df): axes = _check_plot_works( df.hist, column="height", by="classroom", layout=(2, 2) ) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) # without column with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(df.hist, by="classroom") - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) axes = df.hist(by="gender", layout=(3, 5)) - self._check_axes_shape(axes, axes_num=2, layout=(3, 5)) + _check_axes_shape(axes, axes_num=2, layout=(3, 5)) axes = df.hist(column=["height", "weight", "category"]) - self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) def test_grouped_hist_multiple_axes(self, hist_df): # GH 6970, GH 7069 df = hist_df - fig, axes = self.plt.subplots(2, 3) + fig, axes = mpl.pyplot.subplots(2, 3) returned = df.hist(column=["height", "weight", "category"], ax=axes[0]) - self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[0]) assert returned[0].figure is fig returned = df.hist(by="classroom", ax=axes[1]) - self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[1]) assert returned[0].figure is fig - fig, axes = self.plt.subplots(2, 3) + fig, axes = mpl.pyplot.subplots(2, 3) # pass different number of axes from required msg = "The number of passed axes must be 1, the same as the output plot" with pytest.raises(ValueError, match=msg): @@ -754,35 +755,35 @@ def test_axis_share_x(self, hist_df): ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True) # share x - assert self.get_x_axis(ax1).joined(ax1, ax2) - assert self.get_x_axis(ax2).joined(ax1, ax2) + assert get_x_axis(ax1).joined(ax1, ax2) + assert get_x_axis(ax2).joined(ax1, ax2) # don't share y - assert not self.get_y_axis(ax1).joined(ax1, ax2) - assert not self.get_y_axis(ax2).joined(ax1, ax2) + assert not get_y_axis(ax1).joined(ax1, ax2) + assert not get_y_axis(ax2).joined(ax1, ax2) def test_axis_share_y(self, hist_df): df = hist_df ax1, ax2 = df.hist(column="height", by=df.gender, sharey=True) # share y - assert self.get_y_axis(ax1).joined(ax1, ax2) - assert self.get_y_axis(ax2).joined(ax1, ax2) + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) # don't share x - assert not self.get_x_axis(ax1).joined(ax1, ax2) - assert not self.get_x_axis(ax2).joined(ax1, ax2) + assert not get_x_axis(ax1).joined(ax1, ax2) + assert not get_x_axis(ax2).joined(ax1, ax2) def test_axis_share_xy(self, hist_df): df = hist_df ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True, sharey=True) # share both x and y - assert self.get_x_axis(ax1).joined(ax1, ax2) - assert self.get_x_axis(ax2).joined(ax1, ax2) + assert get_x_axis(ax1).joined(ax1, ax2) + assert get_x_axis(ax2).joined(ax1, ax2) - assert self.get_y_axis(ax1).joined(ax1, ax2) - assert self.get_y_axis(ax2).joined(ax1, ax2) + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) @pytest.mark.parametrize( "histtype, expected", @@ -797,4 +798,4 @@ def test_histtype_argument(self, histtype, expected): # GH23992 Verify functioning of histtype argument df = DataFrame(np.random.randint(1, 10, size=(100, 2)), columns=["a", "b"]) ax = df.hist(by="a", histtype=histtype) - self._check_patches_all_filled(ax, filled=expected) + _check_patches_all_filled(ax, filled=expected) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index a89956d1c14c8..e8797266fcbbe 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -15,10 +15,15 @@ ) import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_colors, + _check_legend_labels, _check_plot_works, + _check_text_labels, + _check_ticks_props, ) +mpl = pytest.importorskip("matplotlib") + @td.skip_if_mpl def test_import_error_message(): @@ -63,8 +68,7 @@ def test_get_accessor_args(): assert len(kwargs) == 24 -@td.skip_if_no_mpl -class TestSeriesPlots(TestPlotBase): +class TestSeriesPlots: def test_autocorrelation_plot(self): from pandas.plotting import autocorrelation_plot @@ -75,7 +79,7 @@ def test_autocorrelation_plot(self): _check_plot_works(autocorrelation_plot, series=ser.values) ax = autocorrelation_plot(ser, label="Test") - self._check_legend_labels(ax, labels=["Test"]) + _check_legend_labels(ax, labels=["Test"]) @pytest.mark.parametrize("kwargs", [{}, {"lag": 5}]) def test_lag_plot(self, kwargs): @@ -91,8 +95,7 @@ def test_bootstrap_plot(self): _check_plot_works(bootstrap_plot, series=ser, size=10) -@td.skip_if_no_mpl -class TestDataFramePlots(TestPlotBase): +class TestDataFramePlots: @td.skip_if_no_scipy @pytest.mark.parametrize("pass_axis", [False, True]) def test_scatter_matrix_axis(self, pass_axis): @@ -100,7 +103,7 @@ def test_scatter_matrix_axis(self, pass_axis): ax = None if pass_axis: - _, ax = self.plt.subplots(3, 3) + _, ax = mpl.pyplot.subplots(3, 3) df = DataFrame(np.random.RandomState(42).randn(100, 3)) @@ -116,8 +119,8 @@ def test_scatter_matrix_axis(self, pass_axis): # GH 5662 expected = ["-2", "0", "2"] - self._check_text_labels(axes0_labels, expected) - self._check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) + _check_text_labels(axes0_labels, expected) + _check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) df[0] = (df[0] - 2) / 3 @@ -131,8 +134,8 @@ def test_scatter_matrix_axis(self, pass_axis): ) axes0_labels = axes[0][0].yaxis.get_majorticklabels() expected = ["-1.0", "-0.5", "0.0"] - self._check_text_labels(axes0_labels, expected) - self._check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) + _check_text_labels(axes0_labels, expected) + _check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) @pytest.mark.slow def test_andrews_curves(self, iris): @@ -149,25 +152,19 @@ def test_andrews_curves(self, iris): ax = _check_plot_works( andrews_curves, frame=df, class_column="Name", color=rgba ) - self._check_colors( - ax.get_lines()[:10], linecolors=rgba, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df["Name"][:10]) cnames = ["dodgerblue", "aquamarine", "seagreen"] ax = _check_plot_works( andrews_curves, frame=df, class_column="Name", color=cnames ) - self._check_colors( - ax.get_lines()[:10], linecolors=cnames, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df["Name"][:10]) ax = _check_plot_works( andrews_curves, frame=df, class_column="Name", colormap=cm.jet ) cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] - self._check_colors( - ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10]) length = 10 df = DataFrame( @@ -185,31 +182,25 @@ def test_andrews_curves(self, iris): ax = _check_plot_works( andrews_curves, frame=df, class_column="Name", color=rgba ) - self._check_colors( - ax.get_lines()[:10], linecolors=rgba, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df["Name"][:10]) cnames = ["dodgerblue", "aquamarine", "seagreen"] ax = _check_plot_works( andrews_curves, frame=df, class_column="Name", color=cnames ) - self._check_colors( - ax.get_lines()[:10], linecolors=cnames, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df["Name"][:10]) ax = _check_plot_works( andrews_curves, frame=df, class_column="Name", colormap=cm.jet ) cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] - self._check_colors( - ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10]) colors = ["b", "g", "r"] df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors}) ax = andrews_curves(df, "Name", color=colors) handles, labels = ax.get_legend_handles_labels() - self._check_colors(handles, linecolors=colors) + _check_colors(handles, linecolors=colors) @pytest.mark.slow def test_parallel_coordinates(self, iris): @@ -227,25 +218,19 @@ def test_parallel_coordinates(self, iris): ax = _check_plot_works( parallel_coordinates, frame=df, class_column="Name", color=rgba ) - self._check_colors( - ax.get_lines()[:10], linecolors=rgba, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df["Name"][:10]) cnames = ["dodgerblue", "aquamarine", "seagreen"] ax = _check_plot_works( parallel_coordinates, frame=df, class_column="Name", color=cnames ) - self._check_colors( - ax.get_lines()[:10], linecolors=cnames, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df["Name"][:10]) ax = _check_plot_works( parallel_coordinates, frame=df, class_column="Name", colormap=cm.jet ) cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] - self._check_colors( - ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10] - ) + _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10]) ax = _check_plot_works( parallel_coordinates, frame=df, class_column="Name", axvlines=False @@ -256,7 +241,7 @@ def test_parallel_coordinates(self, iris): df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors}) ax = parallel_coordinates(df, "Name", color=colors) handles, labels = ax.get_legend_handles_labels() - self._check_colors(handles, linecolors=colors) + _check_colors(handles, linecolors=colors) # not sure if this is indicative of a problem @pytest.mark.filterwarnings("ignore:Attempting to set:UserWarning") @@ -299,17 +284,17 @@ def test_radviz(self, iris): ax = _check_plot_works(radviz, frame=df, class_column="Name", color=rgba) # skip Circle drawn as ticks patches = [p for p in ax.patches[:20] if p.get_label() != ""] - self._check_colors(patches[:10], facecolors=rgba, mapping=df["Name"][:10]) + _check_colors(patches[:10], facecolors=rgba, mapping=df["Name"][:10]) cnames = ["dodgerblue", "aquamarine", "seagreen"] _check_plot_works(radviz, frame=df, class_column="Name", color=cnames) patches = [p for p in ax.patches[:20] if p.get_label() != ""] - self._check_colors(patches, facecolors=cnames, mapping=df["Name"][:10]) + _check_colors(patches, facecolors=cnames, mapping=df["Name"][:10]) _check_plot_works(radviz, frame=df, class_column="Name", colormap=cm.jet) cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] patches = [p for p in ax.patches[:20] if p.get_label() != ""] - self._check_colors(patches, facecolors=cmaps, mapping=df["Name"][:10]) + _check_colors(patches, facecolors=cmaps, mapping=df["Name"][:10]) colors = [[0.0, 0.0, 1.0, 1.0], [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]] df = DataFrame( @@ -317,7 +302,7 @@ def test_radviz(self, iris): ) ax = radviz(df, "Name", color=colors) handles, labels = ax.get_legend_handles_labels() - self._check_colors(handles, facecolors=colors) + _check_colors(handles, facecolors=colors) def test_subplot_titles(self, iris): df = iris.drop("Name", axis=1).head() @@ -478,7 +463,7 @@ def test_has_externally_shared_axis_x_axis(self): # Test _has_externally_shared_axis() works for x-axis func = plotting._matplotlib.tools._has_externally_shared_axis - fig = self.plt.figure() + fig = mpl.pyplot.figure() plots = fig.subplots(2, 4) # Create *externally* shared axes for first and third columns @@ -503,7 +488,7 @@ def test_has_externally_shared_axis_y_axis(self): # Test _has_externally_shared_axis() works for y-axis func = plotting._matplotlib.tools._has_externally_shared_axis - fig = self.plt.figure() + fig = mpl.pyplot.figure() plots = fig.subplots(4, 2) # Create *externally* shared axes for first and third rows @@ -529,7 +514,7 @@ def test_has_externally_shared_axis_invalid_compare_axis(self): # passed an invalid value as compare_axis parameter func = plotting._matplotlib.tools._has_externally_shared_axis - fig = self.plt.figure() + fig = mpl.pyplot.figure() plots = fig.subplots(4, 2) # Create arbitrary axes @@ -546,7 +531,7 @@ def test_externally_shared_axes(self): df = DataFrame({"a": np.random.randn(1000), "b": np.random.randn(1000)}) # Create figure - fig = self.plt.figure() + fig = mpl.pyplot.figure() plots = fig.subplots(2, 3) # Create *externally* shared axes diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 755a1811c1356..c2dffdb6f7e47 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -18,10 +18,21 @@ ) import pandas._testing as tm from pandas.tests.plotting.common import ( - TestPlotBase, + _check_ax_scales, + _check_axes_shape, + _check_colors, + _check_grid_settings, + _check_has_errorbars, + _check_legend_labels, _check_plot_works, + _check_text_labels, + _check_ticks_props, + _unpack_cycler, + get_y_axis, ) +mpl = pytest.importorskip("matplotlib") + @pytest.fixture def ts(): @@ -38,23 +49,22 @@ def iseries(): return tm.makePeriodSeries(name="iseries") -@td.skip_if_no_mpl -class TestSeriesPlots(TestPlotBase): +class TestSeriesPlots: @pytest.mark.slow def test_plot(self, ts): _check_plot_works(ts.plot, label="foo") _check_plot_works(ts.plot, use_index=False) axes = _check_plot_works(ts.plot, rot=0) - self._check_ticks_props(axes, xrot=0) + _check_ticks_props(axes, xrot=0) ax = _check_plot_works(ts.plot, style=".", logy=True) - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") ax = _check_plot_works(ts.plot, style=".", logx=True) - self._check_ax_scales(ax, xaxis="log") + _check_ax_scales(ax, xaxis="log") ax = _check_plot_works(ts.plot, style=".", loglog=True) - self._check_ax_scales(ax, xaxis="log", yaxis="log") + _check_ax_scales(ax, xaxis="log", yaxis="log") _check_plot_works(ts[:10].plot.bar) _check_plot_works(ts.plot.area, stacked=False) @@ -81,35 +91,35 @@ def test_plot_series_barh(self, series): def test_plot_series_bar_ax(self): ax = _check_plot_works(Series(np.random.randn(10)).plot.bar, color="black") - self._check_colors([ax.patches[0]], facecolors=["black"]) + _check_colors([ax.patches[0]], facecolors=["black"]) def test_plot_6951(self, ts): # GH 6951 ax = _check_plot_works(ts.plot, subplots=True) - self._check_axes_shape(ax, axes_num=1, layout=(1, 1)) + _check_axes_shape(ax, axes_num=1, layout=(1, 1)) ax = _check_plot_works(ts.plot, subplots=True, layout=(-1, 1)) - self._check_axes_shape(ax, axes_num=1, layout=(1, 1)) + _check_axes_shape(ax, axes_num=1, layout=(1, 1)) ax = _check_plot_works(ts.plot, subplots=True, layout=(1, -1)) - self._check_axes_shape(ax, axes_num=1, layout=(1, 1)) + _check_axes_shape(ax, axes_num=1, layout=(1, 1)) def test_plot_figsize_and_title(self, series): # figsize and title - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = series.plot(title="Test", figsize=(16, 8), ax=ax) - self._check_text_labels(ax.title, "Test") - self._check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16, 8)) + _check_text_labels(ax.title, "Test") + _check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16, 8)) def test_dont_modify_rcParams(self): # GH 8242 key = "axes.prop_cycle" - colors = self.plt.rcParams[key] - _, ax = self.plt.subplots() + colors = mpl.pyplot.rcParams[key] + _, ax = mpl.pyplot.subplots() Series([1, 2, 3]).plot(ax=ax) - assert colors == self.plt.rcParams[key] + assert colors == mpl.pyplot.rcParams[key] def test_ts_line_lim(self, ts): - fig, ax = self.plt.subplots() + fig, ax = mpl.pyplot.subplots() ax = ts.plot(ax=ax) xmin, xmax = ax.get_xlim() lines = ax.get_lines() @@ -124,81 +134,81 @@ def test_ts_line_lim(self, ts): assert xmax >= lines[0].get_data(orig=False)[0][-1] def test_ts_area_lim(self, ts): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.area(stacked=False, ax=ax) xmin, xmax = ax.get_xlim() line = ax.get_lines()[0].get_data(orig=False)[0] assert xmin <= line[0] assert xmax >= line[-1] - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) tm.close() # GH 7471 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.area(stacked=False, x_compat=True, ax=ax) xmin, xmax = ax.get_xlim() line = ax.get_lines()[0].get_data(orig=False)[0] assert xmin <= line[0] assert xmax >= line[-1] - self._check_ticks_props(ax, xrot=30) + _check_ticks_props(ax, xrot=30) tm.close() tz_ts = ts.copy() tz_ts.index = tz_ts.tz_localize("GMT").tz_convert("CET") - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = tz_ts.plot.area(stacked=False, x_compat=True, ax=ax) xmin, xmax = ax.get_xlim() line = ax.get_lines()[0].get_data(orig=False)[0] assert xmin <= line[0] assert xmax >= line[-1] - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) tm.close() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = tz_ts.plot.area(stacked=False, secondary_y=True, ax=ax) xmin, xmax = ax.get_xlim() line = ax.get_lines()[0].get_data(orig=False)[0] assert xmin <= line[0] assert xmax >= line[-1] - self._check_ticks_props(ax, xrot=0) + _check_ticks_props(ax, xrot=0) def test_area_sharey_dont_overwrite(self, ts): # GH37942 - fig, (ax1, ax2) = self.plt.subplots(1, 2, sharey=True) + fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2, sharey=True) abs(ts).plot(ax=ax1, kind="area") abs(ts).plot(ax=ax2, kind="area") - assert self.get_y_axis(ax1).joined(ax1, ax2) - assert self.get_y_axis(ax2).joined(ax1, ax2) + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) def test_label(self): s = Series([1, 2]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot(label="LABEL", legend=True, ax=ax) - self._check_legend_labels(ax, labels=["LABEL"]) - self.plt.close() - _, ax = self.plt.subplots() + _check_legend_labels(ax, labels=["LABEL"]) + mpl.pyplot.close() + _, ax = mpl.pyplot.subplots() ax = s.plot(legend=True, ax=ax) - self._check_legend_labels(ax, labels=[""]) - self.plt.close() + _check_legend_labels(ax, labels=[""]) + mpl.pyplot.close() # get name from index s.name = "NAME" - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot(legend=True, ax=ax) - self._check_legend_labels(ax, labels=["NAME"]) - self.plt.close() + _check_legend_labels(ax, labels=["NAME"]) + mpl.pyplot.close() # override the default - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot(legend=True, label="LABEL", ax=ax) - self._check_legend_labels(ax, labels=["LABEL"]) - self.plt.close() + _check_legend_labels(ax, labels=["LABEL"]) + mpl.pyplot.close() # Add lebel info, but don't draw - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot(legend=False, label="LABEL", ax=ax) assert ax.get_legend() is None # Hasn't been drawn ax.legend() # draw it - self._check_legend_labels(ax, labels=["LABEL"]) + _check_legend_labels(ax, labels=["LABEL"]) def test_boolean(self): # GH 23719 @@ -231,11 +241,11 @@ def test_line_area_nan_series(self, index): def test_line_use_index_false(self): s = Series([1, 2, 3], index=["a", "b", "c"]) s.index.name = "The Index" - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot(use_index=False, ax=ax) label = ax.get_xlabel() assert label == "" - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax2 = s.plot.bar(use_index=False, ax=ax) label2 = ax2.get_xlabel() assert label2 == "" @@ -248,12 +258,12 @@ def test_line_use_index_false(self): def test_bar_log(self): expected = np.array([1e-1, 1e0, 1e1, 1e2, 1e3, 1e4]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = Series([200, 500]).plot.bar(log=True, ax=ax) tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), expected) tm.close() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = Series([200, 500]).plot.barh(log=True, ax=ax) tm.assert_numpy_array_equal(ax.xaxis.get_ticklocs(), expected) tm.close() @@ -261,7 +271,7 @@ def test_bar_log(self): # GH 9905 expected = np.array([1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = Series([0.1, 0.01, 0.001]).plot(log=True, kind="bar", ax=ax) ymin = 0.0007943282347242822 ymax = 0.12589254117941673 @@ -271,7 +281,7 @@ def test_bar_log(self): tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), expected) tm.close() - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = Series([0.1, 0.01, 0.001]).plot(log=True, kind="barh", ax=ax) res = ax.get_xlim() tm.assert_almost_equal(res[0], ymin) @@ -280,9 +290,9 @@ def test_bar_log(self): def test_bar_ignore_index(self): df = Series([1, 2, 3, 4], index=["a", "b", "c", "d"]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot.bar(use_index=False, ax=ax) - self._check_text_labels(ax.get_xticklabels(), ["0", "1", "2", "3"]) + _check_text_labels(ax.get_xticklabels(), ["0", "1", "2", "3"]) def test_bar_user_colors(self): s = Series([1, 2, 3, 4]) @@ -299,13 +309,13 @@ def test_bar_user_colors(self): def test_rotation(self): df = DataFrame(np.random.randn(5, 5)) # Default rot 0 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() axes = df.plot(ax=ax) - self._check_ticks_props(axes, xrot=0) + _check_ticks_props(axes, xrot=0) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() axes = df.plot(rot=30, ax=ax) - self._check_ticks_props(axes, xrot=30) + _check_ticks_props(axes, xrot=30) def test_irregular_datetime(self): from pandas.plotting._matplotlib.converter import DatetimeConverter @@ -313,19 +323,19 @@ def test_irregular_datetime(self): rng = date_range("1/1/2000", "3/1/2000") rng = rng[[0, 1, 2, 3, 5, 9, 10, 11, 12]] ser = Series(np.random.randn(len(rng)), rng) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ser.plot(ax=ax) xp = DatetimeConverter.convert(datetime(1999, 1, 1), "", ax) ax.set_xlim("1/1/1999", "1/1/2001") assert xp == ax.get_xlim()[0] - self._check_ticks_props(ax, xrot=30) + _check_ticks_props(ax, xrot=30) def test_unsorted_index_xlim(self): ser = Series( [0.0, 1.0, np.nan, 3.0, 4.0, 5.0, 6.0], index=[1.0, 0.0, 3.0, 2.0, np.nan, 3.0, 2.0], ) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ser.plot(ax=ax) xmin, xmax = ax.get_xlim() lines = ax.get_lines() @@ -339,26 +349,26 @@ def test_pie_series(self): np.random.randint(1, 5), index=["a", "b", "c", "d", "e"], name="YLABEL" ) ax = _check_plot_works(series.plot.pie) - self._check_text_labels(ax.texts, series.index) + _check_text_labels(ax.texts, series.index) assert ax.get_ylabel() == "YLABEL" # without wedge labels ax = _check_plot_works(series.plot.pie, labels=None) - self._check_text_labels(ax.texts, [""] * 5) + _check_text_labels(ax.texts, [""] * 5) # with less colors than elements color_args = ["r", "g", "b"] ax = _check_plot_works(series.plot.pie, colors=color_args) color_expected = ["r", "g", "b", "r", "g"] - self._check_colors(ax.patches, facecolors=color_expected) + _check_colors(ax.patches, facecolors=color_expected) # with labels and colors labels = ["A", "B", "C", "D", "E"] color_args = ["r", "g", "b", "c", "m"] ax = _check_plot_works(series.plot.pie, labels=labels, colors=color_args) - self._check_text_labels(ax.texts, labels) - self._check_colors(ax.patches, facecolors=color_args) + _check_text_labels(ax.texts, labels) + _check_colors(ax.patches, facecolors=color_args) # with autopct and fontsize ax = _check_plot_works( @@ -366,7 +376,7 @@ def test_pie_series(self): ) pcts = [f"{s*100:.2f}" for s in series.values / series.sum()] expected_texts = list(chain.from_iterable(zip(series.index, pcts))) - self._check_text_labels(ax.texts, expected_texts) + _check_text_labels(ax.texts, expected_texts) for t in ax.texts: assert t.get_fontsize() == 7 @@ -378,11 +388,11 @@ def test_pie_series(self): # includes nan series = Series([1, 2, np.nan, 4], index=["a", "b", "c", "d"], name="YLABEL") ax = _check_plot_works(series.plot.pie) - self._check_text_labels(ax.texts, ["a", "b", "", "d"]) + _check_text_labels(ax.texts, ["a", "b", "", "d"]) def test_pie_nan(self): s = Series([1, np.nan, 1, 1]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot.pie(legend=True, ax=ax) expected = ["0", "", "2", "3"] result = [x.get_text() for x in ax.texts] @@ -394,59 +404,59 @@ def test_df_series_secondary_legend(self): s = Series(np.random.randn(30), name="x") # primary -> secondary (without passing ax) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot(ax=ax) s.plot(legend=True, secondary_y=True, ax=ax) # both legends are drawn on left ax # left and right axis must be visible - self._check_legend_labels(ax, labels=["a", "b", "c", "x (right)"]) + _check_legend_labels(ax, labels=["a", "b", "c", "x (right)"]) assert ax.get_yaxis().get_visible() assert ax.right_ax.get_yaxis().get_visible() tm.close() # primary -> secondary (with passing ax) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot(ax=ax) s.plot(ax=ax, legend=True, secondary_y=True) # both legends are drawn on left ax # left and right axis must be visible - self._check_legend_labels(ax, labels=["a", "b", "c", "x (right)"]) + _check_legend_labels(ax, labels=["a", "b", "c", "x (right)"]) assert ax.get_yaxis().get_visible() assert ax.right_ax.get_yaxis().get_visible() tm.close() # secondary -> secondary (without passing ax) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot(secondary_y=True, ax=ax) s.plot(legend=True, secondary_y=True, ax=ax) # both legends are drawn on left ax # left axis must be invisible and right axis must be visible expected = ["a (right)", "b (right)", "c (right)", "x (right)"] - self._check_legend_labels(ax.left_ax, labels=expected) + _check_legend_labels(ax.left_ax, labels=expected) assert not ax.left_ax.get_yaxis().get_visible() assert ax.get_yaxis().get_visible() tm.close() # secondary -> secondary (with passing ax) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot(secondary_y=True, ax=ax) s.plot(ax=ax, legend=True, secondary_y=True) # both legends are drawn on left ax # left axis must be invisible and right axis must be visible expected = ["a (right)", "b (right)", "c (right)", "x (right)"] - self._check_legend_labels(ax.left_ax, expected) + _check_legend_labels(ax.left_ax, expected) assert not ax.left_ax.get_yaxis().get_visible() assert ax.get_yaxis().get_visible() tm.close() # secondary -> secondary (with passing ax) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = df.plot(secondary_y=True, mark_right=False, ax=ax) s.plot(ax=ax, legend=True, secondary_y=True) # both legends are drawn on left ax # left axis must be invisible and right axis must be visible expected = ["a", "b", "c", "x (right)"] - self._check_legend_labels(ax.left_ax, expected) + _check_legend_labels(ax.left_ax, expected) assert not ax.left_ax.get_yaxis().get_visible() assert ax.get_yaxis().get_visible() tm.close() @@ -468,7 +478,7 @@ def test_secondary_logy(self, input_logy, expected_scale): def test_plot_fails_with_dupe_color_and_style(self): x = Series(np.random.randn(2)) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() msg = ( "Cannot pass 'style' string with a color symbol and 'color' keyword " "argument. Please use one or the other or pass 'style' without a color " @@ -485,10 +495,10 @@ def test_kde_kwargs(self, ts): _check_plot_works(ts.plot.kde, bw_method=None, ind=np.int_(20)) _check_plot_works(ts.plot.kde, bw_method=0.5, ind=sample_points) _check_plot_works(ts.plot.density, bw_method=0.5, ind=sample_points) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.kde(logy=True, bw_method=0.5, ind=sample_points, ax=ax) - self._check_ax_scales(ax, yaxis="log") - self._check_text_labels(ax.yaxis.get_label(), "Density") + _check_ax_scales(ax, yaxis="log") + _check_text_labels(ax.yaxis.get_label(), "Density") @td.skip_if_no_scipy def test_kde_missing_vals(self): @@ -501,13 +511,13 @@ def test_kde_missing_vals(self): @pytest.mark.xfail(reason="Api changed in 3.6.0") def test_boxplot_series(self, ts): - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ts.plot.box(logy=True, ax=ax) - self._check_ax_scales(ax, yaxis="log") + _check_ax_scales(ax, yaxis="log") xlabels = ax.get_xticklabels() - self._check_text_labels(xlabels, [ts.name]) + _check_text_labels(xlabels, [ts.name]) ylabels = ax.get_yticklabels() - self._check_text_labels(ylabels, [""] * len(ylabels)) + _check_text_labels(ylabels, [""] * len(ylabels)) @td.skip_if_no_scipy @pytest.mark.parametrize( @@ -516,17 +526,17 @@ def test_boxplot_series(self, ts): ) def test_kind_both_ways(self, kind): s = Series(range(3)) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s.plot(kind=kind, ax=ax) - self.plt.close() - _, ax = self.plt.subplots() + mpl.pyplot.close() + _, ax = mpl.pyplot.subplots() getattr(s.plot, kind)() - self.plt.close() + mpl.pyplot.close() @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds) def test_invalid_plot_data(self, kind): s = Series(list("abcd")) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() msg = "no numeric data to plot" with pytest.raises(TypeError, match=msg): s.plot(kind=kind, ax=ax) @@ -540,7 +550,7 @@ def test_valid_object_plot(self, kind): @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds) def test_partially_invalid_plot_data(self, kind): s = Series(["a", "b", 1.0, 2]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() msg = "no numeric data to plot" with pytest.raises(TypeError, match=msg): s.plot(kind=kind, ax=ax) @@ -589,18 +599,18 @@ def test_errorbar_plot(self): kinds = ["line", "bar"] for kind in kinds: ax = _check_plot_works(s.plot, yerr=Series(s_err), kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(s.plot, yerr=s_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(s.plot, yerr=s_err.tolist(), kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(s.plot, yerr=d_err, kind=kind) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(s.plot, xerr=0.2, yerr=0.2, kind=kind) - self._check_has_errorbars(ax, xerr=1, yerr=1) + _check_has_errorbars(ax, xerr=1, yerr=1) ax = _check_plot_works(s.plot, xerr=s_err) - self._check_has_errorbars(ax, xerr=1, yerr=0) + _check_has_errorbars(ax, xerr=1, yerr=0) # test time series plotting ix = date_range("1/1/2000", "1/1/2001", freq="M") @@ -609,9 +619,9 @@ def test_errorbar_plot(self): td_err = DataFrame(np.abs(np.random.randn(12, 2)), index=ix, columns=["x", "y"]) ax = _check_plot_works(ts.plot, yerr=ts_err) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(ts.plot, yerr=td_err) - self._check_has_errorbars(ax, xerr=0, yerr=1) + _check_has_errorbars(ax, xerr=0, yerr=1) # check incorrect lengths and types with tm.external_error_raised(ValueError): @@ -630,7 +640,7 @@ def test_table(self, series): @td.skip_if_no_scipy def test_series_grid_settings(self): # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792 - self._check_grid_settings( + _check_grid_settings( Series([1, 2, 3]), plotting.PlotAccessor._series_kinds + plotting.PlotAccessor._common_kinds, ) @@ -686,39 +696,39 @@ def test_standard_colors_all(self): def test_series_plot_color_kwargs(self): # GH1890 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = Series(np.arange(12) + 1).plot(color="green", ax=ax) - self._check_colors(ax.get_lines(), linecolors=["green"]) + _check_colors(ax.get_lines(), linecolors=["green"]) def test_time_series_plot_color_kwargs(self): # #1890 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = Series(np.arange(12) + 1, index=date_range("1/1/2000", periods=12)).plot( color="green", ax=ax ) - self._check_colors(ax.get_lines(), linecolors=["green"]) + _check_colors(ax.get_lines(), linecolors=["green"]) def test_time_series_plot_color_with_empty_kwargs(self): import matplotlib as mpl - def_colors = self._unpack_cycler(mpl.rcParams) + def_colors = _unpack_cycler(mpl.rcParams) index = date_range("1/1/2000", periods=12) s = Series(np.arange(1, 13), index=index) ncolors = 3 - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() for i in range(ncolors): ax = s.plot(ax=ax) - self._check_colors(ax.get_lines(), linecolors=def_colors[:ncolors]) + _check_colors(ax.get_lines(), linecolors=def_colors[:ncolors]) def test_xticklabels(self): # GH11529 s = Series(np.arange(10), index=[f"P{i:02d}" for i in range(10)]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = s.plot(xticks=[0, 3, 5, 9], ax=ax) exp = [f"P{i:02d}" for i in [0, 3, 5, 9]] - self._check_text_labels(ax.get_xticklabels(), exp) + _check_text_labels(ax.get_xticklabels(), exp) def test_xtick_barPlot(self): # GH28172 @@ -749,12 +759,12 @@ def test_custom_business_day_freq(self): ) def test_plot_accessor_updates_on_inplace(self): ser = Series([1, 2, 3, 4]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() ax = ser.plot(ax=ax) before = ax.xaxis.get_ticklocs() ser.drop([0, 1], inplace=True) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() after = ax.xaxis.get_ticklocs() tm.assert_numpy_array_equal(before, after) @@ -763,7 +773,7 @@ def test_plot_xlim_for_series(self, kind): # test if xlim is also correctly plotted in Series for line and area # GH 27686 s = Series([2, 3]) - _, ax = self.plt.subplots() + _, ax = mpl.pyplot.subplots() s.plot(kind=kind, ax=ax) xlims = ax.get_xlim() @@ -853,5 +863,5 @@ def test_series_none_color(self): # GH51953 series = Series([1, 2, 3]) ax = series.plot(color=None) - expected = self._unpack_cycler(self.plt.rcParams)[:1] - self._check_colors(ax.get_lines(), linecolors=expected) + expected = _unpack_cycler(mpl.pyplot.rcParams)[:1] + _check_colors(ax.get_lines(), linecolors=expected)
Replaces the plotting tests' `TestPlotBase` methods into individual testing function and fixtures where appropriate
https://api.github.com/repos/pandas-dev/pandas/pulls/53550
2023-06-07T03:41:27Z
2023-06-09T17:13:47Z
2023-06-09T17:13:47Z
2023-06-09T17:13:50Z
Backport PR #53532 on branch 2.0.x (BUG: Series.str.split(expand=True) for ArrowDtype(pa.string()))
diff --git a/doc/source/whatsnew/v2.0.3.rst b/doc/source/whatsnew/v2.0.3.rst index 2c63d7d20ed1c..89c64b02e0cb5 100644 --- a/doc/source/whatsnew/v2.0.3.rst +++ b/doc/source/whatsnew/v2.0.3.rst @@ -22,6 +22,8 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Bug in :func:`read_csv` when defining ``dtype`` with ``bool[pyarrow]`` for the ``"c"`` and ``"python"`` engines (:issue:`53390`) +- Bug in :meth:`Series.str.split` and :meth:`Series.str.rsplit` with ``expand=True`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`53532`) +- .. --------------------------------------------------------------------------- .. _whatsnew_203.other: diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 699a32fe0c028..e544bde16da9c 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -273,14 +273,40 @@ def _wrap_result( if isinstance(result.dtype, ArrowDtype): import pyarrow as pa + from pandas.compat import pa_version_under11p0 + from pandas.core.arrays.arrow.array import ArrowExtensionArray - max_len = pa.compute.max( - result._data.combine_chunks().value_lengths() - ).as_py() - if result.isna().any(): + value_lengths = result._data.combine_chunks().value_lengths() + max_len = pa.compute.max(value_lengths).as_py() + min_len = pa.compute.min(value_lengths).as_py() + if result._hasna: # ArrowExtensionArray.fillna doesn't work for list scalars - result._data = result._data.fill_null([None] * max_len) + result = ArrowExtensionArray( + result._data.fill_null([None] * max_len) + ) + if min_len < max_len: + # append nulls to each scalar list element up to max_len + if not pa_version_under11p0: + result = ArrowExtensionArray( + pa.compute.list_slice( + result._data, + start=0, + stop=max_len, + return_fixed_size_list=True, + ) + ) + else: + all_null = np.full(max_len, fill_value=None, dtype=object) + values = result.to_numpy() + new_values = [] + for row in values: + if len(row) < max_len: + nulls = all_null[: max_len - len(row)] + row = np.append(row, nulls) + new_values.append(row) + pa_type = result._data.type + result = ArrowExtensionArray(pa.array(new_values, type=pa_type)) if name is not None: labels = name else: diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 3efb59fc6afce..03734626c8f95 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -2315,6 +2315,15 @@ def test_str_split(): ) tm.assert_frame_equal(result, expected) + result = ser.str.split("1", expand=True) + expected = pd.DataFrame( + { + 0: ArrowExtensionArray(pa.array(["a", "a2cbcb", None])), + 1: ArrowExtensionArray(pa.array(["cbcb", None, None])), + } + ) + tm.assert_frame_equal(result, expected) + def test_str_rsplit(): # GH 52401 @@ -2340,6 +2349,15 @@ def test_str_rsplit(): ) tm.assert_frame_equal(result, expected) + result = ser.str.rsplit("1", expand=True) + expected = pd.DataFrame( + { + 0: ArrowExtensionArray(pa.array(["a", "a2cbcb", None])), + 1: ArrowExtensionArray(pa.array(["cbcb", None, None])), + } + ) + tm.assert_frame_equal(result, expected) + def test_str_unsupported_extract(): ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
null
https://api.github.com/repos/pandas-dev/pandas/pulls/53549
2023-06-07T01:54:12Z
2023-06-07T15:46:13Z
2023-06-07T15:46:13Z
2023-06-08T02:31:44Z
CI/DEPS: Add xfail(strict=False) to related unstable sorting changes in Numpy 1.25
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 0c0b312c11c48..b63f3f28b8f6c 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -424,7 +424,7 @@ def lexsort_indexer( def nargsort( items: ArrayLike | Index | Series, - kind: SortKind = "stable", + kind: SortKind = "quicksort", ascending: bool = True, na_position: str = "last", key: Callable | None = None, diff --git a/pandas/tests/frame/methods/test_nlargest.py b/pandas/tests/frame/methods/test_nlargest.py index b5c33a41dd780..17dea51263222 100644 --- a/pandas/tests/frame/methods/test_nlargest.py +++ b/pandas/tests/frame/methods/test_nlargest.py @@ -9,6 +9,7 @@ import pandas as pd import pandas._testing as tm +from pandas.util.version import Version @pytest.fixture @@ -155,7 +156,7 @@ def test_nlargest_n_identical_values(self): [["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]], ) @pytest.mark.parametrize("n", range(1, 6)) - def test_nlargest_n_duplicate_index(self, df_duplicates, n, order): + def test_nlargest_n_duplicate_index(self, df_duplicates, n, order, request): # GH#13412 df = df_duplicates @@ -165,6 +166,18 @@ def test_nlargest_n_duplicate_index(self, df_duplicates, n, order): result = df.nlargest(n, order) expected = df.sort_values(order, ascending=False).head(n) + if Version(np.__version__) >= Version("1.25") and ( + (order == ["a"] and n in (1, 2, 3, 4)) or (order == ["a", "b"]) and n == 5 + ): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) tm.assert_frame_equal(result, expected) def test_nlargest_duplicate_keep_all_ties(self): diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index e2877acbdd040..4c41632040dbe 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -12,6 +12,7 @@ date_range, ) import pandas._testing as tm +from pandas.util.version import Version class TestDataFrameSortValues: @@ -849,9 +850,22 @@ def ascending(request): class TestSortValuesLevelAsStr: def test_sort_index_level_and_column_label( - self, df_none, df_idx, sort_names, ascending + self, df_none, df_idx, sort_names, ascending, request ): # GH#14353 + if ( + Version(np.__version__) >= Version("1.25") + and request.node.callspec.id == "df_idx0-inner-True" + ): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) # Get index levels from df_idx levels = df_idx.index.names @@ -867,7 +881,7 @@ def test_sort_index_level_and_column_label( tm.assert_frame_equal(result, expected) def test_sort_column_level_and_index_label( - self, df_none, df_idx, sort_names, ascending + self, df_none, df_idx, sort_names, ascending, request ): # GH#14353 @@ -886,6 +900,17 @@ def test_sort_column_level_and_index_label( # Compute result by transposing and sorting on axis=1. result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1) + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + tm.assert_frame_equal(result, expected) def test_sort_values_validate_ascending_for_value_error(self): diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index 5477ad75a56f7..78c8b6b236b65 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -21,6 +21,7 @@ to_datetime, ) import pandas._testing as tm +from pandas.util.version import Version def tests_value_counts_index_names_category_column(): @@ -246,8 +247,18 @@ def test_bad_subset(education_df): gp.value_counts(subset=["country"]) -def test_basic(education_df): +def test_basic(education_df, request): # gh43564 + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) result = education_df.groupby("country")[["gender", "education"]].value_counts( normalize=True ) @@ -285,7 +296,7 @@ def _frame_value_counts(df, keys, normalize, sort, ascending): @pytest.mark.parametrize("as_index", [True, False]) @pytest.mark.parametrize("frame", [True, False]) def test_against_frame_and_seriesgroupby( - education_df, groupby, normalize, name, sort, ascending, as_index, frame + education_df, groupby, normalize, name, sort, ascending, as_index, frame, request ): # test all parameters: # - Use column, array or function as by= parameter @@ -295,6 +306,16 @@ def test_against_frame_and_seriesgroupby( # - 3-way compare against: # - apply with :meth:`~DataFrame.value_counts` # - `~SeriesGroupBy.value_counts` + if Version(np.__version__) >= Version("1.25") and frame and sort and normalize: + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) by = { "column": "country", "array": education_df["country"].values, @@ -456,8 +477,18 @@ def nulls_df(): ], ) def test_dropna_combinations( - nulls_df, group_dropna, count_dropna, expected_rows, expected_values + nulls_df, group_dropna, count_dropna, expected_rows, expected_values, request ): + if Version(np.__version__) >= Version("1.25") and not group_dropna: + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) gp = nulls_df.groupby(["A", "B"], dropna=group_dropna) result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna) columns = DataFrame() @@ -548,10 +579,20 @@ def test_data_frame_value_counts_dropna( ], ) def test_categorical_single_grouper_with_only_observed_categories( - education_df, as_index, observed, normalize, name, expected_data + education_df, as_index, observed, normalize, name, expected_data, request ): # Test single categorical grouper with only observed grouping categories # when non-groupers are also categorical + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) gp = education_df.astype("category").groupby( "country", as_index=as_index, observed=observed @@ -647,10 +688,21 @@ def assert_categorical_single_grouper( ], ) def test_categorical_single_grouper_observed_true( - education_df, as_index, normalize, name, expected_data + education_df, as_index, normalize, name, expected_data, request ): # GH#46357 + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + expected_index = [ ("FR", "male", "low"), ("FR", "female", "high"), @@ -717,10 +769,21 @@ def test_categorical_single_grouper_observed_true( ], ) def test_categorical_single_grouper_observed_false( - education_df, as_index, normalize, name, expected_data + education_df, as_index, normalize, name, expected_data, request ): # GH#46357 + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + expected_index = [ ("FR", "male", "low"), ("FR", "female", "high"), @@ -858,10 +921,22 @@ def test_categorical_multiple_groupers( ], ) def test_categorical_non_groupers( - education_df, as_index, observed, normalize, name, expected_data + education_df, as_index, observed, normalize, name, expected_data, request ): # GH#46357 Test non-observed categories are included in the result, # regardless of `observed` + + if Version(np.__version__) >= Version("1.25"): + request.node.add_marker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + education_df = education_df.copy() education_df["gender"] = education_df["gender"].astype("category") education_df["education"] = education_df["education"].astype("category")
Notes: * Due to https://github.com/numpy/numpy/pull/23707 and our usage of an unstable sorting algorithm (quicksort) everywhere and the CI runners able to use AVX-512
https://api.github.com/repos/pandas-dev/pandas/pulls/53548
2023-06-07T01:03:26Z
2023-06-08T18:09:06Z
2023-06-08T18:09:06Z
2023-12-04T19:14:06Z
TST: Remove inheritance from pandas/tests/indexes
diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index d7fdbb39f3e69..232d966e39a01 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -14,27 +14,15 @@ CategoricalIndex, Index, ) -from pandas.tests.indexes.common import Base -class TestCategoricalIndex(Base): - _index_cls = CategoricalIndex - +class TestCategoricalIndex: @pytest.fixture def simple_index(self) -> CategoricalIndex: - return self._index_cls(list("aabbca"), categories=list("cab"), ordered=False) - - @pytest.fixture - def index(self): - return tm.makeCategoricalIndex(100) - - def create_index(self, *, categories=None, ordered=False): - if categories is None: - categories = list("cab") - return CategoricalIndex(list("aabbca"), categories=categories, ordered=ordered) + return CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) def test_can_hold_identifiers(self): - idx = self.create_index(categories=list("abcd")) + idx = CategoricalIndex(list("aabbca"), categories=None, ordered=False) key = idx[0] assert idx._can_hold_identifiers_and_holds_name(key) is True @@ -247,12 +235,13 @@ def test_identical(self): assert ci1.identical(ci1.copy()) assert not ci1.identical(ci2) - def test_ensure_copied_data(self, index): + def test_ensure_copied_data(self): # gh-12309: Check the "copy" argument of each # Index.__new__ is honored. # # Must be tested separately from other indexes because # self.values is not an ndarray. + index = tm.makeCategoricalIndex(10) result = CategoricalIndex(index.values, copy=True) tm.assert_index_equal(index, result) @@ -267,18 +256,8 @@ def test_frame_repr(self): expected = " A\na 1\nb 2\nc 3" assert result == expected - def test_reindex_base(self): - # See test_reindex.py - pass - - def test_map_str(self): - # See test_map.py - pass - class TestCategoricalIndex2: - # Tests that are not overriding a test in Base - def test_view_i8(self): # GH#25464 ci = tm.makeCategoricalIndex(100) diff --git a/pandas/tests/indexes/datetimes/test_datetimelike.py b/pandas/tests/indexes/datetimes/test_datetimelike.py index 31ec8c497299e..a6bee20d3d3ec 100644 --- a/pandas/tests/indexes/datetimes/test_datetimelike.py +++ b/pandas/tests/indexes/datetimes/test_datetimelike.py @@ -1,39 +1,10 @@ """ generic tests from the Datetimelike class """ -import pytest +from pandas import date_range -from pandas import ( - DatetimeIndex, - date_range, -) -import pandas._testing as tm -from pandas.tests.indexes.datetimelike import DatetimeLike - -class TestDatetimeIndex(DatetimeLike): - _index_cls = DatetimeIndex - - @pytest.fixture - def simple_index(self) -> DatetimeIndex: - return date_range("20130101", periods=5) - - @pytest.fixture( - params=[tm.makeDateIndex(10), date_range("20130110", periods=10, freq="-1D")], - ids=["index_inc", "index_dec"], - ) - def index(self, request): - return request.param - - def test_format(self, simple_index): +class TestDatetimeIndex: + def test_format(self): # GH35439 - idx = simple_index + idx = date_range("20130101", periods=5) expected = [f"{x:%Y-%m-%d}" for x in idx] assert idx.format() == expected - - def test_shift(self): - pass # handled in test_ops - - def test_intersection(self): - pass # handled in test_setops - - def test_union(self): - pass # handled in test_setops diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py index de9d8be21ae60..e0155a13481ac 100644 --- a/pandas/tests/indexes/interval/test_base.py +++ b/pandas/tests/indexes/interval/test_base.py @@ -3,38 +3,24 @@ from pandas import IntervalIndex import pandas._testing as tm -from pandas.tests.indexes.common import Base -class TestBase(Base): +class TestInterval: """ Tests specific to the shared common index tests; unrelated tests should be placed in test_interval.py or the specific test file (e.g. test_astype.py) """ - _index_cls = IntervalIndex - @pytest.fixture def simple_index(self) -> IntervalIndex: - return self._index_cls.from_breaks(range(11), closed="right") + return IntervalIndex.from_breaks(range(11), closed="right") @pytest.fixture def index(self): return tm.makeIntervalIndex(10) - def create_index(self, *, closed="right"): - return IntervalIndex.from_breaks(range(11), closed=closed) - - def test_repr_max_seq_item_setting(self): - # override base test: not a valid repr as we use interval notation - pass - - def test_repr_roundtrip(self): - # override base test: not a valid repr as we use interval notation - pass - def test_take(self, closed): - index = self.create_index(closed=closed) + index = IntervalIndex.from_breaks(range(11), closed=closed) result = index.take(range(10)) tm.assert_index_equal(result, index) diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py index 284b7f782a3f2..4080dc7081771 100644 --- a/pandas/tests/indexes/numeric/test_numeric.py +++ b/pandas/tests/indexes/numeric/test_numeric.py @@ -7,12 +7,9 @@ Series, ) import pandas._testing as tm -from pandas.tests.indexes.common import NumericBase -class TestFloatNumericIndex(NumericBase): - _index_cls = Index - +class TestFloatNumericIndex: @pytest.fixture(params=[np.float64, np.float32]) def dtype(self, request): return request.param @@ -20,7 +17,7 @@ def dtype(self, request): @pytest.fixture def simple_index(self, dtype): values = np.arange(5, dtype=dtype) - return self._index_cls(values) + return Index(values) @pytest.fixture( params=[ @@ -32,15 +29,15 @@ def simple_index(self, dtype): ids=["mixed", "float", "mixed_dec", "float_dec"], ) def index(self, request, dtype): - return self._index_cls(request.param, dtype=dtype) + return Index(request.param, dtype=dtype) @pytest.fixture def mixed_index(self, dtype): - return self._index_cls([1.5, 2, 3, 4, 5], dtype=dtype) + return Index([1.5, 2, 3, 4, 5], dtype=dtype) @pytest.fixture def float_index(self, dtype): - return self._index_cls([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype) + return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype) def test_repr_roundtrip(self, index): tm.assert_index_equal(eval(repr(index)), index, exact=True) @@ -49,16 +46,16 @@ def check_coerce(self, a, b, is_float_index=True): assert a.equals(b) tm.assert_index_equal(a, b, exact=False) if is_float_index: - assert isinstance(b, self._index_cls) + assert isinstance(b, Index) else: assert type(b) is Index def test_constructor_from_list_no_dtype(self): - index = self._index_cls([1.5, 2.5, 3.5]) + index = Index([1.5, 2.5, 3.5]) assert index.dtype == np.float64 def test_constructor(self, dtype): - index_cls = self._index_cls + index_cls = Index # explicit construction index = index_cls([1, 2, 3, 4, 5], dtype=dtype) @@ -97,7 +94,7 @@ def test_constructor(self, dtype): assert pd.isna(result.values).all() def test_constructor_invalid(self): - index_cls = self._index_cls + index_cls = Index cls_name = index_cls.__name__ # invalid msg = ( @@ -131,7 +128,7 @@ def test_type_coercion_fail(self, any_int_numpy_dtype): Index([1, 2, 3.5], dtype=any_int_numpy_dtype) def test_equals_numeric(self): - index_cls = self._index_cls + index_cls = Index idx = index_cls([1.0, 2.0]) assert idx.equals(idx) @@ -156,7 +153,7 @@ def test_equals_numeric(self): ), ) def test_equals_numeric_other_index_type(self, other): - idx = self._index_cls([1.0, 2.0]) + idx = Index([1.0, 2.0]) assert idx.equals(other) assert other.equals(idx) @@ -198,13 +195,13 @@ def test_lookups_datetimelike_values(self, vals, dtype): assert isinstance(result, type(expected)) and result == expected def test_doesnt_contain_all_the_things(self): - idx = self._index_cls([np.nan]) + idx = Index([np.nan]) assert not idx.isin([0]).item() assert not idx.isin([1]).item() assert idx.isin([np.nan]).item() def test_nan_multiple_containment(self): - index_cls = self._index_cls + index_cls = Index idx = index_cls([1.0, np.nan]) tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False])) @@ -215,7 +212,7 @@ def test_nan_multiple_containment(self): tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False])) def test_fillna_float64(self): - index_cls = self._index_cls + index_cls = Index # GH 11343 idx = Index([1.0, np.nan, 3.0], dtype=float, name="x") # can't downcast @@ -231,11 +228,17 @@ def test_fillna_float64(self): tm.assert_index_equal(idx.fillna("obj"), exp, exact=True) -class NumericInt(NumericBase): - _index_cls = Index +class TestNumericInt: + @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8, np.uint64]) + def dtype(self, request): + return request.param + + @pytest.fixture + def simple_index(self, dtype): + return Index(range(0, 20, 2), dtype=dtype) def test_is_monotonic(self): - index_cls = self._index_cls + index_cls = Index index = index_cls([1, 2, 3, 4]) assert index.is_monotonic_increasing is True @@ -257,7 +260,7 @@ def test_is_monotonic(self): assert index._is_strictly_monotonic_decreasing is True def test_is_strictly_monotonic(self): - index_cls = self._index_cls + index_cls = Index index = index_cls([1, 1, 2, 3]) assert index.is_monotonic_increasing is True @@ -303,7 +306,7 @@ def test_cant_or_shouldnt_cast(self, dtype): # can't data = ["foo", "bar", "baz"] with pytest.raises(ValueError, match=msg): - self._index_cls(data, dtype=dtype) + Index(data, dtype=dtype) def test_view_index(self, simple_index): index = simple_index @@ -315,27 +318,17 @@ def test_prevent_casting(self, simple_index): assert result.dtype == np.object_ -class TestIntNumericIndex(NumericInt): +class TestIntNumericIndex: @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8]) def dtype(self, request): return request.param - @pytest.fixture - def simple_index(self, dtype): - return self._index_cls(range(0, 20, 2), dtype=dtype) - - @pytest.fixture( - params=[range(0, 20, 2), range(19, -1, -1)], ids=["index_inc", "index_dec"] - ) - def index(self, request, dtype): - return self._index_cls(request.param, dtype=dtype) - def test_constructor_from_list_no_dtype(self): - index = self._index_cls([1, 2, 3]) + index = Index([1, 2, 3]) assert index.dtype == np.int64 def test_constructor(self, dtype): - index_cls = self._index_cls + index_cls = Index # scalar raise Exception msg = ( @@ -379,7 +372,7 @@ def test_constructor(self, dtype): tm.assert_index_equal(idx, expected) def test_constructor_corner(self, dtype): - index_cls = self._index_cls + index_cls = Index arr = np.array([1, 2, 3, 4], dtype=object) @@ -426,7 +419,7 @@ def test_constructor_np_unsigned(self, any_unsigned_int_numpy_dtype): def test_coerce_list(self): # coerce things arr = Index([1, 2, 3, 4]) - assert isinstance(arr, self._index_cls) + assert isinstance(arr, Index) # but not if explicit dtype passed arr = Index([1, 2, 3, 4], dtype=object) @@ -436,10 +429,8 @@ def test_coerce_list(self): class TestFloat16Index: # float 16 indexes not supported # GH 49535 - _index_cls = Index - def test_constructor(self): - index_cls = self._index_cls + index_cls = Index dtype = np.float16 msg = "float16 indexes are not supported" @@ -471,27 +462,6 @@ def test_constructor(self): index_cls(np.array([np.nan]), dtype=dtype) -class TestUIntNumericIndex(NumericInt): - @pytest.fixture(params=[np.uint64]) - def dtype(self, request): - return request.param - - @pytest.fixture - def simple_index(self, dtype): - # compat with shared Int64/Float64 tests - return self._index_cls(np.arange(5, dtype=dtype)) - - @pytest.fixture( - params=[ - [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25], - [2**63 + 25, 2**63 + 20, 2**63 + 15, 2**63 + 10, 2**63], - ], - ids=["index_inc", "index_dec"], - ) - def index(self, request): - return self._index_cls(request.param, dtype=np.uint64) - - @pytest.mark.parametrize( "box", [list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)], diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index e5c85edfaaffa..412d66de11ba3 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -14,30 +14,9 @@ period_range, ) import pandas._testing as tm -from pandas.tests.indexes.datetimelike import DatetimeLike -class TestPeriodIndex(DatetimeLike): - _index_cls = PeriodIndex - - @pytest.fixture - def simple_index(self) -> Index: - return period_range("20130101", periods=5, freq="D") - - @pytest.fixture( - params=[ - tm.makePeriodIndex(10), - period_range("20130101", periods=10, freq="D")[::-1], - ], - ids=["index_inc", "index_dec"], - ) - def index(self, request): - return request.param - - def test_where(self): - # This is handled in test_indexing - pass - +class TestPeriodIndex: def test_make_time_series(self): index = period_range(freq="A", start="1/1/2001", end="12/1/2009") series = Series(1, index=index) @@ -147,42 +126,9 @@ def test_period_index_length(self): with pytest.raises(ValueError, match=msg): PeriodIndex(vals) - def test_fields(self): - # year, month, day, hour, minute - # second, weekofyear, week, dayofweek, weekday, dayofyear, quarter - # qyear - pi = period_range(freq="A", start="1/1/2001", end="12/1/2005") - self._check_all_fields(pi) - - pi = period_range(freq="Q", start="1/1/2001", end="12/1/2002") - self._check_all_fields(pi) - - pi = period_range(freq="M", start="1/1/2001", end="1/1/2002") - self._check_all_fields(pi) - - pi = period_range(freq="D", start="12/1/2001", end="6/1/2001") - self._check_all_fields(pi) - - pi = period_range(freq="B", start="12/1/2001", end="6/1/2001") - self._check_all_fields(pi) - - pi = period_range(freq="H", start="12/31/2001", end="1/1/2002 23:00") - self._check_all_fields(pi) - - pi = period_range(freq="Min", start="12/31/2001", end="1/1/2002 00:20") - self._check_all_fields(pi) - - pi = period_range( - freq="S", start="12/31/2001 00:00:00", end="12/31/2001 00:05:00" - ) - self._check_all_fields(pi) - - end_intv = Period("2006-12-31", "W") - i1 = period_range(end=end_intv, periods=10) - self._check_all_fields(i1) - - def _check_all_fields(self, periodindex): - fields = [ + @pytest.mark.parametrize( + "field", + [ "year", "month", "day", @@ -198,24 +144,40 @@ def _check_all_fields(self, periodindex): "quarter", "qyear", "days_in_month", - ] - + ], + ) + @pytest.mark.parametrize( + "periodindex", + [ + period_range(freq="A", start="1/1/2001", end="12/1/2005"), + period_range(freq="Q", start="1/1/2001", end="12/1/2002"), + period_range(freq="M", start="1/1/2001", end="1/1/2002"), + period_range(freq="D", start="12/1/2001", end="6/1/2001"), + period_range(freq="B", start="12/1/2001", end="6/1/2001"), + period_range(freq="H", start="12/31/2001", end="1/1/2002 23:00"), + period_range(freq="Min", start="12/31/2001", end="1/1/2002 00:20"), + period_range( + freq="S", start="12/31/2001 00:00:00", end="12/31/2001 00:05:00" + ), + period_range(end=Period("2006-12-31", "W"), periods=10), + ], + ) + def test_fields(self, periodindex, field): periods = list(periodindex) ser = Series(periodindex) - for field in fields: - field_idx = getattr(periodindex, field) - assert len(periodindex) == len(field_idx) - for x, val in zip(periods, field_idx): - assert getattr(x, field) == val + field_idx = getattr(periodindex, field) + assert len(periodindex) == len(field_idx) + for x, val in zip(periods, field_idx): + assert getattr(x, field) == val - if len(ser) == 0: - continue + if len(ser) == 0: + return - field_s = getattr(ser.dt, field) - assert len(periodindex) == len(field_s) - for x, val in zip(periods, field_s): - assert getattr(x, field) == val + field_s = getattr(ser.dt, field) + assert len(periodindex) == len(field_s) + for x, val in zip(periods, field_s): + assert getattr(x, field) == val def test_is_(self): create_index = lambda: period_range(freq="A", start="1/1/2001", end="12/1/2009") @@ -241,10 +203,6 @@ def test_index_unique(self): tm.assert_index_equal(idx.unique(), expected) assert idx.nunique() == 3 - def test_shift(self): - # This is tested in test_arithmetic - pass - def test_negative_ordinals(self): Period(ordinal=-1000, freq="A") Period(ordinal=0, freq="A") @@ -307,7 +265,7 @@ def test_map(self): def test_format_empty(self): # GH35712 - empty_idx = self._index_cls([], freq="A") + empty_idx = PeriodIndex([], freq="A") assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index b964fb43f1560..06ad1f3c865c8 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -9,42 +9,19 @@ RangeIndex, ) import pandas._testing as tm -from pandas.tests.indexes.common import NumericBase # aliases to make some tests easier to read RI = RangeIndex -class TestRangeIndex(NumericBase): - _index_cls = RangeIndex - - @pytest.fixture - def dtype(self): - return np.int64 - - @pytest.fixture( - params=["uint64", "float64", "category", "datetime64", "object"], - ) - def invalid_dtype(self, request): - return request.param - +class TestRangeIndex: @pytest.fixture def simple_index(self): - return self._index_cls(start=0, stop=20, step=2) + return RangeIndex(start=0, stop=20, step=2) - @pytest.fixture( - params=[ - RangeIndex(start=0, stop=20, step=2, name="foo"), - RangeIndex(start=18, stop=-1, step=-2, name="bar"), - ], - ids=["index_inc", "index_dec"], - ) - def index(self, request): - return request.param - - def test_constructor_unwraps_index(self, dtype): - result = self._index_cls(1, 3) - expected = np.array([1, 2], dtype=dtype) + def test_constructor_unwraps_index(self): + result = RangeIndex(1, 3) + expected = np.array([1, 2], dtype=np.int64) tm.assert_numpy_array_equal(result._data, expected) def test_can_hold_identifiers(self, simple_index): @@ -330,16 +307,18 @@ def test_is_monotonic(self): assert index._is_strictly_monotonic_increasing is True assert index._is_strictly_monotonic_decreasing is True - def test_equals_range(self): - equiv_pairs = [ + @pytest.mark.parametrize( + "left,right", + [ (RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)), (RangeIndex(0), RangeIndex(1, -1, 3)), (RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)), (RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)), - ] - for left, right in equiv_pairs: - assert left.equals(right) - assert right.equals(left) + ], + ) + def test_equals_range(self, left, right): + assert left.equals(right) + assert right.equals(left) def test_logical_compat(self, simple_index): idx = simple_index @@ -408,6 +387,14 @@ def test_slice_keep_name(self): idx = RangeIndex(1, 2, name="asdf") assert idx.name == idx[1:].name + @pytest.mark.parametrize( + "index", + [ + RangeIndex(start=0, stop=20, step=2, name="foo"), + RangeIndex(start=18, stop=-1, step=-2, name="bar"), + ], + ids=["index_inc", "index_dec"], + ) def test_has_duplicates(self, index): assert index.is_unique assert not index.has_duplicates @@ -440,10 +427,6 @@ def test_min_fitting_element(self): result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num) assert big_num == result - def test_pickle_compat_construction(self): - # RangeIndex() is a valid constructor - pass - def test_slice_specialised(self, simple_index): index = simple_index index.name = "foo" @@ -511,8 +494,9 @@ def test_len_specialised(self, step): index = RangeIndex(stop, start, step) assert len(index) == 0 - @pytest.fixture( - params=[ + @pytest.mark.parametrize( + "indices, expected", + [ ([RI(1, 12, 5)], RI(1, 12, 5)), ([RI(0, 6, 4)], RI(0, 6, 4)), ([RI(1, 3), RI(3, 7)], RI(1, 7)), @@ -532,17 +516,10 @@ def test_len_specialised(self, step): ([RI(3), Index([-1, 3.1, 15.0])], Index([0, 1, 2, -1, 3.1, 15.0])), ([RI(3), Index(["a", None, 14])], Index([0, 1, 2, "a", None, 14])), ([RI(3, 1), Index(["a", None, 14])], Index(["a", None, 14])), - ] + ], ) - def appends(self, request): - """Inputs and expected outputs for RangeIndex.append test""" - return request.param - - def test_append(self, appends): + def test_append(self, indices, expected): # GH16212 - - indices, expected = appends - result = indices[0].append(indices[1:]) tm.assert_index_equal(result, expected, exact=True) @@ -575,7 +552,7 @@ def test_engineless_lookup(self): def test_format_empty(self): # GH35712 - empty_idx = self._index_cls(0) + empty_idx = RangeIndex(0) assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] @@ -610,9 +587,6 @@ def test_sort_values_key(self): expected = Index([4, 8, 6, 0, 2], dtype="int64") tm.assert_index_equal(result, expected, check_exact=True) - def test_cast_string(self, dtype): - pytest.skip("casting of strings not relevant for RangeIndex") - def test_range_index_rsub_by_const(self): # GH#53255 result = 3 - RangeIndex(0, 4, 1) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index db317a819c520..41a0d25af7b52 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -39,15 +39,12 @@ ensure_index, ensure_index_from_sequences, ) -from pandas.tests.indexes.common import Base -class TestIndex(Base): - _index_cls = Index - +class TestIndex: @pytest.fixture def simple_index(self) -> Index: - return self._index_cls(list("abcde")) + return Index(list("abcde")) def test_can_hold_identifiers(self, simple_index): index = simple_index @@ -1303,19 +1300,13 @@ def test_index_round(self, decimals, expected_results): tm.assert_index_equal(result, expected) -class TestMixedIntIndex(Base): +class TestMixedIntIndex: # Mostly the tests from common.py for which the results differ # in py2 and py3 because ints and strings are uncomparable in py3 # (GH 13514) - _index_cls = Index - @pytest.fixture def simple_index(self) -> Index: - return self._index_cls([0, "a", 1, "b", 2, "c"]) - - @pytest.fixture(params=[[0, "a", 1, "b", 2, "c"]], ids=["mixedIndex"]) - def index(self, request): - return Index(request.param) + return Index([0, "a", 1, "b", 2, "c"]) def test_argsort(self, simple_index): index = simple_index diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/test_datetimelike.py similarity index 81% rename from pandas/tests/indexes/datetimelike.py rename to pandas/tests/indexes/test_datetimelike.py index 1a050e606277b..b315b1ac141cd 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/test_datetimelike.py @@ -5,10 +5,33 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.indexes.common import Base -class DatetimeLike(Base): +class TestDatetimeLike: + @pytest.fixture( + params=[ + pd.period_range("20130101", periods=5, freq="D"), + pd.TimedeltaIndex( + [ + "0 days 01:00:00", + "1 days 01:00:00", + "2 days 01:00:00", + "3 days 01:00:00", + "4 days 01:00:00", + ], + dtype="timedelta64[ns]", + freq="D", + ), + pd.DatetimeIndex( + ["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"], + dtype="datetime64[ns]", + freq="D", + ), + ] + ) + def simple_index(self, request): + return request.param + def test_isin(self, simple_index): index = simple_index[:4] result = index.isin(index) @@ -45,7 +68,7 @@ def test_shift_empty(self, simple_index): def test_str(self, simple_index): # test the string repr - idx = simple_index + idx = simple_index.copy() idx.name = "foo" assert f"length={len(idx)}" not in str(idx) assert "'foo'" in str(idx) @@ -63,11 +86,11 @@ def test_view(self, simple_index): idx = simple_index idx_view = idx.view("i8") - result = self._index_cls(idx) + result = type(simple_index)(idx) tm.assert_index_equal(result, idx) - idx_view = idx.view(self._index_cls) - result = self._index_cls(idx) + idx_view = idx.view(type(simple_index)) + result = type(simple_index)(idx) tm.assert_index_equal(result, idx_view) def test_map_callable(self, simple_index): diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/test_old_base.py similarity index 86% rename from pandas/tests/indexes/common.py rename to pandas/tests/indexes/test_old_base.py index 73de3ee60339a..ff23c8a8ba5a4 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/test_old_base.py @@ -8,7 +8,10 @@ from pandas._libs.tslibs import Timestamp -from pandas.core.dtypes.common import is_integer_dtype +from pandas.core.dtypes.common import ( + is_integer_dtype, + is_numeric_dtype, +) from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd @@ -24,27 +27,52 @@ Series, TimedeltaIndex, isna, + period_range, ) import pandas._testing as tm from pandas.core.arrays import BaseMaskedArray -class Base: - """ - Base class for index sub-class tests. - """ - - _index_cls: type[Index] - - @pytest.fixture - def simple_index(self): - raise NotImplementedError("Method not implemented") - - def create_index(self) -> Index: - raise NotImplementedError("Method not implemented") +class TestBase: + @pytest.fixture( + params=[ + RangeIndex(start=0, stop=20, step=2), + Index(np.arange(5, dtype=np.float64)), + Index(np.arange(5, dtype=np.float32)), + Index(np.arange(5, dtype=np.uint64)), + Index(range(0, 20, 2), dtype=np.int64), + Index(range(0, 20, 2), dtype=np.int32), + Index(range(0, 20, 2), dtype=np.int16), + Index(range(0, 20, 2), dtype=np.int8), + Index(list("abcde")), + Index([0, "a", 1, "b", 2, "c"]), + period_range("20130101", periods=5, freq="D"), + TimedeltaIndex( + [ + "0 days 01:00:00", + "1 days 01:00:00", + "2 days 01:00:00", + "3 days 01:00:00", + "4 days 01:00:00", + ], + dtype="timedelta64[ns]", + freq="D", + ), + DatetimeIndex( + ["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"], + dtype="datetime64[ns]", + freq="D", + ), + IntervalIndex.from_breaks(range(11), closed="right"), + ] + ) + def simple_index(self, request): + return request.param - def test_pickle_compat_construction(self): + def test_pickle_compat_construction(self, simple_index): # need an object to create with + if isinstance(simple_index, RangeIndex): + pytest.skip("RangeIndex() is a valid constructor") msg = "|".join( [ r"Index\(\.\.\.\) must be called with a collection of some " @@ -58,10 +86,12 @@ def test_pickle_compat_construction(self): ] ) with pytest.raises(TypeError, match=msg): - self._index_cls() + type(simple_index)() def test_shift(self, simple_index): # GH8083 test the base class for shift + if isinstance(simple_index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)): + pytest.skip("Tested in test_ops/test_arithmetic") idx = simple_index msg = ( f"This method is only implemented for DatetimeIndex, PeriodIndex and " @@ -82,7 +112,7 @@ def test_constructor_name_unhashable(self, simple_index): def test_create_index_existing_name(self, simple_index): # GH11193, when an existing index is passed, and a new name is not # specified, the new index should inherit the previous object name - expected = simple_index + expected = simple_index.copy() if not isinstance(expected, MultiIndex): expected.name = "foo" result = Index(expected) @@ -138,6 +168,10 @@ def test_numeric_compat(self, simple_index): assert not isinstance(idx, MultiIndex) if type(idx) is Index: return + if is_numeric_dtype(simple_index.dtype) or isinstance( + simple_index, TimedeltaIndex + ): + pytest.skip("Tested elsewhere.") typ = type(idx._data).__name__ cls = type(idx).__name__ @@ -175,6 +209,12 @@ def test_numeric_compat(self, simple_index): 1 // idx def test_logical_compat(self, simple_index): + if ( + isinstance(simple_index, RangeIndex) + or is_numeric_dtype(simple_index.dtype) + or simple_index.dtype == object + ): + pytest.skip("Tested elsewhere.") idx = simple_index with pytest.raises(TypeError, match="cannot perform all"): idx.all() @@ -182,11 +222,15 @@ def test_logical_compat(self, simple_index): idx.any() def test_repr_roundtrip(self, simple_index): + if isinstance(simple_index, IntervalIndex): + pytest.skip(f"Not a valid repr for {type(simple_index).__name__}") idx = simple_index tm.assert_index_equal(eval(repr(idx)), idx) def test_repr_max_seq_item_setting(self, simple_index): # GH10182 + if isinstance(simple_index, IntervalIndex): + pytest.skip(f"Not a valid repr for {type(simple_index).__name__}") idx = simple_index idx = idx.repeat(50) with pd.option_context("display.max_seq_items", None): @@ -330,6 +374,10 @@ def test_numpy_repeat(self, simple_index): np.repeat(idx, rep, axis=0) def test_where(self, listlike_box, simple_index): + if isinstance(simple_index, (IntervalIndex, PeriodIndex)) or is_numeric_dtype( + simple_index.dtype + ): + pytest.skip("Tested elsewhere.") klass = listlike_box idx = simple_index @@ -497,13 +545,19 @@ def test_equals_op(self, simple_index): def test_format(self, simple_index): # GH35439 + if is_numeric_dtype(simple_index.dtype) or isinstance( + simple_index, DatetimeIndex + ): + pytest.skip("Tested elsewhere.") idx = simple_index expected = [str(x) for x in idx] assert idx.format() == expected - def test_format_empty(self): + def test_format_empty(self, simple_index): # GH35712 - empty_idx = self._index_cls([]) + if isinstance(simple_index, (PeriodIndex, RangeIndex)): + pytest.skip("Tested elsewhere") + empty_idx = type(simple_index)([]) assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] @@ -580,6 +634,8 @@ def test_join_self_unique(self, join_type, simple_index): def test_map(self, simple_index): # callable + if isinstance(simple_index, (TimedeltaIndex, PeriodIndex)): + pytest.skip("Tested elsewhere.") idx = simple_index result = idx.map(lambda x: x) @@ -601,6 +657,8 @@ def test_map_dictlike(self, mapper, simple_index): # non-unique values, which raises. This _should_ work fine for # CategoricalIndex. pytest.skip(f"skipping tests for {type(idx)}") + elif isinstance(idx, (DatetimeIndex, TimedeltaIndex, PeriodIndex)): + pytest.skip("Tested elsewhere.") identity = mapper(idx.values, idx) @@ -619,6 +677,8 @@ def test_map_dictlike(self, mapper, simple_index): def test_map_str(self, simple_index): # GH 31202 + if isinstance(simple_index, CategoricalIndex): + pytest.skip("See test_map.py") idx = simple_index result = idx.map(str) expected = Index([str(x) for x in idx], dtype=object) @@ -682,6 +742,8 @@ def test_engine_reference_cycle(self, simple_index): def test_getitem_2d_deprecated(self, simple_index): # GH#30588, GH#31479 + if isinstance(simple_index, IntervalIndex): + pytest.skip("Tested elsewhere") idx = simple_index msg = "Multi-dimensional indexing" with pytest.raises(ValueError, match=msg): @@ -834,30 +896,43 @@ def test_is_object_is_deprecated(self, simple_index): idx.is_object() -class NumericBase(Base): - """ - Base class for numeric index (incl. RangeIndex) sub-class tests. - """ +class TestNumericBase: + @pytest.fixture( + params=[ + RangeIndex(start=0, stop=20, step=2), + Index(np.arange(5, dtype=np.float64)), + Index(np.arange(5, dtype=np.float32)), + Index(np.arange(5, dtype=np.uint64)), + Index(range(0, 20, 2), dtype=np.int64), + Index(range(0, 20, 2), dtype=np.int32), + Index(range(0, 20, 2), dtype=np.int16), + Index(range(0, 20, 2), dtype=np.int8), + ] + ) + def simple_index(self, request): + return request.param - def test_constructor_unwraps_index(self, dtype): - index_cls = self._index_cls + def test_constructor_unwraps_index(self, simple_index): + if isinstance(simple_index, RangeIndex): + pytest.skip("Tested elsewhere.") + index_cls = type(simple_index) + dtype = simple_index.dtype idx = Index([1, 2], dtype=dtype) result = index_cls(idx) expected = np.array([1, 2], dtype=idx.dtype) tm.assert_numpy_array_equal(result._data, expected) - def test_where(self): - # Tested in numeric.test_indexing - pass - def test_can_hold_identifiers(self, simple_index): idx = simple_index key = idx[0] assert idx._can_hold_identifiers_and_holds_name(key) is False - def test_view(self, dtype): - index_cls = self._index_cls + def test_view(self, simple_index): + if isinstance(simple_index, RangeIndex): + pytest.skip("Tested elsewhere.") + index_cls = type(simple_index) + dtype = simple_index.dtype idx = index_cls([], dtype=dtype, name="Foo") idx_view = idx.view() @@ -871,14 +946,13 @@ def test_view(self, dtype): def test_format(self, simple_index): # GH35439 + if isinstance(simple_index, DatetimeIndex): + pytest.skip("Tested elsewhere") idx = simple_index max_width = max(len(str(x)) for x in idx) expected = [str(x).ljust(max_width) for x in idx] assert idx.format() == expected - def test_numeric_compat(self): - pass # override Base method - def test_insert_non_na(self, simple_index): # GH#43921 inserting an element that we know we can hold should # not change dtype or type (except for RangeIndex) @@ -905,10 +979,10 @@ def test_insert_na(self, nulls_fixture, simple_index): result = index.insert(1, na_val) tm.assert_index_equal(result, expected, exact=True) - def test_arithmetic_explicit_conversions(self): + def test_arithmetic_explicit_conversions(self, simple_index): # GH 8608 # add/sub are overridden explicitly for Float/Int Index - index_cls = self._index_cls + index_cls = type(simple_index) if index_cls is RangeIndex: idx = RangeIndex(5) else: @@ -939,7 +1013,9 @@ def test_astype_to_complex(self, complex_dtype, simple_index): assert type(result) is Index and result.dtype == complex_dtype - def test_cast_string(self, dtype): - result = self._index_cls(["0", "1", "2"], dtype=dtype) - expected = self._index_cls([0, 1, 2], dtype=dtype) + def test_cast_string(self, simple_index): + if isinstance(simple_index, RangeIndex): + pytest.skip("casting of strings not relevant for RangeIndex") + result = type(simple_index)(["0", "1", "2"], dtype=simple_index.dtype) + expected = type(simple_index)([0, 1, 2], dtype=simple_index.dtype) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 0cbc4bde4b07f..8e71d1fd9078f 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -3,45 +3,22 @@ import numpy as np import pytest -import pandas as pd from pandas import ( Index, NaT, Series, Timedelta, - TimedeltaIndex, timedelta_range, ) import pandas._testing as tm from pandas.core.arrays import TimedeltaArray -from pandas.tests.indexes.datetimelike import DatetimeLike -randn = np.random.randn - - -class TestTimedeltaIndex(DatetimeLike): - _index_cls = TimedeltaIndex - - @pytest.fixture - def simple_index(self) -> TimedeltaIndex: - index = pd.to_timedelta(range(5), unit="d")._with_freq("infer") - assert index.freq == "D" - ret = index + pd.offsets.Hour(1) - assert ret.freq == "D" - return ret +class TestTimedeltaIndex: @pytest.fixture def index(self): return tm.makeTimedeltaIndex(10) - def test_numeric_compat(self): - # Dummy method to override super's version; this test is now done - # in test_arithmetic.py - pass - - def test_shift(self): - pass # this is handled in test_arithmetic.py - def test_misc_coverage(self): rng = timedelta_range("1 day", periods=5) result = rng.groupby(rng.days)
Replaced the inheritance structure of `pandas/tests/indexes` to use parameterization to make them more independent. Tests are skipped appropriately where they are tested in the old subclass.
https://api.github.com/repos/pandas-dev/pandas/pulls/53544
2023-06-06T20:18:38Z
2023-06-06T22:31:36Z
2023-06-06T22:31:36Z
2023-06-06T22:31:39Z
TST: Clean up finalize tests
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 9dfa2c8a5a90a..f23952b91044f 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -153,7 +153,7 @@ ({"A": ["a", "b", "c"], "B": [1, 3, 5], "C": [2, 4, 6]},), operator.methodcaller("melt", id_vars=["A"], value_vars=["B"]), ), - pytest.param((pd.DataFrame, frame_data, operator.methodcaller("map", lambda x: x))), + (pd.DataFrame, frame_data, operator.methodcaller("map", lambda x: x)), pytest.param( ( pd.DataFrame, @@ -162,9 +162,7 @@ ), marks=not_implemented_mark, ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("round", 2)), - ), + (pd.DataFrame, frame_data, operator.methodcaller("round", 2)), (pd.DataFrame, frame_data, operator.methodcaller("corr")), pytest.param( (pd.DataFrame, frame_data, operator.methodcaller("cov")), @@ -172,19 +170,13 @@ pytest.mark.filterwarnings("ignore::RuntimeWarning"), ], ), - pytest.param( - ( - pd.DataFrame, - frame_data, - operator.methodcaller("corrwith", pd.DataFrame(*frame_data)), - ), - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("count")), - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("nunique")), + ( + pd.DataFrame, + frame_data, + operator.methodcaller("corrwith", pd.DataFrame(*frame_data)), ), + (pd.DataFrame, frame_data, operator.methodcaller("count")), + (pd.DataFrame, frame_data, operator.methodcaller("nunique")), (pd.DataFrame, frame_data, operator.methodcaller("idxmin")), (pd.DataFrame, frame_data, operator.methodcaller("idxmax")), (pd.DataFrame, frame_data, operator.methodcaller("mode")), @@ -192,33 +184,25 @@ (pd.Series, [0], operator.methodcaller("mode")), marks=not_implemented_mark, ), - pytest.param( - ( - pd.DataFrame, - frame_data, - operator.methodcaller("quantile", numeric_only=True), - ), + ( + pd.DataFrame, + frame_data, + operator.methodcaller("quantile", numeric_only=True), ), - pytest.param( - ( - pd.DataFrame, - frame_data, - operator.methodcaller("quantile", q=[0.25, 0.75], numeric_only=True), - ), + ( + pd.DataFrame, + frame_data, + operator.methodcaller("quantile", q=[0.25, 0.75], numeric_only=True), ), - pytest.param( - ( - pd.DataFrame, - ({"A": [pd.Timedelta(days=1), pd.Timedelta(days=2)]},), - operator.methodcaller("quantile", numeric_only=False), - ), + ( + pd.DataFrame, + ({"A": [pd.Timedelta(days=1), pd.Timedelta(days=2)]},), + operator.methodcaller("quantile", numeric_only=False), ), - pytest.param( - ( - pd.DataFrame, - ({"A": [np.datetime64("2022-01-01"), np.datetime64("2022-01-02")]},), - operator.methodcaller("quantile", numeric_only=True), - ), + ( + pd.DataFrame, + ({"A": [np.datetime64("2022-01-01"), np.datetime64("2022-01-02")]},), + operator.methodcaller("quantile", numeric_only=True), ), ( pd.DataFrame, @@ -230,18 +214,12 @@ ({"A": [1]}, [pd.Timestamp("2000")]), operator.methodcaller("to_period", freq="D"), ), - pytest.param( - (pd.DataFrame, frame_mi_data, operator.methodcaller("isin", [1])), - ), - pytest.param( - (pd.DataFrame, frame_mi_data, operator.methodcaller("isin", pd.Series([1]))), - ), - pytest.param( - ( - pd.DataFrame, - frame_mi_data, - operator.methodcaller("isin", pd.DataFrame({"A": [1]})), - ), + (pd.DataFrame, frame_mi_data, operator.methodcaller("isin", [1])), + (pd.DataFrame, frame_mi_data, operator.methodcaller("isin", pd.Series([1]))), + ( + pd.DataFrame, + frame_mi_data, + operator.methodcaller("isin", pd.DataFrame({"A": [1]})), ), (pd.DataFrame, frame_mi_data, operator.methodcaller("droplevel", "A")), (pd.DataFrame, frame_data, operator.methodcaller("pop", "A")), @@ -261,7 +239,7 @@ (pd.Series, [1], operator.inv), (pd.DataFrame, frame_data, abs), (pd.Series, [1], abs), - pytest.param((pd.DataFrame, frame_data, round)), + (pd.DataFrame, frame_data, round), (pd.Series, [1], round), (pd.DataFrame, frame_data, operator.methodcaller("take", [0, 0])), (pd.DataFrame, frame_mi_data, operator.methodcaller("xs", "a")), @@ -383,17 +361,13 @@ (pd.Series, ([1, 2],), operator.methodcaller("pct_change")), (pd.DataFrame, frame_data, operator.methodcaller("pct_change")), (pd.Series, ([1],), operator.methodcaller("transform", lambda x: x - x.min())), - pytest.param( - ( - pd.DataFrame, - frame_mi_data, - operator.methodcaller("transform", lambda x: x - x.min()), - ), + ( + pd.DataFrame, + frame_mi_data, + operator.methodcaller("transform", lambda x: x - x.min()), ), (pd.Series, ([1],), operator.methodcaller("apply", lambda x: x)), - pytest.param( - (pd.DataFrame, frame_mi_data, operator.methodcaller("apply", lambda x: x)), - ), + (pd.DataFrame, frame_mi_data, operator.methodcaller("apply", lambda x: x)), # Cumulative reductions (pd.Series, ([1],), operator.methodcaller("cumsum")), (pd.DataFrame, frame_data, operator.methodcaller("cumsum")), @@ -402,12 +376,8 @@ (pd.DataFrame, frame_data, operator.methodcaller("any")), marks=not_implemented_mark, ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("sum")), - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("std")), - ), + (pd.DataFrame, frame_data, operator.methodcaller("sum")), + (pd.DataFrame, frame_data, operator.methodcaller("std")), pytest.param( (pd.DataFrame, frame_data, operator.methodcaller("mean")), marks=not_implemented_mark,
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53543
2023-06-06T19:07:49Z
2023-06-07T00:17:23Z
2023-06-07T00:17:23Z
2023-06-07T13:56:29Z
BUG: Fix metadata propagation in reductions
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index f1e370a0b8316..97de305077545 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -770,8 +770,10 @@ Styler Metadata ^^^^^^^^ +- Fixed metadata propagation in :meth:`DataFrame.max`, :meth:`DataFrame.min`, :meth:`DataFrame.prod`, :meth:`DataFrame.mean`, :meth:`Series.mode`, :meth:`DataFrame.median`, :meth:`DataFrame.sem`, :meth:`DataFrame.skew`, :meth:`DataFrame.kurt` (:issue:`28283`) - Fixed metadata propagation in :meth:`DataFrame.squeeze`, and :meth:`DataFrame.describe` (:issue:`28283`) - Fixed metadata propagation in :meth:`DataFrame.std` (:issue:`28283`) +- Other ^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5207fd5db1c4d..f7fe51b1eee0a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11137,12 +11137,13 @@ def any( # type: ignore[override] bool_only: bool = False, skipna: bool = True, **kwargs, - ) -> Series: - # error: Incompatible return value type (got "Union[Series, bool]", - # expected "Series") - return self._logical_func( # type: ignore[return-value] + ) -> Series | bool: + result = self._logical_func( "any", nanops.nanany, axis, bool_only, skipna, **kwargs ) + if isinstance(result, Series): + result = result.__finalize__(self, method="any") + return result @doc(make_doc("all", ndim=2)) def all( @@ -11151,12 +11152,13 @@ def all( bool_only: bool = False, skipna: bool = True, **kwargs, - ) -> Series: - # error: Incompatible return value type (got "Union[Series, bool]", - # expected "Series") - return self._logical_func( # type: ignore[return-value] + ) -> Series | bool: + result = self._logical_func( "all", nanops.nanall, axis, bool_only, skipna, **kwargs ) + if isinstance(result, Series): + result = result.__finalize__(self, method="all") + return result @doc(make_doc("min", ndim=2)) def min( @@ -11166,7 +11168,10 @@ def min( numeric_only: bool = False, **kwargs, ): - return super().min(axis, skipna, numeric_only, **kwargs) + result = super().min(axis, skipna, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="min") + return result @doc(make_doc("max", ndim=2)) def max( @@ -11176,7 +11181,10 @@ def max( numeric_only: bool = False, **kwargs, ): - return super().max(axis, skipna, numeric_only, **kwargs) + result = super().max(axis, skipna, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="max") + return result @doc(make_doc("sum", ndim=2)) def sum( @@ -11199,7 +11207,8 @@ def prod( min_count: int = 0, **kwargs, ): - return super().prod(axis, skipna, numeric_only, min_count, **kwargs) + result = super().prod(axis, skipna, numeric_only, min_count, **kwargs) + return result.__finalize__(self, method="prod") @doc(make_doc("mean", ndim=2)) def mean( @@ -11209,7 +11218,10 @@ def mean( numeric_only: bool = False, **kwargs, ): - return super().mean(axis, skipna, numeric_only, **kwargs) + result = super().mean(axis, skipna, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="mean") + return result @doc(make_doc("median", ndim=2)) def median( @@ -11219,7 +11231,10 @@ def median( numeric_only: bool = False, **kwargs, ): - return super().median(axis, skipna, numeric_only, **kwargs) + result = super().median(axis, skipna, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="median") + return result @doc(make_doc("sem", ndim=2)) def sem( @@ -11230,7 +11245,10 @@ def sem( numeric_only: bool = False, **kwargs, ): - return super().sem(axis, skipna, ddof, numeric_only, **kwargs) + result = super().sem(axis, skipna, ddof, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="sem") + return result @doc(make_doc("var", ndim=2)) def var( @@ -11241,7 +11259,10 @@ def var( numeric_only: bool = False, **kwargs, ): - return super().var(axis, skipna, ddof, numeric_only, **kwargs) + result = super().var(axis, skipna, ddof, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="var") + return result @doc(make_doc("std", ndim=2)) def std( @@ -11252,8 +11273,10 @@ def std( numeric_only: bool = False, **kwargs, ): - result = cast(Series, super().std(axis, skipna, ddof, numeric_only, **kwargs)) - return result.__finalize__(self, method="std") + result = super().std(axis, skipna, ddof, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="std") + return result @doc(make_doc("skew", ndim=2)) def skew( @@ -11263,7 +11286,10 @@ def skew( numeric_only: bool = False, **kwargs, ): - return super().skew(axis, skipna, numeric_only, **kwargs) + result = super().skew(axis, skipna, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="skew") + return result @doc(make_doc("kurt", ndim=2)) def kurt( @@ -11273,7 +11299,10 @@ def kurt( numeric_only: bool = False, **kwargs, ): - return super().kurt(axis, skipna, numeric_only, **kwargs) + result = super().kurt(axis, skipna, numeric_only, **kwargs) + if isinstance(result, Series): + result = result.__finalize__(self, method="kurt") + return result kurtosis = kurt product = prod diff --git a/pandas/core/reshape/encoding.py b/pandas/core/reshape/encoding.py index 8c464c2229515..e30881e1a79c6 100644 --- a/pandas/core/reshape/encoding.py +++ b/pandas/core/reshape/encoding.py @@ -6,7 +6,10 @@ Iterable, ) import itertools -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, + cast, +) import numpy as np @@ -455,10 +458,12 @@ def from_dummies( f"Received 'data' of type: {type(data).__name__}" ) - if data.isna().any().any(): + col_isna_mask = cast(Series, data.isna().any()) + + if col_isna_mask.any(): raise ValueError( "Dummy DataFrame contains NA value in column: " - f"'{data.isna().any().idxmax()}'" + f"'{col_isna_mask.idxmax()}'" ) # index data with a list of all columns that are dummies diff --git a/pandas/core/series.py b/pandas/core/series.py index e6080144627ba..4677dc2274a52 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2202,7 +2202,7 @@ def mode(self, dropna: bool = True) -> Series: # Ensure index is type stable (should always use int index) return self._constructor( res_values, index=range(len(res_values)), name=self.name, copy=False - ) + ).__finalize__(self, method="mode") def unique(self) -> ArrayLike: # pylint: disable=useless-parent-delegation """ diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index f827eaf63a342..1522b83a4f5d0 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -180,10 +180,8 @@ (pd.DataFrame, frame_data, operator.methodcaller("idxmin")), (pd.DataFrame, frame_data, operator.methodcaller("idxmax")), (pd.DataFrame, frame_data, operator.methodcaller("mode")), - pytest.param( - (pd.Series, [0], operator.methodcaller("mode")), - marks=not_implemented_mark, - ), + (pd.Series, [0], operator.methodcaller("mode")), + (pd.DataFrame, frame_data, operator.methodcaller("median")), ( pd.DataFrame, frame_data, @@ -363,17 +361,24 @@ # Cumulative reductions (pd.Series, ([1],), operator.methodcaller("cumsum")), (pd.DataFrame, frame_data, operator.methodcaller("cumsum")), + (pd.Series, ([1],), operator.methodcaller("cummin")), + (pd.DataFrame, frame_data, operator.methodcaller("cummin")), + (pd.Series, ([1],), operator.methodcaller("cummax")), + (pd.DataFrame, frame_data, operator.methodcaller("cummax")), + (pd.Series, ([1],), operator.methodcaller("cumprod")), + (pd.DataFrame, frame_data, operator.methodcaller("cumprod")), # Reductions - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("any")), - marks=not_implemented_mark, - ), + (pd.DataFrame, frame_data, operator.methodcaller("any")), + (pd.DataFrame, frame_data, operator.methodcaller("all")), + (pd.DataFrame, frame_data, operator.methodcaller("min")), + (pd.DataFrame, frame_data, operator.methodcaller("max")), (pd.DataFrame, frame_data, operator.methodcaller("sum")), (pd.DataFrame, frame_data, operator.methodcaller("std")), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("mean")), - marks=not_implemented_mark, - ), + (pd.DataFrame, frame_data, operator.methodcaller("mean")), + (pd.DataFrame, frame_data, operator.methodcaller("prod")), + (pd.DataFrame, frame_data, operator.methodcaller("sem")), + (pd.DataFrame, frame_data, operator.methodcaller("skew")), + (pd.DataFrame, frame_data, operator.methodcaller("kurt")), ]
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53542
2023-06-06T18:57:15Z
2023-08-01T16:56:53Z
2023-08-01T16:56:53Z
2023-08-01T16:57:46Z
CI: Bump builds to 3.11, update numpy nightly wheels location (#53508)
diff --git a/.circleci/config.yml b/.circleci/config.yml index e704c37df3e45..276ff2ee8314a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -6,7 +6,7 @@ jobs: image: ubuntu-2004:2022.04.1 resource_class: arm.large environment: - ENV_FILE: ci/deps/circle-38-arm64.yaml + ENV_FILE: ci/deps/circle-310-arm64.yaml PYTEST_WORKERS: auto PATTERN: "not single_cpu and not slow and not network and not clipboard and not arm_slow and not db" PYTEST_TARGET: "pandas" diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 31e2095624347..888092e2057e1 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -31,14 +31,14 @@ jobs: pattern: [""] include: - name: "Downstream Compat" - env_file: actions-38-downstream_compat.yaml + env_file: actions-311-downstream_compat.yaml pattern: "not slow and not network and not single_cpu" pytest_target: "pandas/tests/test_downstream.py" - name: "Minimum Versions" env_file: actions-38-minimum_versions.yaml pattern: "not slow and not network and not single_cpu" - name: "Locale: it_IT" - env_file: actions-38.yaml + env_file: actions-311.yaml pattern: "not slow and not network and not single_cpu" extra_apt: "language-pack-it" # Use the utf8 version as the default, it has no bad side-effect. @@ -48,7 +48,7 @@ jobs: # It will be temporarily activated during tests with locale.setlocale extra_loc: "it_IT" - name: "Locale: zh_CN" - env_file: actions-38.yaml + env_file: actions-311.yaml pattern: "not slow and not network and not single_cpu" extra_apt: "language-pack-zh-hans" # Use the utf8 version as the default, it has no bad side-effect. @@ -58,7 +58,7 @@ jobs: # It will be temporarily activated during tests with locale.setlocale extra_loc: "zh_CN" - name: "Copy-on-Write" - env_file: actions-310.yaml + env_file: actions-311.yaml pattern: "not slow and not network and not single_cpu" pandas_copy_on_write: "1" - name: "Pypy" @@ -66,7 +66,7 @@ jobs: pattern: "not slow and not network and not single_cpu" test_args: "--max-worker-restart 0" - name: "Numpy Dev" - env_file: actions-310-numpydev.yaml + env_file: actions-311-numpydev.yaml pattern: "not slow and not network and not single_cpu" test_args: "-W error::DeprecationWarning -W error::FutureWarning" # TODO(cython3): Re-enable once next-beta(after beta 1) comes out diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-311-downstream_compat.yaml similarity index 98% rename from ci/deps/actions-38-downstream_compat.yaml rename to ci/deps/actions-311-downstream_compat.yaml index 3c498663c04df..a5c92f81c0406 100644 --- a/ci/deps/actions-38-downstream_compat.yaml +++ b/ci/deps/actions-311-downstream_compat.yaml @@ -3,7 +3,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.8 + - python=3.11 # build dependencies - versioneer[toml] diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-311-numpydev.yaml similarity index 77% rename from ci/deps/actions-310-numpydev.yaml rename to ci/deps/actions-311-numpydev.yaml index ce9d656adc16a..78a89e7a84bd7 100644 --- a/ci/deps/actions-310-numpydev.yaml +++ b/ci/deps/actions-311-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.10 + - python=3.11 # build dependencies - versioneer[toml] @@ -21,7 +21,7 @@ dependencies: - pip: - "cython" - - "--extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple" + - "--extra-index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple" - "--pre" - "numpy" - "scipy" diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-310-arm64.yaml similarity index 98% rename from ci/deps/circle-38-arm64.yaml rename to ci/deps/circle-310-arm64.yaml index 8f309b0781457..a9ac1c98377e7 100644 --- a/ci/deps/circle-38-arm64.yaml +++ b/ci/deps/circle-310-arm64.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.8 + - python=3.10 # build dependencies - versioneer[toml] diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index d3637d177b7f5..a0e4d003e45bd 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1136,7 +1136,7 @@ def _validate(self): if not isinstance(self.win_type, str): raise ValueError(f"Invalid win_type {self.win_type}") signal = import_optional_dependency( - "scipy.signal", extra="Scipy is required to generate window weight." + "scipy.signal.windows", extra="Scipy is required to generate window weight." ) self._scipy_weight_generator = getattr(signal, self.win_type, None) if self._scipy_weight_generator is None:
null
https://api.github.com/repos/pandas-dev/pandas/pulls/53541
2023-06-06T18:16:26Z
2023-06-08T01:54:45Z
2023-06-08T01:54:45Z
2023-06-08T01:54:48Z
DOC: Fixing EX01 - Added more examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 28fec987efd1a..304b4616355db 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -263,16 +263,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.window.ewm.ExponentialMovingWindow.cov \ pandas.api.indexers.BaseIndexer \ pandas.api.indexers.VariableOffsetWindowIndexer \ - pandas.core.groupby.DataFrameGroupBy.__iter__ \ - pandas.core.groupby.SeriesGroupBy.__iter__ \ - pandas.core.groupby.DataFrameGroupBy.groups \ - pandas.core.groupby.SeriesGroupBy.groups \ - pandas.core.groupby.DataFrameGroupBy.indices \ - pandas.core.groupby.SeriesGroupBy.indices \ - pandas.core.groupby.DataFrameGroupBy.get_group \ - pandas.core.groupby.SeriesGroupBy.get_group \ - pandas.core.groupby.DataFrameGroupBy.all \ - pandas.core.groupby.DataFrameGroupBy.any \ pandas.core.groupby.DataFrameGroupBy.count \ pandas.core.groupby.DataFrameGroupBy.cummax \ pandas.core.groupby.DataFrameGroupBy.cummin \ @@ -293,8 +283,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.groupby.DataFrameGroupBy.std \ pandas.core.groupby.DataFrameGroupBy.sum \ pandas.core.groupby.DataFrameGroupBy.var \ - pandas.core.groupby.SeriesGroupBy.all \ - pandas.core.groupby.SeriesGroupBy.any \ pandas.core.groupby.SeriesGroupBy.count \ pandas.core.groupby.SeriesGroupBy.cummax \ pandas.core.groupby.SeriesGroupBy.cummin \ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 6ea5fc437f5a2..5d15be19f34f7 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -720,6 +720,33 @@ def __repr__(self) -> str: def groups(self) -> dict[Hashable, np.ndarray]: """ Dict {group name -> group labels}. + + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + dtype: int64 + >>> ser.groupby(level=0).groups + {'a': ['a', 'a'], 'b': ['b']} + + For DataFrameGroupBy: + + >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"]) + >>> df + a b c + 0 1 2 3 + 1 1 5 6 + 2 7 8 9 + >>> df.groupby(by=["a"]).groups + {1: [0, 1], 7: [2]} """ return self.grouper.groups @@ -733,6 +760,34 @@ def ngroups(self) -> int: def indices(self) -> dict[Hashable, npt.NDArray[np.intp]]: """ Dict {group name -> group indices}. + + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + dtype: int64 + >>> ser.groupby(level=0).indices + {'a': array([0, 1]), 'b': array([2])} + + For DataFrameGroupBy: + + >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["owl", "toucan", "eagle"]) + >>> df + a b c + owl 1 2 3 + toucan 1 5 6 + eagle 7 8 9 + >>> df.groupby(by=["a"]).indices + {1: array([0, 1]), 7: array([2])} """ return self.grouper.indices @@ -867,6 +922,38 @@ def get_group(self, name, obj=None) -> DataFrame | Series: Returns ------- same type as obj + + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + dtype: int64 + >>> ser.groupby(level=0).get_group("a") + a 1 + a 2 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["owl", "toucan", "eagle"]) + >>> df + a b c + owl 1 2 3 + toucan 1 5 6 + eagle 7 8 9 + >>> df.groupby(by=["a"]).get_group(1) + a b c + owl 1 2 3 + toucan 1 5 6 """ if obj is None: obj = self._selected_obj @@ -886,6 +973,47 @@ def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: ------- Generator yielding sequence of (name, subsetted object) for each group + + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 3], index=lst) + >>> ser + a 1 + a 2 + b 3 + dtype: int64 + >>> for x, y in ser.groupby(level=0): + ... print(f'{x}\\n{y}\\n') + a + a 1 + a 2 + dtype: int64 + b + b 3 + dtype: int64 + + For DataFrameGroupBy: + + >>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"]) + >>> df + a b c + 0 1 2 3 + 1 1 5 6 + 2 7 8 9 + >>> for x, y in df.groupby(by=["a"]): + ... print(f'{x}\\n{y}\\n') + (1,) + a b c + 0 1 2 3 + 1 1 5 6 + (7,) + a b c + 2 7 8 9 """ keys = self.keys level = self.level @@ -1787,7 +1915,7 @@ def _obj_1d_constructor(self) -> Callable: @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def any(self, skipna: bool = True): """ Return True if any value in the group is truthful, else False. @@ -1802,6 +1930,38 @@ def any(self, skipna: bool = True): Series or DataFrame DataFrame or Series of boolean values, where a value is True if any element is True within its respective group, False otherwise. + %(see_also)s + Examples + -------- + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 0], index=lst) + >>> ser + a 1 + a 2 + b 0 + dtype: int64 + >>> ser.groupby(level=0).any() + a True + b False + dtype: bool + + For DataFrameGroupBy: + + >>> data = [[1, 0, 3], [1, 0, 6], [7, 1, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["ostrich", "penguin", "parrot"]) + >>> df + a b c + ostrich 1 0 3 + penguin 1 0 6 + parrot 7 1 9 + >>> df.groupby(by=["a"]).any() + b c + a + 1 False True + 7 True True """ return self._cython_agg_general( "any", @@ -1811,7 +1971,7 @@ def any(self, skipna: bool = True): @final @Substitution(name="groupby") - @Appender(_common_see_also) + @Substitution(see_also=_common_see_also) def all(self, skipna: bool = True): """ Return True if all values in the group are truthful, else False. @@ -1826,6 +1986,39 @@ def all(self, skipna: bool = True): Series or DataFrame DataFrame or Series of boolean values, where a value is True if all elements are True within its respective group, False otherwise. + %(see_also)s + Examples + -------- + + For SeriesGroupBy: + + >>> lst = ['a', 'a', 'b'] + >>> ser = pd.Series([1, 2, 0], index=lst) + >>> ser + a 1 + a 2 + b 0 + dtype: int64 + >>> ser.groupby(level=0).all() + a True + b False + dtype: bool + + For DataFrameGroupBy: + + >>> data = [[1, 0, 3], [1, 5, 6], [7, 8, 9]] + >>> df = pd.DataFrame(data, columns=["a", "b", "c"], + ... index=["ostrich", "penguin", "parrot"]) + >>> df + a b c + ostrich 1 0 3 + penguin 1 5 6 + parrot 7 8 9 + >>> df.groupby(by=["a"]).all() + b c + a + 1 False True + 7 True True """ return self._cython_agg_general( "all",
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53540
2023-06-06T17:08:56Z
2023-06-07T15:36:23Z
2023-06-07T15:36:23Z
2023-06-07T17:38:10Z
BUG: Fix metadata propagation in squeeze and describe
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 6bb972c21d927..480548f705763 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -482,6 +482,7 @@ Styler Metadata ^^^^^^^^ +- Fixed metadata propagation in :meth:`DataFrame.squeeze`, and :meth:`DataFrame.describe` (:issue:`28283`) - Fixed metadata propagation in :meth:`DataFrame.std` (:issue:`28283`) Other diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 90a0444872ec7..16287c194db8c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -957,12 +957,15 @@ def squeeze(self, axis: Axis | None = None): 1 """ axes = range(self._AXIS_LEN) if axis is None else (self._get_axis_number(axis),) - return self.iloc[ + result = self.iloc[ tuple( 0 if i in axes and len(a) == 1 else slice(None) for i, a in enumerate(self.axes) ) ] + if isinstance(result, NDFrame): + result = result.__finalize__(self, method="squeeze") + return result # ---------------------------------------------------------------------- # Rename @@ -11137,7 +11140,7 @@ def describe( include=include, exclude=exclude, percentiles=percentiles, - ) + ).__finalize__(self, method="describe") @final def pct_change( diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 9dfa2c8a5a90a..e6a0687155a6a 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -245,10 +245,8 @@ ), (pd.DataFrame, frame_mi_data, operator.methodcaller("droplevel", "A")), (pd.DataFrame, frame_data, operator.methodcaller("pop", "A")), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("squeeze")), - marks=not_implemented_mark, - ), + # Squeeze on columns, otherwise we'll end up with a scalar + (pd.DataFrame, frame_data, operator.methodcaller("squeeze", axis="columns")), (pd.Series, ([1, 2],), operator.methodcaller("squeeze")), (pd.Series, ([1, 2],), operator.methodcaller("rename_axis", index="a")), (pd.DataFrame, frame_data, operator.methodcaller("rename_axis", columns="a")), @@ -372,14 +370,8 @@ ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)), operator.methodcaller("tz_localize", "CET"), ), - pytest.param( - (pd.Series, ([1, 2],), operator.methodcaller("describe")), - marks=not_implemented_mark, - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("describe")), - marks=not_implemented_mark, - ), + (pd.Series, ([1, 2],), operator.methodcaller("describe")), + (pd.DataFrame, frame_data, operator.methodcaller("describe")), (pd.Series, ([1, 2],), operator.methodcaller("pct_change")), (pd.DataFrame, frame_data, operator.methodcaller("pct_change")), (pd.Series, ([1],), operator.methodcaller("transform", lambda x: x - x.min())), @@ -767,7 +759,6 @@ def test_groupby_finalize(obj, method): lambda x: x.agg("sem"), lambda x: x.agg("size"), lambda x: x.agg("ohlc"), - lambda x: x.agg("describe"), ], ) @not_implemented_mark
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53538
2023-06-06T14:34:30Z
2023-06-07T00:31:56Z
2023-06-07T00:31:56Z
2023-06-07T13:56:21Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 94644ca6049c3..28fec987efd1a 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -82,12 +82,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01 --ignore_functions \ pandas.Series.backfill \ pandas.Series.pad \ - pandas.DataFrame.sparse \ - pandas.Series.attrs \ - pandas.Series.plot \ pandas.Series.hist \ - pandas.Series.to_string \ - pandas.errors.AbstractMethodError \ pandas.errors.AccessorRegistrationWarning \ pandas.errors.AttributeConflictWarning \ pandas.errors.DataError \ diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index ede58c86aa78d..6eb1387c63a0a 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -234,6 +234,13 @@ def to_dense(self) -> Series: class SparseFrameAccessor(BaseAccessor, PandasDelegate): """ DataFrame accessor for sparse data. + + Examples + -------- + >>> df = pd.DataFrame({"a": [1, 2, 0, 0], + ... "b": [3, 0, 0, 4]}, dtype="Sparse[int]") + >>> df.sparse.density + 0.5 """ def _validate(self, data): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 90a0444872ec7..aa7dd9006d911 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -334,6 +334,13 @@ def attrs(self) -> dict[Hashable, Any]: See Also -------- DataFrame.flags : Global flags applying to this object. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]) + >>> ser.attrs = {"A": [10, 20, 30]} + >>> ser.attrs + {'A': [10, 20, 30]} """ if self._attrs is None: self._attrs = {} diff --git a/pandas/core/series.py b/pandas/core/series.py index 41a32cb60c39f..9c7110cc21082 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1713,6 +1713,12 @@ def to_string( ------- str or None String representation of Series if ``buf=None``, otherwise None. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]).to_string() + >>> ser + '0 1\\n1 2\\n2 3' """ formatter = fmt.SeriesFormatter( self, diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 1ead53d2cfc4d..438f504968b2d 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -193,6 +193,22 @@ class AccessorRegistrationWarning(Warning): class AbstractMethodError(NotImplementedError): """ Raise this error instead of NotImplementedError for abstract methods. + + Examples + -------- + >>> class Foo: + ... @classmethod + ... def classmethod(cls): + ... raise pd.errors.AbstractMethodError(cls, methodtype="classmethod") + ... def method(self): + ... raise pd.errors.AbstractMethodError(self) + >>> test = Foo.classmethod() + Traceback (most recent call last): + AbstractMethodError: This classmethod must be defined in the concrete class Foo + + >>> test2 = Foo().method() + Traceback (most recent call last): + AbstractMethodError: This classmethod must be defined in the concrete class Foo """ def __init__(self, class_instance, methodtype: str = "method") -> None: diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 38e1be302b054..0f9fd948b6fe5 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -775,6 +775,15 @@ class PlotAccessor(PandasObject): for bar plot layout by `position` keyword. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center) + + Examples + -------- + + .. plot:: + :context: close-figs + + >>> ser = pd.Series([1, 2, 3, 3]) + >>> plot = ser.plot(kind='hist', title="My plot") """ _common_kinds = ("line", "bar", "barh", "kde", "density", "area", "hist", "box")
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53536
2023-06-06T11:29:33Z
2023-06-06T16:55:09Z
2023-06-06T16:55:09Z
2023-06-06T17:07:14Z
BUG: Series.str.split(expand=True) for ArrowDtype(pa.string())
diff --git a/doc/source/whatsnew/v2.0.3.rst b/doc/source/whatsnew/v2.0.3.rst index 2c63d7d20ed1c..89c64b02e0cb5 100644 --- a/doc/source/whatsnew/v2.0.3.rst +++ b/doc/source/whatsnew/v2.0.3.rst @@ -22,6 +22,8 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Bug in :func:`read_csv` when defining ``dtype`` with ``bool[pyarrow]`` for the ``"c"`` and ``"python"`` engines (:issue:`53390`) +- Bug in :meth:`Series.str.split` and :meth:`Series.str.rsplit` with ``expand=True`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`53532`) +- .. --------------------------------------------------------------------------- .. _whatsnew_203.other: diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 08c2736bf9816..127ad5e962b16 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -275,14 +275,40 @@ def _wrap_result( if isinstance(result.dtype, ArrowDtype): import pyarrow as pa + from pandas.compat import pa_version_under11p0 + from pandas.core.arrays.arrow.array import ArrowExtensionArray - max_len = pa.compute.max( - result._pa_array.combine_chunks().value_lengths() - ).as_py() - if result.isna().any(): + value_lengths = result._pa_array.combine_chunks().value_lengths() + max_len = pa.compute.max(value_lengths).as_py() + min_len = pa.compute.min(value_lengths).as_py() + if result._hasna: # ArrowExtensionArray.fillna doesn't work for list scalars - result._pa_array = result._pa_array.fill_null([None] * max_len) + result = ArrowExtensionArray( + result._pa_array.fill_null([None] * max_len) + ) + if min_len < max_len: + # append nulls to each scalar list element up to max_len + if not pa_version_under11p0: + result = ArrowExtensionArray( + pa.compute.list_slice( + result._pa_array, + start=0, + stop=max_len, + return_fixed_size_list=True, + ) + ) + else: + all_null = np.full(max_len, fill_value=None, dtype=object) + values = result.to_numpy() + new_values = [] + for row in values: + if len(row) < max_len: + nulls = all_null[: max_len - len(row)] + row = np.append(row, nulls) + new_values.append(row) + pa_type = result._pa_array.type + result = ArrowExtensionArray(pa.array(new_values, type=pa_type)) if name is not None: labels = name else: diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index a0d15c70b5720..8625500a83e79 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -2286,6 +2286,15 @@ def test_str_split(): ) tm.assert_frame_equal(result, expected) + result = ser.str.split("1", expand=True) + expected = pd.DataFrame( + { + 0: ArrowExtensionArray(pa.array(["a", "a2cbcb", None])), + 1: ArrowExtensionArray(pa.array(["cbcb", None, None])), + } + ) + tm.assert_frame_equal(result, expected) + def test_str_rsplit(): # GH 52401 @@ -2311,6 +2320,15 @@ def test_str_rsplit(): ) tm.assert_frame_equal(result, expected) + result = ser.str.rsplit("1", expand=True) + expected = pd.DataFrame( + { + 0: ArrowExtensionArray(pa.array(["a", "a2cbcb", None])), + 1: ArrowExtensionArray(pa.array(["cbcb", None, None])), + } + ) + tm.assert_frame_equal(result, expected) + def test_str_unsupported_extract(): ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.3.rst` file if fixing a bug or adding a new feature. main: ``` In [1]: import pandas as pd In [2]: import pyarrow as pa In [3]: ser = pd.Series(["a", "a|b", "a|b|c"], dtype=pd.ArrowDtype(pa.string())) In [4]: ser.str.split("|", expand=True) Out[4]: 0 0 a 1 a 2 a ``` PR: ``` Out[4]: 0 1 2 0 a <NA> <NA> 1 a b <NA> 2 a b c ```
https://api.github.com/repos/pandas-dev/pandas/pulls/53532
2023-06-06T01:59:41Z
2023-06-07T00:15:57Z
2023-06-07T00:15:57Z
2023-06-08T02:31:47Z
DOC: create a table for period aliases
diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index 97be46e338c09..fb1c37c1b9073 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -1299,6 +1299,31 @@ frequencies. We will refer to these aliases as *offset aliases*. given frequency it will roll to the next value for ``start_date`` (respectively previous for the ``end_date``) +.. _timeseries.period_aliases: + +Period aliases +~~~~~~~~~~~~~~ + +A number of string aliases are given to useful common time series +frequencies. We will refer to these aliases as *period aliases*. + +.. csv-table:: + :header: "Alias", "Description" + :widths: 15, 100 + + "B", "business day frequency" + "D", "calendar day frequency" + "W", "weekly frequency" + "M", "monthly frequency" + "Q", "quarterly frequency" + "A, Y", "yearly frequency" + "H", "hourly frequency" + "T, min", "minutely frequency" + "S", "secondly frequency" + "L, ms", "milliseconds" + "U, us", "microseconds" + "N", "nanoseconds" + Combining aliases ~~~~~~~~~~~~~~~~~ @@ -2083,7 +2108,7 @@ Period dtypes dtype similar to the :ref:`timezone aware dtype <timeseries.timezone_series>` (``datetime64[ns, tz]``). The ``period`` dtype holds the ``freq`` attribute and is represented with -``period[freq]`` like ``period[D]`` or ``period[M]``, using :ref:`frequency strings <timeseries.offset_aliases>`. +``period[freq]`` like ``period[D]`` or ``period[M]``, using :ref:`frequency strings <timeseries.period_aliases>`. .. ipython:: python diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 28b56a220f005..3d083e55b12ab 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1145,13 +1145,13 @@ def to_period(self, freq=None) -> PeriodArray: Parameters ---------- - freq : str or Offset, optional - One of pandas' :ref:`offset strings <timeseries.offset_aliases>` - or an Offset object. Will be inferred by default. + freq : str or Period, optional + One of pandas' :ref:`period aliases <timeseries.period_aliases>` + or an Period object. Will be inferred by default. Returns ------- - PeriodArray/Index + PeriodArray/PeriodIndex Raises ------
related to pr #53477 Updated documentation for [Time series / date functionality](https://pandas.pydata.org/docs/user_guide/timeseries.html#time-series-date-functionality) Created a new table for `period aliases`. Added to the doc of `Period dtypes`reference to the table `period aliases` instead of [offset aliases](https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases). Corrected docs for `to_period`. Pointed out that only frequencies from the table `period aliases` are valid for `to_period`.
https://api.github.com/repos/pandas-dev/pandas/pulls/53530
2023-06-05T22:10:25Z
2023-06-09T17:19:07Z
2023-06-09T17:19:07Z
2023-06-09T17:19:14Z
DOC: Fixing EX01 - Added more examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 4962469dbf429..1a79e99966396 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -250,14 +250,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.DatetimeIndex.mean \ pandas.DatetimeIndex.std \ pandas.TimedeltaIndex \ - pandas.TimedeltaIndex.seconds \ - pandas.TimedeltaIndex.microseconds \ - pandas.TimedeltaIndex.nanoseconds \ - pandas.TimedeltaIndex.components \ - pandas.TimedeltaIndex.inferred_freq \ - pandas.TimedeltaIndex.as_unit \ - pandas.TimedeltaIndex.to_pytimedelta \ - pandas.TimedeltaIndex.mean \ pandas.core.window.rolling.Rolling.max \ pandas.core.window.rolling.Rolling.cov \ pandas.core.window.rolling.Rolling.skew \ diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index c3c0608a766db..8c57496e092c4 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -861,9 +861,20 @@ def inferred_freq(self) -> str | None: Examples -------- + For DatetimeIndex: + >>> idx = pd.DatetimeIndex(["2018-01-01", "2018-01-03", "2018-01-05"]) >>> idx.inferred_freq '2D' + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta(["0 days", "10 days", "20 days"]) + >>> tdelta_idx + TimedeltaIndex(['0 days', '10 days', '20 days'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.inferred_freq + '10D' """ if self.ndim != 1: return None @@ -1535,6 +1546,15 @@ def mean(self, *, skipna: bool = True, axis: AxisInt | None = 0): Notes ----- mean is only defined for Datetime and Timedelta dtypes, not for Period. + + Examples + -------- + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='D') + >>> tdelta_idx + TimedeltaIndex(['1 days', '2 days', '3 days'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.mean() + Timedelta('2 days 00:00:00') """ if isinstance(self.dtype, PeriodDtype): # See discussion in GH#24757 diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 0a28de0b27549..bf62c327de2f0 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -796,6 +796,16 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: Returns ------- numpy.ndarray + + Examples + -------- + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='D') + >>> tdelta_idx + TimedeltaIndex(['1 days', '2 days', '3 days'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.to_pytimedelta() + array([datetime.timedelta(days=1), datetime.timedelta(days=2), + datetime.timedelta(days=3)], dtype=object) """ return ints_to_pytimedelta(self._ndarray) @@ -804,6 +814,8 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: Examples -------- + For Series: + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='d')) >>> ser 0 1 days @@ -814,7 +826,16 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: 0 1 1 2 2 3 - dtype: int64""" + dtype: int64 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta(["0 days", "10 days", "20 days"]) + >>> tdelta_idx + TimedeltaIndex(['0 days', '10 days', '20 days'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.days + Index([0, 10, 20], dtype='int64')""" ) days = _field_accessor("days", "days", days_docstring) @@ -823,6 +844,8 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: Examples -------- + For Series: + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='S')) >>> ser 0 0 days 00:00:01 @@ -833,7 +856,16 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: 0 1 1 2 2 3 - dtype: int32""" + dtype: int32 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='S') + >>> tdelta_idx + TimedeltaIndex(['0 days 00:00:01', '0 days 00:00:02', '0 days 00:00:03'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.seconds + Index([1, 2, 3], dtype='int32')""" ) seconds = _field_accessor( "seconds", @@ -846,6 +878,8 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: Examples -------- + For Series: + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='U')) >>> ser 0 0 days 00:00:00.000001 @@ -856,7 +890,17 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: 0 1 1 2 2 3 - dtype: int32""" + dtype: int32 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='U') + >>> tdelta_idx + TimedeltaIndex(['0 days 00:00:00.000001', '0 days 00:00:00.000002', + '0 days 00:00:00.000003'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.microseconds + Index([1, 2, 3], dtype='int32')""" ) microseconds = _field_accessor( "microseconds", @@ -869,6 +913,8 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: Examples -------- + For Series: + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='N')) >>> ser 0 0 days 00:00:00.000000001 @@ -879,7 +925,17 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: 0 1 1 2 2 3 - dtype: int32""" + dtype: int32 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='N') + >>> tdelta_idx + TimedeltaIndex(['0 days 00:00:00.000000001', '0 days 00:00:00.000000002', + '0 days 00:00:00.000000003'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.nanoseconds + Index([1, 2, 3], dtype='int32')""" ) nanoseconds = _field_accessor( "nanoseconds", @@ -898,6 +954,16 @@ def components(self) -> DataFrame: Returns ------- DataFrame + + Examples + -------- + >>> tdelta_idx = pd.to_timedelta(['1 day 3 min 2 us 42 ns']) + >>> tdelta_idx + TimedeltaIndex(['1 days 00:03:00.000002042'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.components + days hours minutes seconds milliseconds microseconds nanoseconds + 0 1 0 3 0 0 2 42 """ from pandas import DataFrame diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 73535f0a57199..d818e1e862c12 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -431,6 +431,15 @@ def as_unit(self, unit: str) -> Self: Returns ------- same type as self + + Examples + -------- + >>> tdelta_idx = pd.to_timedelta(['1 day 3 min 2 us 42 ns']) + >>> tdelta_idx + TimedeltaIndex(['1 days 00:03:00.000002042'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.as_unit('s') + TimedeltaIndex(['1 days 00:03:00'], dtype='timedelta64[s]', freq=None) """ arr = self._data.as_unit(unit) return type(self)._simple_new(arr, name=self.name)
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53528
2023-06-05T17:30:12Z
2023-06-05T18:30:09Z
2023-06-05T18:30:09Z
2023-06-06T08:51:00Z
DOC: Fixing EX01 - Added examples
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 4962469dbf429..d23e1c912ebf4 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -82,15 +82,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01 --ignore_functions \ pandas.Series.backfill \ pandas.Series.pad \ - pandas.Series.sparse \ pandas.DataFrame.sparse \ - pandas.Series.cat.codes \ - pandas.Series.cat.reorder_categories \ - pandas.Series.cat.set_categories \ - pandas.Series.cat.as_ordered \ - pandas.Series.cat.as_unordered \ - pandas.Series.sparse.fill_value \ - pandas.Flags \ pandas.Series.attrs \ pandas.Series.plot \ pandas.Series.hist \ @@ -242,7 +234,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.IntervalIndex.to_tuples \ pandas.MultiIndex.dtypes \ pandas.MultiIndex.drop \ - pandas.DatetimeIndex.indexer_between_time \ pandas.DatetimeIndex.snap \ pandas.DatetimeIndex.as_unit \ pandas.DatetimeIndex.to_pydatetime \ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 4cc7236ff1083..97ed64856fe3b 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -875,6 +875,15 @@ def as_ordered(self) -> Self: ------- Categorical Ordered Categorical. + + Examples + -------- + >>> ser = pd.Series(["a", "b", "c", "a"], dtype="category") + >>> ser.cat.ordered + False + >>> ser = ser.cat.as_ordered() + >>> ser.cat.ordered + True """ return self.set_ordered(True) @@ -886,6 +895,15 @@ def as_unordered(self) -> Self: ------- Categorical Unordered Categorical. + + Examples + -------- + >>> raw_cate = pd.Categorical(["a", "b", "c"], + ... categories=["a", "b", "c"], ordered=True) + >>> ser = pd.Series(raw_cate) + >>> ser = ser.cat.as_unordered() + >>> ser.cat.ordered + False """ return self.set_ordered(False) @@ -936,6 +954,26 @@ def set_categories(self, new_categories, ordered=None, rename: bool = False): add_categories : Add new categories. remove_categories : Remove the specified categories. remove_unused_categories : Remove categories which are not used. + + Examples + -------- + >>> raw_cate = pd.Categorical(["a", "b", "c", "A"], + ... categories=["a", "b", "c"], ordered=True) + >>> ser = pd.Series(raw_cate) + >>> ser + 0 a + 1 b + 2 c + 3 NaN + dtype: category + Categories (3, object): ['a' < 'b' < 'c'] + >>> ser.cat.set_categories(["A", "B", "C"], rename=True) + 0 A + 1 B + 2 C + 3 NaN + dtype: category + Categories (3, object): ['A' < 'B' < 'C'] """ if ordered is None: @@ -1062,6 +1100,26 @@ def reorder_categories(self, new_categories, ordered=None) -> Self: remove_categories : Remove the specified categories. remove_unused_categories : Remove categories which are not used. set_categories : Set the categories to the specified ones. + + Examples + -------- + >>> ser = pd.Series(["a", "b", "c", "a"], dtype="category") + >>> ser = ser.cat.reorder_categories(['c', 'b', 'a'], ordered=True) + >>> ser + 0 a + 1 b + 2 c + 3 a + dtype: category + Categories (3, object): ['c' < 'b' < 'a'] + >>> ser = ser.sort_values() + >>> ser + 2 c + 1 b + 0 a + 3 a + dtype: category + Categories (3, object): ['c' < 'b' < 'a'] """ if ( len(self.categories) != len(new_categories) @@ -2663,6 +2721,17 @@ def _delegate_property_set(self, name: str, new_values): # type: ignore[overrid def codes(self) -> Series: """ Return Series of codes as well as the index. + + Examples + -------- + >>> raw_cate = pd.Categorical(["a", "b", "c", "a"], categories=["a", "b"]) + >>> ser = pd.Series(raw_cate) + >>> ser.cat.codes + 0 0 + 1 1 + 2 -1 + 3 0 + dtype: int8 """ from pandas import Series diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index eeff44cfa3c9c..ede58c86aa78d 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -40,6 +40,14 @@ def _validate(self, data): class SparseAccessor(BaseAccessor, PandasDelegate): """ Accessor for SparseSparse from other sparse matrix data types. + + Examples + -------- + >>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]") + >>> ser.sparse.density + 0.6 + >>> ser.sparse.sp_values + array([2, 2, 2]) """ def _validate(self, data): diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 4f5505015ef76..16e7835a7183d 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -629,6 +629,16 @@ def fill_value(self): Elements in `data` that are `fill_value` are not stored. For memory savings, this should be the most common value in the array. + + Examples + -------- + >>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]") + >>> ser.sparse.fill_value + 0 + >>> spa_dtype = pd.SparseDtype(dtype=np.int32, fill_value=2) + >>> ser = pd.Series([0, 0, 2, 2, 2], dtype=spa_dtype) + >>> ser.sparse.fill_value + 2 """ return self.dtype.fill_value diff --git a/pandas/core/flags.py b/pandas/core/flags.py index c4d92bcb4e994..038132f99c82e 100644 --- a/pandas/core/flags.py +++ b/pandas/core/flags.py @@ -32,9 +32,9 @@ class Flags: it is expected that every method taking or returning one or more DataFrame or Series objects will propagate ``allows_duplicate_labels``. - Notes - ----- - Attributes can be set in two ways + Examples + -------- + Attributes can be set in two ways: >>> df = pd.DataFrame() >>> df.flags diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 85dd0d6165eec..1500bcef5d4d9 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -764,6 +764,16 @@ def indexer_between_time( -------- indexer_at_time : Get index locations of values at particular time of day. DataFrame.between_time : Select values between particular times of day. + + Examples + -------- + >>> idx = pd.date_range("2023-01-01", periods=4, freq="H") + >>> idx + DatetimeIndex(['2023-01-01 00:00:00', '2023-01-01 01:00:00', + '2023-01-01 02:00:00', '2023-01-01 03:00:00'], + dtype='datetime64[ns]', freq='H') + >>> idx.indexer_between_time("00:00", "2:00", include_end=False) + array([0, 1]) """ start_time = to_time(start_time) end_time = to_time(end_time)
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Towards https://github.com/pandas-dev/pandas/issues/37875
https://api.github.com/repos/pandas-dev/pandas/pulls/53526
2023-06-05T13:40:45Z
2023-06-05T17:35:06Z
2023-06-05T17:35:05Z
2023-06-06T08:51:30Z
TST: Add test for boxable categories GH#21658
diff --git a/pandas/tests/indexes/multi/test_compat.py b/pandas/tests/indexes/multi/test_compat.py index 60608e0def7f5..f91856c3948a0 100644 --- a/pandas/tests/indexes/multi/test_compat.py +++ b/pandas/tests/indexes/multi/test_compat.py @@ -1,6 +1,7 @@ import numpy as np import pytest +import pandas as pd from pandas import MultiIndex import pandas._testing as tm @@ -83,3 +84,39 @@ def test_inplace_mutation_resets_values(): # Should have correct values tm.assert_almost_equal(exp_values, new_values) + + +def test_boxable_categorical_values(): + cat = pd.Categorical(pd.date_range("2012-01-01", periods=3, freq="H")) + result = MultiIndex.from_product([["a", "b", "c"], cat]).values + expected = pd.Series( + [ + ("a", pd.Timestamp("2012-01-01 00:00:00")), + ("a", pd.Timestamp("2012-01-01 01:00:00")), + ("a", pd.Timestamp("2012-01-01 02:00:00")), + ("b", pd.Timestamp("2012-01-01 00:00:00")), + ("b", pd.Timestamp("2012-01-01 01:00:00")), + ("b", pd.Timestamp("2012-01-01 02:00:00")), + ("c", pd.Timestamp("2012-01-01 00:00:00")), + ("c", pd.Timestamp("2012-01-01 01:00:00")), + ("c", pd.Timestamp("2012-01-01 02:00:00")), + ] + ).values + tm.assert_numpy_array_equal(result, expected) + result = pd.DataFrame({"a": ["a", "b", "c"], "b": cat, "c": np.array(cat)}).values + expected = pd.DataFrame( + { + "a": ["a", "b", "c"], + "b": [ + pd.Timestamp("2012-01-01 00:00:00"), + pd.Timestamp("2012-01-01 01:00:00"), + pd.Timestamp("2012-01-01 02:00:00"), + ], + "c": [ + pd.Timestamp("2012-01-01 00:00:00"), + pd.Timestamp("2012-01-01 01:00:00"), + pd.Timestamp("2012-01-01 02:00:00"), + ], + } + ).values + tm.assert_numpy_array_equal(result, expected)
- [ ] closes #21658 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53524
2023-06-05T08:58:47Z
2023-06-06T16:56:13Z
2023-06-06T16:56:13Z
2023-06-06T20:54:46Z
docs: Fix alignment in "merge_ordered" docstring
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 65cd7e7983bfe..46fbcc86318a2 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -294,7 +294,7 @@ def merge_ordered( ... } ... ) >>> df1 - key lvalue group + key lvalue group 0 a 1 a 1 c 2 a 2 e 3 a @@ -304,7 +304,7 @@ def merge_ordered( >>> df2 = pd.DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]}) >>> df2 - key rvalue + key rvalue 0 b 1 1 c 2 2 d 3
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/53522
2023-06-04T18:42:21Z
2023-06-05T17:45:54Z
2023-06-05T17:45:54Z
2023-06-05T17:46:55Z
DEPR `fill_method` and `limit` keywords in `pct_change`
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 762f41b4049c2..baacc8c421414 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -227,6 +227,7 @@ Other API changes Deprecations ~~~~~~~~~~~~ - Deprecated 'broadcast_axis' keyword in :meth:`Series.align` and :meth:`DataFrame.align`, upcast before calling ``align`` with ``left = DataFrame({col: left for col in right.columns}, index=right.index)`` (:issue:`51856`) +- Deprecated 'fill_method' and 'limit' keywords in :meth:`DataFrame.pct_change`, :meth:`Series.pct_change`, :meth:`DataFrameGroupBy.pct_change`, and :meth:`SeriesGroupBy.pct_change`, explicitly call ``ffill`` or ``bfill`` before calling ``pct_change`` instead (:issue:`53491`) - Deprecated 'method', 'limit', and 'fill_axis' keywords in :meth:`DataFrame.align` and :meth:`Series.align`, explicitly call ``fillna`` on the alignment results instead (:issue:`51856`) - Deprecated 'quantile' keyword in :meth:`Rolling.quantile` and :meth:`Expanding.quantile`, renamed as 'q' instead (:issue:`52550`) - Deprecated :meth:`.DataFrameGroupBy.apply` and methods on the objects returned by :meth:`.DataFrameGroupBy.resample` operating on the grouping column(s); select the columns to operate on after groupby to either explicitly include or exclude the groupings and avoid the ``FutureWarning`` (:issue:`7155`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 91083f4018c06..f73ef36f76086 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11219,8 +11219,8 @@ def describe( def pct_change( self, periods: int = 1, - fill_method: Literal["backfill", "bfill", "pad", "ffill"] | None = "pad", - limit: int | None = None, + fill_method: FillnaOptions | None | lib.NoDefault = lib.no_default, + limit: int | None | lib.NoDefault = lib.no_default, freq=None, **kwargs, ) -> Self: @@ -11244,8 +11244,14 @@ def pct_change( Periods to shift for forming percent change. fill_method : {'backfill', 'bfill', 'pad', 'ffill', None}, default 'pad' How to handle NAs **before** computing percent changes. + + .. deprecated:: 2.1 + limit : int, default None The number of consecutive NAs to fill before stopping. + + .. deprecated:: 2.1 + freq : DateOffset, timedelta, or str, optional Increment to use from time series API (e.g. 'M' or BDay()). **kwargs @@ -11298,7 +11304,7 @@ def pct_change( 3 85.0 dtype: float64 - >>> s.pct_change(fill_method='ffill') + >>> s.ffill().pct_change() 0 NaN 1 0.011111 2 0.000000 @@ -11345,6 +11351,31 @@ def pct_change( GOOG 0.179241 0.094112 NaN APPL -0.252395 -0.011860 NaN """ + # GH#53491 + if fill_method is not lib.no_default or limit is not lib.no_default: + warnings.warn( + "The 'fill_method' and 'limit' keywords in " + f"{type(self).__name__}.pct_change are deprecated and will be " + "removed in a future version. Call " + f"{'bfill' if fill_method in ('backfill', 'bfill') else 'ffill'} " + "before calling pct_change instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + if fill_method is lib.no_default: + if self.isna().values.any(): + warnings.warn( + "The default fill_method='pad' in " + f"{type(self).__name__}.pct_change is deprecated and will be " + "removed in a future version. Call ffill before calling " + "pct_change to retain current behavior and silence this warning.", + FutureWarning, + stacklevel=find_stack_level(), + ) + fill_method = "pad" + if limit is lib.no_default: + limit = None + axis = self._get_axis_number(kwargs.pop("axis", "index")) if fill_method is None: data = self diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 4ef9b02e3afad..d1ca10ef91c2c 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -4787,8 +4787,8 @@ def diff( def pct_change( self, periods: int = 1, - fill_method: FillnaOptions = "ffill", - limit: int | None = None, + fill_method: FillnaOptions | lib.NoDefault = lib.no_default, + limit: int | None | lib.NoDefault = lib.no_default, freq=None, axis: Axis | lib.NoDefault = lib.no_default, ): @@ -4838,6 +4838,30 @@ def pct_change( catfish NaN NaN goldfish 0.2 0.125 """ + # GH#53491 + if fill_method is not lib.no_default or limit is not lib.no_default: + warnings.warn( + "The 'fill_method' and 'limit' keywords in " + f"{type(self).__name__}.pct_change are deprecated and will be " + "removed in a future version. Call " + f"{'bfill' if fill_method in ('backfill', 'bfill') else 'ffill'} " + "before calling pct_change instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + if fill_method is lib.no_default: + if any(grp.isna().values.any() for _, grp in self): + warnings.warn( + "The default fill_method='ffill' in " + f"{type(self).__name__}.pct_change is deprecated and will be " + "removed in a future version. Call ffill before calling " + "pct_change to retain current behavior and silence this warning.", + FutureWarning, + stacklevel=find_stack_level(), + ) + fill_method = "ffill" + if limit is lib.no_default: + limit = None if axis is not lib.no_default: axis = self.obj._get_axis_number(axis) diff --git a/pandas/tests/frame/methods/test_pct_change.py b/pandas/tests/frame/methods/test_pct_change.py index 37d6361dec935..d0153da038a75 100644 --- a/pandas/tests/frame/methods/test_pct_change.py +++ b/pandas/tests/frame/methods/test_pct_change.py @@ -10,7 +10,7 @@ class TestDataFramePctChange: @pytest.mark.parametrize( - "periods,fill_method,limit,exp", + "periods, fill_method, limit, exp", [ (1, "ffill", None, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, 0]), (1, "ffill", 1, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, np.nan]), @@ -28,7 +28,12 @@ def test_pct_change_with_nas( vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan] obj = frame_or_series(vals) - res = obj.pct_change(periods=periods, fill_method=fill_method, limit=limit) + msg = ( + "The 'fill_method' and 'limit' keywords in " + f"{type(obj).__name__}.pct_change are deprecated" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + res = obj.pct_change(periods=periods, fill_method=fill_method, limit=limit) tm.assert_equal(res, frame_or_series(exp)) def test_pct_change_numeric(self): @@ -40,21 +45,34 @@ def test_pct_change_numeric(self): pnl.iat[1, 1] = np.nan pnl.iat[2, 3] = 60 + msg = ( + "The 'fill_method' and 'limit' keywords in " + "DataFrame.pct_change are deprecated" + ) + for axis in range(2): expected = pnl.ffill(axis=axis) / pnl.ffill(axis=axis).shift(axis=axis) - 1 - result = pnl.pct_change(axis=axis, fill_method="pad") + with tm.assert_produces_warning(FutureWarning, match=msg): + result = pnl.pct_change(axis=axis, fill_method="pad") tm.assert_frame_equal(result, expected) def test_pct_change(self, datetime_frame): - rs = datetime_frame.pct_change(fill_method=None) + msg = ( + "The 'fill_method' and 'limit' keywords in " + "DataFrame.pct_change are deprecated" + ) + + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = datetime_frame.pct_change(fill_method=None) tm.assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) rs = datetime_frame.pct_change(2) filled = datetime_frame.ffill() tm.assert_frame_equal(rs, filled / filled.shift(2) - 1) - rs = datetime_frame.pct_change(fill_method="bfill", limit=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = datetime_frame.pct_change(fill_method="bfill", limit=1) filled = datetime_frame.bfill(limit=1) tm.assert_frame_equal(rs, filled / filled.shift(1) - 1) @@ -69,7 +87,10 @@ def test_pct_change_shift_over_nas(self): df = DataFrame({"a": s, "b": s}) - chg = df.pct_change() + msg = "The default fill_method='pad' in DataFrame.pct_change is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + chg = df.pct_change() + expected = Series([np.nan, 0.5, 0.0, 2.5 / 1.5 - 1, 0.2]) edf = DataFrame({"a": expected, "b": expected}) tm.assert_frame_equal(chg, edf) @@ -88,18 +109,31 @@ def test_pct_change_shift_over_nas(self): def test_pct_change_periods_freq( self, datetime_frame, freq, periods, fill_method, limit ): - # GH#7292 - rs_freq = datetime_frame.pct_change( - freq=freq, fill_method=fill_method, limit=limit - ) - rs_periods = datetime_frame.pct_change( - periods, fill_method=fill_method, limit=limit + msg = ( + "The 'fill_method' and 'limit' keywords in " + "DataFrame.pct_change are deprecated" ) + + # GH#7292 + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_freq = datetime_frame.pct_change( + freq=freq, fill_method=fill_method, limit=limit + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_periods = datetime_frame.pct_change( + periods, fill_method=fill_method, limit=limit + ) tm.assert_frame_equal(rs_freq, rs_periods) empty_ts = DataFrame(index=datetime_frame.index, columns=datetime_frame.columns) - rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit) - rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_freq = empty_ts.pct_change( + freq=freq, fill_method=fill_method, limit=limit + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_periods = empty_ts.pct_change( + periods, fill_method=fill_method, limit=limit + ) tm.assert_frame_equal(rs_freq, rs_periods) @@ -109,7 +143,14 @@ def test_pct_change_with_duplicated_indices(fill_method): data = DataFrame( {0: [np.nan, 1, 2, 3, 9, 18], 1: [0, 1, np.nan, 3, 9, 18]}, index=["a", "b"] * 3 ) - result = data.pct_change(fill_method=fill_method) + + msg = ( + "The 'fill_method' and 'limit' keywords in " + "DataFrame.pct_change are deprecated" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = data.pct_change(fill_method=fill_method) + if fill_method is None: second_column = [np.nan, np.inf, np.nan, np.nan, 2.0, 1.0] else: diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py index 269fda8fbf361..ab268a1d94b96 100644 --- a/pandas/tests/groupby/test_groupby_dropna.py +++ b/pandas/tests/groupby/test_groupby_dropna.py @@ -622,8 +622,15 @@ def test_categorical_transformers( "x", dropna=False, observed=observed, sort=sort, as_index=as_index ) gb_dropna = df.groupby("x", dropna=True, observed=observed, sort=sort) - result = getattr(gb_keepna, transformation_func)(*args) + + msg = "The default fill_method='ffill' in DataFrameGroupBy.pct_change is deprecated" + if transformation_func == "pct_change": + with tm.assert_produces_warning(FutureWarning, match=msg): + result = getattr(gb_keepna, "pct_change")(*args) + else: + result = getattr(gb_keepna, transformation_func)(*args) expected = getattr(gb_dropna, transformation_func)(*args) + for iloc, value in zip( df[df["x"].isnull()].index.tolist(), null_group_result.values.ravel() ): diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index eb7e6c154afc9..397500f64787f 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -408,11 +408,24 @@ def mock_op(x): test_op = lambda x: x.transform(transformation_func) mock_op = lambda x: getattr(x, transformation_func)() - result = test_op(df.groupby("A")) + msg = "The default fill_method='pad' in DataFrame.pct_change is deprecated" + groupby_msg = ( + "The default fill_method='ffill' in DataFrameGroupBy.pct_change is deprecated" + ) + if transformation_func == "pct_change": + with tm.assert_produces_warning(FutureWarning, match=groupby_msg): + result = test_op(df.groupby("A")) + else: + result = test_op(df.groupby("A")) + # pass the group in same order as iterating `for ... in df.groupby(...)` # but reorder to match df's index since this is a transform groups = [df[["B"]].iloc[4:6], df[["B"]].iloc[6:], df[["B"]].iloc[:4]] - expected = concat([mock_op(g) for g in groups]).sort_index() + if transformation_func == "pct_change": + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = concat([mock_op(g) for g in groups]).sort_index() + else: + expected = concat([mock_op(g) for g in groups]).sort_index() # sort_index does not preserve the freq expected = expected.set_axis(df.index) @@ -973,9 +986,14 @@ def test_pct_change(frame_or_series, freq, periods, fill_method, limit): else: expected = expected.to_frame("vals") - result = gb.pct_change( - periods=periods, fill_method=fill_method, limit=limit, freq=freq + msg = ( + "The 'fill_method' and 'limit' keywords in " + f"{type(gb).__name__}.pct_change are deprecated" ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = gb.pct_change( + periods=periods, fill_method=fill_method, limit=limit, freq=freq + ) tm.assert_equal(result, expected) @@ -1412,7 +1430,12 @@ def test_null_group_str_transformer(request, dropna, transformation_func): # ngroup/cumcount always returns a Series as it counts the groups, not values expected = expected["B"].rename(None) - result = gb.transform(transformation_func, *args) + msg = "The default fill_method='ffill' in DataFrameGroupBy.pct_change is deprecated" + if transformation_func == "pct_change" and not dropna: + with tm.assert_produces_warning(FutureWarning, match=msg): + result = gb.transform("pct_change", *args) + else: + result = gb.transform(transformation_func, *args) tm.assert_equal(result, expected) diff --git a/pandas/tests/series/methods/test_pct_change.py b/pandas/tests/series/methods/test_pct_change.py index 475d729b6ce78..38a42062b275e 100644 --- a/pandas/tests/series/methods/test_pct_change.py +++ b/pandas/tests/series/methods/test_pct_change.py @@ -10,14 +10,21 @@ class TestSeriesPctChange: def test_pct_change(self, datetime_series): - rs = datetime_series.pct_change(fill_method=None) + msg = ( + "The 'fill_method' and 'limit' keywords in " + "Series.pct_change are deprecated" + ) + + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = datetime_series.pct_change(fill_method=None) tm.assert_series_equal(rs, datetime_series / datetime_series.shift(1) - 1) rs = datetime_series.pct_change(2) filled = datetime_series.ffill() tm.assert_series_equal(rs, filled / filled.shift(2) - 1) - rs = datetime_series.pct_change(fill_method="bfill", limit=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = datetime_series.pct_change(fill_method="bfill", limit=1) filled = datetime_series.bfill(limit=1) tm.assert_series_equal(rs, filled / filled.shift(1) - 1) @@ -40,7 +47,10 @@ def test_pct_change_with_duplicate_axis(self): def test_pct_change_shift_over_nas(self): s = Series([1.0, 1.5, np.nan, 2.5, 3.0]) - chg = s.pct_change() + msg = "The default fill_method='pad' in Series.pct_change is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + chg = s.pct_change() + expected = Series([np.nan, 0.5, 0.0, 2.5 / 1.5 - 1, 0.2]) tm.assert_series_equal(chg, expected) @@ -58,18 +68,31 @@ def test_pct_change_shift_over_nas(self): def test_pct_change_periods_freq( self, freq, periods, fill_method, limit, datetime_series ): - # GH#7292 - rs_freq = datetime_series.pct_change( - freq=freq, fill_method=fill_method, limit=limit - ) - rs_periods = datetime_series.pct_change( - periods, fill_method=fill_method, limit=limit + msg = ( + "The 'fill_method' and 'limit' keywords in " + "Series.pct_change are deprecated" ) + + # GH#7292 + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_freq = datetime_series.pct_change( + freq=freq, fill_method=fill_method, limit=limit + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_periods = datetime_series.pct_change( + periods, fill_method=fill_method, limit=limit + ) tm.assert_series_equal(rs_freq, rs_periods) empty_ts = Series(index=datetime_series.index, dtype=object) - rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit) - rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_freq = empty_ts.pct_change( + freq=freq, fill_method=fill_method, limit=limit + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + rs_periods = empty_ts.pct_change( + periods, fill_method=fill_method, limit=limit + ) tm.assert_series_equal(rs_freq, rs_periods) @@ -77,6 +100,10 @@ def test_pct_change_periods_freq( def test_pct_change_with_duplicated_indices(fill_method): # GH30463 s = Series([np.nan, 1, 2, 3, 9, 18], index=["a", "b"] * 3) - result = s.pct_change(fill_method=fill_method) + + msg = "The 'fill_method' and 'limit' keywords in Series.pct_change are deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.pct_change(fill_method=fill_method) + expected = Series([np.nan, np.nan, 1.0, 0.5, 2.0, 1.0], index=["a", "b"] * 3) tm.assert_series_equal(result, expected)
- [ ] Closes #53491 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file
https://api.github.com/repos/pandas-dev/pandas/pulls/53520
2023-06-04T16:10:55Z
2023-06-09T20:17:09Z
2023-06-09T20:17:09Z
2023-09-20T21:19:29Z
BUG: groupby.nth after selection
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 92124a536fe26..57d2f0ce78f67 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -441,6 +441,8 @@ Groupby/resample/rolling - Bug in :meth:`GroupBy.groups` with a datetime key in conjunction with another key produced incorrect number of group keys (:issue:`51158`) - Bug in :meth:`GroupBy.quantile` may implicitly sort the result index with ``sort=False`` (:issue:`53009`) - Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64, timedelta64 or :class:`PeriodDtype` values (:issue:`52128`, :issue:`53045`) +- Bug in :meth:`SeriresGroupBy.nth` and :meth:`DataFrameGroupBy.nth` after performing column selection when using ``dropna="any"`` or ``dropna="all"`` would not subset columns (:issue:`53518`) +- Bug in :meth:`SeriresGroupBy.nth` and :meth:`DataFrameGroupBy.nth` raised after performing column selection when using ``dropna="any"`` or ``dropna="all"`` resulted in rows being dropped (:issue:`53518`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index bdab641719ded..d60141bc5a96c 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3202,11 +3202,14 @@ def _nth( # old behaviour, but with all and any support for DataFrames. # modified in GH 7559 to have better perf n = cast(int, n) - dropped = self.obj.dropna(how=dropna, axis=self.axis) + dropped = self._selected_obj.dropna(how=dropna, axis=self.axis) # get a new grouper for our dropped obj grouper: np.ndarray | Index | ops.BaseGrouper - if self.keys is None and self.level is None: + if len(dropped) == len(self._selected_obj): + # Nothing was dropped, can use the same grouper + grouper = self.grouper + else: # we don't have the grouper info available # (e.g. we have selected out # a column that is not in the current object) @@ -3220,17 +3223,6 @@ def _nth( values = np.where(nulls, NA, grouper) # type: ignore[call-overload] grouper = Index(values, dtype="Int64") - else: - # create a grouper with the original parameters, but on dropped - # object - grouper, _, _ = get_grouper( - dropped, - key=self.keys, - axis=self.axis, - level=self.level, - sort=self.sort, - ) - if self.axis == 1: grb = dropped.T.groupby(grouper, as_index=self.as_index, sort=self.sort) else: diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index f744c5b741368..f0ca42c2e2719 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -852,3 +852,24 @@ def test_head_tail_dropna_false(): result = df.groupby(["X", "Y"], dropna=False).nth(n=0) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("selection", ("b", ["b"], ["b", "c"])) +@pytest.mark.parametrize("dropna", ["any", "all", None]) +def test_nth_after_selection(selection, dropna): + # GH#11038, GH#53518 + df = DataFrame( + { + "a": [1, 1, 2], + "b": [np.nan, 3, 4], + "c": [5, 6, 7], + } + ) + gb = df.groupby("a")[selection] + result = gb.nth(0, dropna=dropna) + if dropna == "any" or (dropna == "all" and selection != ["b", "c"]): + locs = [1, 2] + else: + locs = [0, 2] + expected = df.loc[locs, selection] + tm.assert_equal(result, expected)
- [x] closes #53518 (Replace xxxx with the GitHub issue number) - [x] closes #11038 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53519
2023-06-04T13:59:38Z
2023-06-05T17:51:30Z
2023-06-05T17:51:29Z
2023-06-05T18:07:43Z
FIX `groupby` with column selection not returning tuple when grouping by list of a single element
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 6bb972c21d927..b30aad4091411 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -438,6 +438,7 @@ Groupby/resample/rolling grouped :class:`Series` or :class:`DataFrame` was a :class:`DatetimeIndex`, :class:`TimedeltaIndex` or :class:`PeriodIndex`, and the ``groupby`` method was given a function as its first argument, the function operated on the whole index rather than each element of the index. (:issue:`51979`) +- Bug in :meth:`DataFrame.groupby` with column selection on the resulting groupby object not returning names as tuples when grouping by a list of a single element. (:issue:`53500`) - Bug in :meth:`DataFrameGroupBy.agg` with lists not respecting ``as_index=False`` (:issue:`52849`) - Bug in :meth:`DataFrameGroupBy.apply` causing an error to be raised when the input :class:`DataFrame` was subset as a :class:`DataFrame` after groupby (``[['a']]`` and not ``['a']``) and the given callable returned :class:`Series` that were not all indexed the same. (:issue:`52444`) - Bug in :meth:`DataFrameGroupBy.apply` raising a ``TypeError`` when selecting multiple columns and providing a function that returns ``np.ndarray`` results (:issue:`18930`) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 80e7be0fd3c91..1d5fb0fb3873d 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1935,7 +1935,7 @@ def _gotitem(self, key, ndim: int, subset=None): subset = self.obj return DataFrameGroupBy( subset, - self.grouper, + self.keys, axis=self.axis, level=self.level, grouper=self.grouper, @@ -1952,6 +1952,7 @@ def _gotitem(self, key, ndim: int, subset=None): subset = self.obj[key] return SeriesGroupBy( subset, + self.keys, level=self.level, grouper=self.grouper, exclusions=self.exclusions, diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 0c6661b49d917..bf0b646847ed6 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2722,10 +2722,13 @@ def test_groupby_none_column_name(): tm.assert_frame_equal(result, expected) -def test_single_element_list_grouping(): - # GH 42795 +@pytest.mark.parametrize("selection", [None, "a", ["a"]]) +def test_single_element_list_grouping(selection): + # GH#42795, GH#53500 df = DataFrame({"a": [1, 2], "b": [np.nan, 5], "c": [np.nan, 2]}, index=["x", "y"]) - result = [key for key, _ in df.groupby(["a"])] + grouped = df.groupby(["a"]) if selection is None else df.groupby(["a"])[selection] + result = [key for key, _ in grouped] + expected = [(1,), (2,)] assert result == expected
- [x] Closes #53500 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file
https://api.github.com/repos/pandas-dev/pandas/pulls/53517
2023-06-04T10:04:31Z
2023-06-06T20:53:56Z
2023-06-06T20:53:56Z
2023-06-28T05:41:16Z
BUG/PERF: DataFrame.isin lossy data conversion
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 92124a536fe26..db46b82ab90ac 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -301,6 +301,7 @@ Performance improvements - Performance improvement in :class:`Series` reductions (:issue:`52341`) - Performance improvement in :func:`concat` when ``axis=1`` and objects have different indexes (:issue:`52541`) - Performance improvement in :meth:`.DataFrameGroupBy.groups` (:issue:`53088`) +- Performance improvement in :meth:`DataFrame.isin` for extension dtypes (:issue:`53514`) - Performance improvement in :meth:`DataFrame.loc` when selecting rows and columns (:issue:`53014`) - Performance improvement in :meth:`Series.add` for pyarrow string and binary dtypes (:issue:`53150`) - Performance improvement in :meth:`Series.corr` and :meth:`Series.cov` for extension dtypes (:issue:`52502`) @@ -310,6 +311,7 @@ Performance improvements - Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`52525`) - Performance improvement when doing various reshaping operations on :class:`arrays.IntegerArrays` & :class:`arrays.FloatingArray` by avoiding doing unnecessary validation (:issue:`53013`) - Performance improvement when indexing with pyarrow timestamp and duration dtypes (:issue:`53368`) +- .. --------------------------------------------------------------------------- .. _whatsnew_210.bug_fixes: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d4c2124182ea5..1524197938a81 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11731,15 +11731,21 @@ def isin(self, values: Series | DataFrame | Sequence | Mapping) -> DataFrame: "to be passed to DataFrame.isin(), " f"you passed a '{type(values).__name__}'" ) - # error: Argument 2 to "isin" has incompatible type "Union[Sequence[Any], - # Mapping[Any, Any]]"; expected "Union[Union[ExtensionArray, - # ndarray[Any, Any]], Index, Series]" - res_values = algorithms.isin( - self.values.ravel(), - values, # type: ignore[arg-type] - ) + + def isin_(x): + # error: Argument 2 to "isin" has incompatible type "Union[Series, + # DataFrame, Sequence[Any], Mapping[Any, Any]]"; expected + # "Union[Union[Union[ExtensionArray, ndarray[Any, Any]], Index, + # Series], List[Any], range]" + result = algorithms.isin( + x.ravel(), + values, # type: ignore[arg-type] + ) + return result.reshape(x.shape) + + res_values = self._mgr.apply(isin_) result = self._constructor( - res_values.reshape(self.shape), + res_values, self.index, self.columns, copy=False, diff --git a/pandas/tests/frame/methods/test_isin.py b/pandas/tests/frame/methods/test_isin.py index e924963f588f3..b4511aad27a93 100644 --- a/pandas/tests/frame/methods/test_isin.py +++ b/pandas/tests/frame/methods/test_isin.py @@ -217,3 +217,11 @@ def test_isin_read_only(self): result = df.isin(arr) expected = DataFrame([True, True, True]) tm.assert_frame_equal(result, expected) + + def test_isin_not_lossy(self): + # GH 53514 + val = 1666880195890293744 + df = DataFrame({"a": [val], "b": [1.0]}) + result = df.isin([val]) + expected = DataFrame({"a": [True], "b": [False]}) + tm.assert_frame_equal(result, expected)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file if fixing a bug or adding a new feature. fixes edge case bug (lossy data conversion): ``` import pandas as pd val = 1666880195890293744 df = pd.DataFrame({"a": [val], "b": [1.0]}) df.apply(lambda x: x.isin([val])) # True, False df.isin([val]) # False, False ``` perf (for EA dtypes): ``` import pandas as pd import numpy as np data = np.random.randint(0, 1000, (100_000, 2)) df = pd.DataFrame(data, dtype="int64[pyarrow]") %timeit df.isin([1, 50]) # 25.6 ms ± 1.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) <- main # 2.1 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/53514
2023-06-03T20:22:45Z
2023-06-05T17:55:13Z
2023-06-05T17:55:13Z
2023-06-08T02:31:50Z
BUG: merge_asof raising ValueError for read-only ndarrays
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 92124a536fe26..fd298491d3816 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -446,6 +446,7 @@ Reshaping ^^^^^^^^^ - Bug in :func:`crosstab` when ``dropna=False`` would not keep ``np.nan`` in the result (:issue:`10772`) - Bug in :func:`merge_asof` raising ``KeyError`` for extension dtypes (:issue:`52904`) +- Bug in :func:`merge_asof` raising ``ValueError`` for data backed by read-only ndarrays (:issue:`53513`) - Bug in :meth:`DataFrame.agg` and :meth:`Series.agg` on non-unique columns would return incorrect type when dist-like argument passed in (:issue:`51099`) - Bug in :meth:`DataFrame.idxmin` and :meth:`DataFrame.idxmax`, where the axis dtype would be lost for empty frames (:issue:`53265`) - Bug in :meth:`DataFrame.merge` not merging correctly when having ``MultiIndex`` with single level (:issue:`52331`) diff --git a/pandas/_libs/join.pyi b/pandas/_libs/join.pyi index 11b65b859095f..7ee649a55fd8f 100644 --- a/pandas/_libs/join.pyi +++ b/pandas/_libs/join.pyi @@ -50,28 +50,28 @@ def outer_join_indexer( npt.NDArray[np.intp], ]: ... def asof_join_backward_on_X_by_Y( - left_values: np.ndarray, # asof_t[:] - right_values: np.ndarray, # asof_t[:] - left_by_values: np.ndarray, # by_t[:] - right_by_values: np.ndarray, # by_t[:] + left_values: np.ndarray, # ndarray[numeric_t] + right_values: np.ndarray, # ndarray[numeric_t] + left_by_values: np.ndarray, # ndarray[by_t] + right_by_values: np.ndarray, # ndarray[by_t] allow_exact_matches: bool = ..., tolerance: np.number | float | None = ..., use_hashtable: bool = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_forward_on_X_by_Y( - left_values: np.ndarray, # asof_t[:] - right_values: np.ndarray, # asof_t[:] - left_by_values: np.ndarray, # by_t[:] - right_by_values: np.ndarray, # by_t[:] + left_values: np.ndarray, # ndarray[numeric_t] + right_values: np.ndarray, # ndarray[numeric_t] + left_by_values: np.ndarray, # ndarray[by_t] + right_by_values: np.ndarray, # ndarray[by_t] allow_exact_matches: bool = ..., tolerance: np.number | float | None = ..., use_hashtable: bool = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_nearest_on_X_by_Y( - left_values: np.ndarray, # asof_t[:] - right_values: np.ndarray, # asof_t[:] - left_by_values: np.ndarray, # by_t[:] - right_by_values: np.ndarray, # by_t[:] + left_values: np.ndarray, # ndarray[numeric_t] + right_values: np.ndarray, # ndarray[numeric_t] + left_by_values: np.ndarray, # ndarray[by_t] + right_by_values: np.ndarray, # ndarray[by_t] allow_exact_matches: bool = ..., tolerance: np.number | float | None = ..., use_hashtable: bool = ..., diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index c49eaa3d619bd..164ed8a5c9227 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -679,10 +679,10 @@ ctypedef fused by_t: uint64_t -def asof_join_backward_on_X_by_Y(numeric_t[:] left_values, - numeric_t[:] right_values, - by_t[:] left_by_values, - by_t[:] right_by_values, +def asof_join_backward_on_X_by_Y(ndarray[numeric_t] left_values, + ndarray[numeric_t] right_values, + ndarray[by_t] left_by_values, + ndarray[by_t] right_by_values, bint allow_exact_matches=True, tolerance=None, bint use_hashtable=True): @@ -756,10 +756,10 @@ def asof_join_backward_on_X_by_Y(numeric_t[:] left_values, return left_indexer, right_indexer -def asof_join_forward_on_X_by_Y(numeric_t[:] left_values, - numeric_t[:] right_values, - by_t[:] left_by_values, - by_t[:] right_by_values, +def asof_join_forward_on_X_by_Y(ndarray[numeric_t] left_values, + ndarray[numeric_t] right_values, + ndarray[by_t] left_by_values, + ndarray[by_t] right_by_values, bint allow_exact_matches=1, tolerance=None, bint use_hashtable=True): diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 65cd7e7983bfe..d057a1952289a 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -2142,13 +2142,13 @@ def injection(obj): # we've verified above that no nulls exist left_values = left_values._data elif isinstance(left_values, ExtensionArray): - left_values = np.array(left_values) + left_values = left_values.to_numpy() if isinstance(right_values, BaseMaskedArray): # we've verified above that no nulls exist right_values = right_values._data elif isinstance(right_values, ExtensionArray): - right_values = np.array(right_values) + right_values = right_values.to_numpy() # a "by" parameter requires special handling if self.left_by is not None: diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index d62dc44cda219..0678074943ffb 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -1627,3 +1627,15 @@ def test_merge_asof_extension_dtype(dtype): ) expected = expected.astype({"join_col": dtype}) tm.assert_frame_equal(result, expected) + + +def test_merge_asof_read_only_ndarray(): + # GH 53513 + left = pd.Series([2], index=[2], name="left") + right = pd.Series([1], index=[1], name="right") + # set to read-only + left.index.values.flags.writeable = False + right.index.values.flags.writeable = False + result = merge_asof(left, right, left_index=True, right_index=True) + expected = pd.DataFrame({"left": [2], "right": [1]}, index=[2]) + tm.assert_frame_equal(result, expected)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file if fixing a bug or adding a new feature. ``` import pandas as pd left = pd.Series([2], index=[2], name="left") right = pd.Series([1], index=[1], name="right") # setting read-only here results in the error below left.index.values.flags.writeable = False # ValueError: buffer source array is read-only pd.merge_asof(left, right, left_index=True, right_index=True) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/53513
2023-06-03T10:47:30Z
2023-06-05T17:57:47Z
2023-06-05T17:57:47Z
2023-06-08T02:31:53Z
DEPR: Period[B]
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index bc187361493c0..e9492b45c3be0 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -348,6 +348,7 @@ Deprecations - Deprecated unused "closed" and "normalize" keywords in the :class:`DatetimeIndex` constructor (:issue:`52628`) - Deprecated unused "closed" keyword in the :class:`TimedeltaIndex` constructor (:issue:`52628`) - Deprecated logical operation between two non boolean :class:`Series` with different indexes always coercing the result to bool dtype. In a future version, this will maintain the return type of the inputs. (:issue:`52500`, :issue:`52538`) +- Deprecated :class:`Period` and :class:`PeriodDtype` with ``BDay`` freq, use a :class:`DatetimeIndex` with ``BDay`` freq instead (:issue:`53446`) - Deprecated :func:`value_counts`, use ``pd.Series(obj).value_counts()`` instead (:issue:`47862`) - Deprecated :meth:`Series.first` and :meth:`DataFrame.first` (please create a mask and filter using ``.loc`` instead) (:issue:`45908`) - Deprecated :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` for object-dtype (:issue:`53631`) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index d4997b5f00975..c37e9cd7ef1f3 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -107,7 +107,10 @@ from pandas._libs.tslibs.offsets cimport ( to_offset, ) -from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG +from pandas._libs.tslibs.offsets import ( + INVALID_FREQ_ERR_MSG, + BDay, +) cdef: enum: @@ -2812,6 +2815,18 @@ class Period(_Period): dt.hour, dt.minute, dt.second, dt.microsecond, 1000*nanosecond, base) + if isinstance(freq, BDay): + # GH#53446 + import warnings + + from pandas.util._exceptions import find_stack_level + warnings.warn( + "Period with BDay freq is deprecated and will be removed " + "in a future version. Use a DatetimeIndex with BDay freq instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return cls._from_ordinal(ordinal, freq) diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 886c0f389ebeb..564d727b4be5a 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -441,7 +441,8 @@ def makeTimedeltaIndex( def makePeriodIndex(k: int = 10, name=None, **kwargs) -> PeriodIndex: dt = datetime(2000, 1, 1) - return pd.period_range(start=dt, periods=k, freq="B", name=name, **kwargs) + pi = pd.period_range(start=dt, periods=k, freq="D", name=name, **kwargs) + return pi def makeMultiIndex(k: int = 10, names=None, **kwargs): diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 5d3d5a1a6b344..88d73589e0339 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -42,6 +42,7 @@ PeriodDtypeBase, abbrev_to_npy_unit, ) +from pandas._libs.tslibs.offsets import BDay from pandas.compat import pa_version_under7p0 from pandas.errors import PerformanceWarning from pandas.util._exceptions import find_stack_level @@ -966,6 +967,15 @@ def __new__(cls, freq): if not isinstance(freq, BaseOffset): freq = cls._parse_dtype_strict(freq) + if isinstance(freq, BDay): + # GH#53446 + warnings.warn( + "PeriodDtype[B] is deprecated and will be removed in a future " + "version. Use a DatetimeIndex with freq='B' instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + try: dtype_code = cls._cache_dtypes[freq] except KeyError: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 15af2dc6aa7bd..90e6f29dd98ab 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -276,10 +276,22 @@ def maybe_convert_index(ax: Axes, data): freq_str = _get_period_alias(freq) - if isinstance(data.index, ABCDatetimeIndex): - data = data.tz_localize(None).to_period(freq=freq_str) - elif isinstance(data.index, ABCPeriodIndex): - data.index = data.index.asfreq(freq=freq_str) + import warnings + + with warnings.catch_warnings(): + # suppress Period[B] deprecation warning + # TODO: need to find an alternative to this before the deprecation + # is enforced! + warnings.filterwarnings( + "ignore", + r"PeriodDtype\[B\] is deprecated", + category=FutureWarning, + ) + + if isinstance(data.index, ABCDatetimeIndex): + data = data.tz_localize(None).to_period(freq=freq_str) + elif isinstance(data.index, ABCPeriodIndex): + data.index = data.index.asfreq(freq=freq_str) return data diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 7df17c42134e9..8f87749a4ed6e 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -2,6 +2,7 @@ import array import re +import warnings import numpy as np import pytest @@ -48,7 +49,10 @@ def period_index(freqstr): the PeriodIndex behavior. """ # TODO: non-monotone indexes; NaTs, different start dates - pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr) + with warnings.catch_warnings(): + # suppress deprecation of Period[B] + warnings.simplefilter("ignore") + pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr) return pi @@ -192,6 +196,9 @@ def test_take_fill(self, arr1d): result = arr.take([-1, 1], allow_fill=True, fill_value=NaT) assert result[0] is NaT + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) def test_take_fill_str(self, arr1d): # Cast str fill_value matching other fill_value-taking methods result = arr1d.take([-1, 1], allow_fill=True, fill_value=str(arr1d[-1])) @@ -745,6 +752,7 @@ def test_astype_object(self, arr1d): assert asobj.dtype == "O" assert list(asobj) == list(dti) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_to_period(self, datetime_index, freqstr): dti = datetime_index arr = DatetimeArray(dti) @@ -999,6 +1007,8 @@ def test_take_fill_valid(self, timedelta_index, fixed_now_ts): arr.take([-1, 1], allow_fill=True, fill_value=value) +@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning") +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") class TestPeriodArray(SharedTests): index_cls = PeriodIndex array_cls = PeriodArray diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py index ab49dd3052d31..4c845d8f24d01 100644 --- a/pandas/tests/base/test_unique.py +++ b/pandas/tests/base/test_unique.py @@ -6,6 +6,7 @@ from pandas.tests.base.common import allow_na_ops +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_unique(index_or_series_obj): obj = index_or_series_obj obj = np.repeat(obj, range(1, len(obj) + 1)) @@ -27,6 +28,7 @@ def test_unique(index_or_series_obj): tm.assert_numpy_array_equal(result, expected) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.parametrize("null_obj", [np.nan, None]) def test_unique_null(null_obj, index_or_series_obj): obj = index_or_series_obj diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py index 89f3c005c52f0..3cdfb7fe41e92 100644 --- a/pandas/tests/base/test_value_counts.py +++ b/pandas/tests/base/test_value_counts.py @@ -19,6 +19,7 @@ from pandas.tests.base.common import allow_na_ops +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_value_counts(index_or_series_obj): obj = index_or_series_obj obj = np.repeat(obj, range(1, len(obj) + 1)) @@ -54,6 +55,7 @@ def test_value_counts(index_or_series_obj): @pytest.mark.parametrize("null_obj", [np.nan, None]) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_value_counts_null(null_obj, index_or_series_obj): orig = index_or_series_obj obj = orig.copy() diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index cdb33db540743..f57093c29b733 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -445,10 +445,13 @@ def test_construction(self): def test_cannot_use_custom_businessday(self): # GH#52534 msg = "CustomBusinessDay cannot be used with Period or PeriodDtype" + msg2 = r"PeriodDtype\[B\] is deprecated" with pytest.raises(TypeError, match=msg): - PeriodDtype("C") + with tm.assert_produces_warning(FutureWarning, match=msg2): + PeriodDtype("C") with pytest.raises(TypeError, match=msg): - PeriodDtype(pd.offsets.CustomBusinessDay()) + with tm.assert_produces_warning(FutureWarning, match=msg2): + PeriodDtype(pd.offsets.CustomBusinessDay()) def test_subclass(self): a = PeriodDtype("period[D]") diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 2c36535d82ba5..c024cb0387ff2 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -249,20 +249,20 @@ def test_shift_with_periodindex(self, frame_or_series): else: tm.assert_numpy_array_equal(unshifted.dropna().values, ps.values[:-1]) - shifted2 = ps.shift(1, "B") - shifted3 = ps.shift(1, offsets.BDay()) + shifted2 = ps.shift(1, "D") + shifted3 = ps.shift(1, offsets.Day()) tm.assert_equal(shifted2, shifted3) - tm.assert_equal(ps, shifted2.shift(-1, "B")) + tm.assert_equal(ps, shifted2.shift(-1, "D")) msg = "does not match PeriodIndex freq" with pytest.raises(ValueError, match=msg): - ps.shift(freq="D") + ps.shift(freq="W") # legacy support - shifted4 = ps.shift(1, freq="B") + shifted4 = ps.shift(1, freq="D") tm.assert_equal(shifted2, shifted4) - shifted5 = ps.shift(1, freq=offsets.BDay()) + shifted5 = ps.shift(1, freq=offsets.Day()) tm.assert_equal(shifted5, shifted4) def test_shift_other_axis(self): @@ -492,10 +492,10 @@ def test_period_index_frame_shift_with_freq(self, frame_or_series): unshifted = shifted.shift(-1, freq="infer") tm.assert_equal(unshifted, ps) - shifted2 = ps.shift(freq="B") + shifted2 = ps.shift(freq="D") tm.assert_equal(shifted, shifted2) - shifted3 = ps.shift(freq=offsets.BDay()) + shifted3 = ps.shift(freq=offsets.Day()) tm.assert_equal(shifted, shifted3) def test_datetime_frame_shift_with_freq(self, datetime_frame, frame_or_series): @@ -524,7 +524,7 @@ def test_datetime_frame_shift_with_freq(self, datetime_frame, frame_or_series): def test_period_index_frame_shift_with_freq_error(self, frame_or_series): ps = tm.makePeriodFrame() ps = tm.get_obj(ps, frame_or_series) - msg = "Given freq M does not match PeriodIndex freq B" + msg = "Given freq M does not match PeriodIndex freq D" with pytest.raises(ValueError, match=msg): ps.shift(freq="M") diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py index ee9c4f05991a0..f7d132a1c0bf0 100644 --- a/pandas/tests/frame/methods/test_to_csv.py +++ b/pandas/tests/frame/methods/test_to_csv.py @@ -341,6 +341,7 @@ def test_to_csv_nrows(self, nrows): "r_idx_type, c_idx_type", [("i", "i"), ("s", "s"), ("s", "dt"), ("p", "p")] ) @pytest.mark.parametrize("ncols", [1, 2, 3, 4]) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_to_csv_idx_types(self, nrows, r_idx_type, c_idx_type, ncols): df = tm.makeCustomDataframe( nrows, ncols, r_idx_type=r_idx_type, c_idx_type=c_idx_type diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index d1e48192edf0a..6a4d4ff2a5092 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -974,6 +974,7 @@ def test_idxmin(self, float_frame, int_frame, skipna, axis): tm.assert_series_equal(result, expected) @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_idxmin_empty(self, index, skipna, axis): # GH53265 if axis == 0: @@ -1014,6 +1015,7 @@ def test_idxmax(self, float_frame, int_frame, skipna, axis): tm.assert_series_equal(result, expected) @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_idxmax_empty(self, index, skipna, axis): # GH53265 if axis == 0: diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 1e9c4b446c4d0..63c0fec7b90b6 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -161,6 +161,7 @@ class TestGrouping: tm.makePeriodIndex, ], ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_grouper_index_types(self, index): # related GH5375 # groupby misbehaving when using a Floatlike index diff --git a/pandas/tests/indexes/datetimes/methods/test_to_period.py b/pandas/tests/indexes/datetimes/methods/test_to_period.py index 6c41b76aa113c..fe0b9464c7f45 100644 --- a/pandas/tests/indexes/datetimes/methods/test_to_period.py +++ b/pandas/tests/indexes/datetimes/methods/test_to_period.py @@ -107,6 +107,7 @@ def test_to_period_infer(self): tm.assert_index_equal(pi1, pi2) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_period_dt64_round_trip(self): dti = date_range("1/1/2000", "1/7/2002", freq="B") pi = dti.to_period() diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index fd0928b82ecbf..29f9295513c31 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -622,6 +622,7 @@ def test_union_with_duplicates_keep_ea_dtype(dupe_val, any_numeric_ea_dtype): tm.assert_index_equal(result, expected) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_union_duplicates(index, request): # GH#38977 if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)): diff --git a/pandas/tests/indexes/period/methods/test_to_timestamp.py b/pandas/tests/indexes/period/methods/test_to_timestamp.py index 164ed3ec43996..8bb0c3518c835 100644 --- a/pandas/tests/indexes/period/methods/test_to_timestamp.py +++ b/pandas/tests/indexes/period/methods/test_to_timestamp.py @@ -18,7 +18,7 @@ class TestToTimestamp: def test_to_timestamp_non_contiguous(self): # GH#44100 - dti = date_range("2021-10-18", periods=9, freq="B") + dti = date_range("2021-10-18", periods=9, freq="D") pi = dti.to_period() result = pi[::2].to_timestamp() diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index e3e0212607f91..7d4d681659ab6 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -61,10 +61,15 @@ def test_index_object_dtype(self, values_constructor): def test_constructor_use_start_freq(self): # GH #1118 - p = Period("4/2/2012", freq="B") - expected = period_range(start="4/2/2012", periods=10, freq="B") - - index = period_range(start=p, periods=10) + msg1 = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg1): + p = Period("4/2/2012", freq="B") + msg2 = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg2): + expected = period_range(start="4/2/2012", periods=10, freq="B") + + with tm.assert_produces_warning(FutureWarning, match=msg2): + index = period_range(start=p, periods=10) tm.assert_index_equal(index, expected) def test_constructor_field_arrays(self): @@ -440,7 +445,9 @@ def test_constructor(self): pi = period_range(freq="D", start="1/1/2001", end="12/31/2009") assert len(pi) == 365 * 9 + 2 - pi = period_range(freq="B", start="1/1/2001", end="12/31/2009") + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pi = period_range(freq="B", start="1/1/2001", end="12/31/2009") assert len(pi) == 261 * 9 pi = period_range(freq="H", start="1/1/2001", end="12/31/2001 23:00") @@ -452,8 +459,9 @@ def test_constructor(self): pi = period_range(freq="S", start="1/1/2001", end="1/1/2001 23:59:59") assert len(pi) == 24 * 60 * 60 - start = Period("02-Apr-2005", "B") - i1 = period_range(start=start, periods=20) + with tm.assert_produces_warning(FutureWarning, match=msg): + start = Period("02-Apr-2005", "B") + i1 = period_range(start=start, periods=20) assert len(i1) == 20 assert i1.freq == start.freq assert i1[0] == start @@ -470,15 +478,17 @@ def test_constructor(self): assert (i1 == i2).all() assert i1.freq == i2.freq - end_intv = Period("2005-05-01", "B") - i1 = period_range(start=start, end=end_intv) + with tm.assert_produces_warning(FutureWarning, match=msg): + end_intv = Period("2005-05-01", "B") + i1 = period_range(start=start, end=end_intv) - # infer freq from first element - i2 = PeriodIndex([end_intv, Period("2005-05-05", "B")]) + # infer freq from first element + i2 = PeriodIndex([end_intv, Period("2005-05-05", "B")]) assert len(i2) == 2 assert i2[0] == end_intv - i2 = PeriodIndex(np.array([end_intv, Period("2005-05-05", "B")])) + with tm.assert_produces_warning(FutureWarning, match=msg): + i2 = PeriodIndex(np.array([end_intv, Period("2005-05-05", "B")])) assert len(i2) == 2 assert i2[0] == end_intv @@ -498,6 +508,10 @@ def test_constructor(self): @pytest.mark.parametrize( "freq", ["M", "Q", "A", "D", "B", "T", "S", "L", "U", "N", "H"] ) + @pytest.mark.filterwarnings( + r"ignore:Period with BDay freq is deprecated:FutureWarning" + ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_recreate_from_data(self, freq): org = period_range(start="2001/04/01", freq=freq, periods=1) idx = PeriodIndex(org.values, freq=freq) diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 412d66de11ba3..6d8ae1793d5ec 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -76,8 +76,10 @@ def test_period_index_length(self): pi = period_range(freq="M", start="1/1/2001", end="12/1/2009") assert len(pi) == 12 * 9 - start = Period("02-Apr-2005", "B") - i1 = period_range(start=start, periods=20) + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + start = Period("02-Apr-2005", "B") + i1 = period_range(start=start, periods=20) assert len(i1) == 20 assert i1.freq == start.freq assert i1[0] == start @@ -95,11 +97,15 @@ def test_period_index_length(self): assert i1.freq == i2.freq msg = "start and end must have same freq" + msg2 = "Period with BDay freq is deprecated" with pytest.raises(ValueError, match=msg): - period_range(start=start, end=end_intv) + with tm.assert_produces_warning(FutureWarning, match=msg2): + period_range(start=start, end=end_intv) - end_intv = Period("2005-05-01", "B") - i1 = period_range(start=start, end=end_intv) + with tm.assert_produces_warning(FutureWarning, match=msg2): + end_intv = Period("2005-05-01", "B") + with tm.assert_produces_warning(FutureWarning, match=msg2): + i1 = period_range(start=start, end=end_intv) msg = ( "Of the three parameters: start, end, and periods, exactly two " @@ -109,11 +115,13 @@ def test_period_index_length(self): period_range(start=start) # infer freq from first element - i2 = PeriodIndex([end_intv, Period("2005-05-05", "B")]) + with tm.assert_produces_warning(FutureWarning, match=msg2): + i2 = PeriodIndex([end_intv, Period("2005-05-05", "B")]) assert len(i2) == 2 assert i2[0] == end_intv - i2 = PeriodIndex(np.array([end_intv, Period("2005-05-05", "B")])) + with tm.assert_produces_warning(FutureWarning, match=msg2): + i2 = PeriodIndex(np.array([end_intv, Period("2005-05-05", "B")])) assert len(i2) == 2 assert i2[0] == end_intv @@ -153,7 +161,6 @@ def test_period_index_length(self): period_range(freq="Q", start="1/1/2001", end="12/1/2002"), period_range(freq="M", start="1/1/2001", end="1/1/2002"), period_range(freq="D", start="12/1/2001", end="6/1/2001"), - period_range(freq="B", start="12/1/2001", end="6/1/2001"), period_range(freq="H", start="12/31/2001", end="1/1/2002 23:00"), period_range(freq="Min", start="12/31/2001", end="1/1/2002 00:20"), period_range( @@ -237,6 +244,8 @@ def test_pindex_multiples(self): assert pi.freq == offsets.MonthEnd(2) assert pi.freqstr == "2M" + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + @pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning") def test_iteration(self): index = period_range(start="1/1/10", periods=4, freq="B") diff --git a/pandas/tests/indexes/period/test_scalar_compat.py b/pandas/tests/indexes/period/test_scalar_compat.py index a42b8496b0bcf..c96444981ff14 100644 --- a/pandas/tests/indexes/period/test_scalar_compat.py +++ b/pandas/tests/indexes/period/test_scalar_compat.py @@ -1,5 +1,7 @@ """Tests for PeriodIndex behaving like a vectorized Period scalar""" +import pytest + from pandas import ( Timedelta, date_range, @@ -22,6 +24,10 @@ def test_end_time(self): expected_index += Timedelta(1, "D") - Timedelta(1, "ns") tm.assert_index_equal(index.end_time, expected_index) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) def test_end_time_business_friday(self): # GH#34449 pi = period_range("1990-01-05", freq="B", periods=1) diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index 22182416c79fd..68858b4466b56 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd from pandas import ( @@ -336,6 +337,7 @@ def test_intersection_equal_duplicates(self): result = idx_dup.intersection(idx_dup) tm.assert_index_equal(result, idx) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_union_duplicates(self): # GH#36289 idx = period_range("2011-01-01", periods=2) diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index 41b76d6aced23..13509bd58b4b8 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -30,6 +30,10 @@ class TestPeriodRepresentation: ("A", 1970), ], ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) def test_freq(self, freq, base_date): rng = period_range(start=base_date, periods=10, freq=freq) exp = np.arange(10, dtype=np.int64) diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index 3b3d6dbaf697f..8a951c3c38be6 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -40,6 +40,7 @@ def test_mutability(index): index[0] = index[0] +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_map_identity_mapping(index, request): # GH#12766 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 3d3c27bc8f6c7..00d82fe353497 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -297,9 +297,9 @@ def test_constructor_empty(self, value, klass): @pytest.mark.parametrize( "empty,klass", [ - (PeriodIndex([], freq="B"), PeriodIndex), - (PeriodIndex(iter([]), freq="B"), PeriodIndex), - (PeriodIndex((_ for _ in []), freq="B"), PeriodIndex), + (PeriodIndex([], freq="D"), PeriodIndex), + (PeriodIndex(iter([]), freq="D"), PeriodIndex), + (PeriodIndex((_ for _ in []), freq="D"), PeriodIndex), (RangeIndex(step=1), RangeIndex), (MultiIndex(levels=[[1, 2], ["blue", "red"]], codes=[[], []]), MultiIndex), ], @@ -557,6 +557,7 @@ def test_map_dictlike_simple(self, mapper): lambda values, index: Series(values, index), ], ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_map_dictlike(self, index, mapper, request): # GH 12756 if isinstance(index, CategoricalIndex): @@ -780,6 +781,7 @@ def test_drop_tuple(self, values, to_drop): with pytest.raises(KeyError, match=msg): removed.drop(drop_me) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_drop_with_duplicates_in_index(self, index): # GH38051 if len(index) == 0 or isinstance(index, MultiIndex): diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index b73bd7c78f009..9bdc16ab2e0e2 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -243,6 +243,8 @@ def test_unique(self, index_flat): result = i.unique() tm.assert_index_equal(result, expected) + @pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning") + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_searchsorted_monotonic(self, index_flat, request): # GH17271 index = index_flat @@ -293,6 +295,7 @@ def test_searchsorted_monotonic(self, index_flat, request): with pytest.raises(ValueError, match=msg): index._searchsorted_monotonic(value, side="left") + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_drop_duplicates(self, index_flat, keep): # MultiIndex is tested separately index = index_flat @@ -328,6 +331,7 @@ def test_drop_duplicates(self, index_flat, keep): expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep)) tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_drop_duplicates_no_duplicates(self, index_flat): # MultiIndex is tested separately index = index_flat @@ -355,6 +359,7 @@ def test_drop_duplicates_inplace(self, index): with pytest.raises(TypeError, match=msg): index.drop_duplicates(inplace=True) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_has_duplicates(self, index_flat): # MultiIndex tested separately in: # tests/indexes/multi/test_unique_and_duplicates. @@ -434,12 +439,14 @@ def test_hasnans_isnans(self, index_flat): assert idx.hasnans is True +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.parametrize("na_position", [None, "middle"]) def test_sort_values_invalid_na_position(index_with_missing, na_position): with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"): index_with_missing.sort_values(na_position=na_position) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.parametrize("na_position", ["first", "last"]) def test_sort_values_with_missing(index_with_missing, na_position, request): # GH 35584. Test that sort_values works with missing values, diff --git a/pandas/tests/indexes/test_datetimelike.py b/pandas/tests/indexes/test_datetimelike.py index b315b1ac141cd..71cc7f29c62bc 100644 --- a/pandas/tests/indexes/test_datetimelike.py +++ b/pandas/tests/indexes/test_datetimelike.py @@ -111,6 +111,7 @@ def test_map_callable(self, simple_index): lambda values, index: pd.Series(values, index, dtype=object), ], ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_map_dictlike(self, mapper, simple_index): index = simple_index expected = index + index.freq diff --git a/pandas/tests/indexes/test_old_base.py b/pandas/tests/indexes/test_old_base.py index 588aa458c8b04..3b627f2fae845 100644 --- a/pandas/tests/indexes/test_old_base.py +++ b/pandas/tests/indexes/test_old_base.py @@ -237,6 +237,7 @@ def test_repr_max_seq_item_setting(self, simple_index): repr(idx) assert "..." not in str(idx) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_ensure_copied_data(self, index): # Check the "copy" argument of each Index.__new__ is honoured # GH12309 @@ -454,6 +455,7 @@ def test_delete_base(self, index): with pytest.raises(IndexError, match=msg): index.delete(length) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_equals(self, index): if isinstance(index, IntervalIndex): # IntervalIndex tested separately, the index.equals(index.astype(object)) @@ -651,6 +653,7 @@ def test_map(self, simple_index): lambda values, index: Series(values, index), ], ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_map_dictlike(self, mapper, simple_index): idx = simple_index if isinstance(idx, CategoricalIndex): diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 8b12d3ccb2c2f..31a867acdb5d1 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -13,10 +13,12 @@ from pandas.core.dtypes.cast import find_common_type from pandas import ( + CategoricalDtype, CategoricalIndex, DatetimeTZDtype, Index, MultiIndex, + PeriodDtype, RangeIndex, Series, Timestamp, @@ -67,6 +69,7 @@ def test_union_different_types(index_flat, index_flat2, request): common_dtype = find_common_type([idx1.dtype, idx2.dtype]) warn = None + msg = "'<' not supported between" if not len(idx1) or not len(idx2): pass elif (idx1.dtype.kind == "c" and (not lib.is_np_dtype(idx2.dtype, "iufc"))) or ( @@ -74,6 +77,19 @@ def test_union_different_types(index_flat, index_flat2, request): ): # complex objects non-sortable warn = RuntimeWarning + elif ( + isinstance(idx1.dtype, PeriodDtype) and isinstance(idx2.dtype, CategoricalDtype) + ) or ( + isinstance(idx2.dtype, PeriodDtype) and isinstance(idx1.dtype, CategoricalDtype) + ): + warn = FutureWarning + msg = r"PeriodDtype\[B\] is deprecated" + mark = pytest.mark.xfail( + reason="Warning not produced on all builds", + raises=AssertionError, + strict=False, + ) + request.node.add_marker(mark) any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype) idx1_signed = is_signed_integer_dtype(idx1.dtype) @@ -84,7 +100,7 @@ def test_union_different_types(index_flat, index_flat2, request): idx1 = idx1.sort_values() idx2 = idx2.sort_values() - with tm.assert_produces_warning(warn, match="'<' not supported between"): + with tm.assert_produces_warning(warn, match=msg): res1 = idx1.union(idx2) res2 = idx2.union(idx1) @@ -175,6 +191,7 @@ def test_set_ops_error_cases(self, case, method, index): with pytest.raises(TypeError, match=msg): getattr(index, method)(case) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_intersection_base(self, index): if isinstance(index, CategoricalIndex): return @@ -203,6 +220,7 @@ def test_intersection_base(self, index): @pytest.mark.filterwarnings( "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning" ) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_union_base(self, index): first = index[3:] second = index[:5] @@ -227,6 +245,7 @@ def test_union_base(self, index): with pytest.raises(TypeError, match=msg): first.union([1, 2, 3]) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.filterwarnings( "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning" ) @@ -255,6 +274,7 @@ def test_difference_base(self, sort, index): with pytest.raises(TypeError, match=msg): first.difference([1, 2, 3], sort) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.filterwarnings( "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning" ) @@ -420,6 +440,7 @@ def test_intersect_unequal(self, index_flat, fname, sname, expected_name): expected = index[1:].set_names(expected_name).sort_values() tm.assert_index_equal(intersect, expected) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_intersection_name_retention_with_nameless(self, index): if isinstance(index, MultiIndex): index = index.rename(list(range(index.nlevels))) @@ -473,6 +494,7 @@ def test_intersection_difference_match_empty(self, index, sort): tm.assert_index_equal(inter, diff, exact=True) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.filterwarnings( "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning" ) diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 3bf8c2eaa7e94..f74da0d48a3be 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -708,7 +708,7 @@ def test_3levels_leading_period_index(): pi = pd.PeriodIndex( ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"], name="datetime", - freq="B", + freq="D", ) lev2 = ["A", "A", "Z", "W"] lev3 = ["B", "C", "Q", "F"] diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 4017a0e3a2f80..f6e7f7355bc73 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1656,6 +1656,7 @@ def test_loc_iloc_getitem_ellipsis(self, obj, indexer): result = indexer(obj)[...] tm.assert_equal(result, obj) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_loc_iloc_getitem_leading_ellipses(self, series_with_simple_index, indexer): obj = series_with_simple_index key = 0 if (indexer is tm.iloc or len(obj) == 0) else obj.index[0] @@ -2963,6 +2964,8 @@ def test_loc_set_int_dtype(): tm.assert_frame_equal(df, expected) +@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning") +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_loc_periodindex_3_levels(): # GH#24091 p_index = PeriodIndex( @@ -3246,6 +3249,8 @@ def test_loc_set_multiple_items_in_multiple_new_columns(self): def test_getitem_loc_str_periodindex(self): # GH#33964 - index = pd.period_range(start="2000", periods=20, freq="B") - series = Series(range(20), index=index) - assert series.loc["2000-01-14"] == 9 + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + index = pd.period_range(start="2000", periods=20, freq="B") + series = Series(range(20), index=index) + assert series.loc["2000-01-14"] == 9 diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 910f83e0b997c..1411c9d600897 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -217,6 +217,7 @@ def test_put_mixed_type(setup_path): ["fixed", tm.makePeriodIndex], ], ) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_store_index_types(setup_path, format, index): # GH5386 # test storing various index types diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index 61dabf15653f0..5a270a7d88a1d 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -342,6 +342,8 @@ def test_read_hdf_series_mode_r(tmp_path, format, setup_path): tm.assert_series_equal(result, series) +@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning") +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_read_py2_hdf_file_in_py3(datapath): # GH 16781 diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 17b7eef011a0a..00a9587241db0 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -911,6 +911,7 @@ def test_columns_multiindex_modified(tmp_path, setup_path): assert cols2load_original == cols2load +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_to_hdf_with_object_column_names(tmp_path, setup_path): # GH9057 diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py index 262f25e77b69c..8f6f8ee6c5682 100644 --- a/pandas/tests/io/pytables/test_time_series.py +++ b/pandas/tests/io/pytables/test_time_series.py @@ -21,6 +21,7 @@ def test_store_datetime_fractional_secs(setup_path): assert store["a"].index[0] == dt +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_tseries_indices_series(setup_path): with ensure_clean_store(setup_path) as store: idx = tm.makeDateIndex(10) @@ -42,6 +43,7 @@ def test_tseries_indices_series(setup_path): tm.assert_class_equal(result.index, ser.index, obj="series index") +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_tseries_indices_frame(setup_path): with ensure_clean_store(setup_path) as store: idx = tm.makeDateIndex(10) diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index f3b3fb43edf36..5cbe7b6e30c84 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -339,7 +339,9 @@ def test_xcompat_plot_params_x_compat(self): ax = df.plot() lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) - assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) def test_xcompat_plot_params_context_manager(self): df = tm.makeTimeDataFrame() @@ -355,7 +357,9 @@ def test_xcompat_plot_period(self): ax = df.plot() lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) - assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) + msg = r"PeriodDtype\[B\] is deprecated " + with tm.assert_produces_warning(FutureWarning, match=msg): + assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) _check_ticks_props(ax, xrot=0) def test_period_compat(self): diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index af8bcd943765e..4b121841b4e4d 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -221,6 +221,7 @@ def test_line_plot_period_mlt_frame(self, frqncy): freq = df.index.asfreq(df.index.freq.rule_code).freq _check_plot_works(df.plot, freq) + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.parametrize( "freq", ["S", "T", "H", "D", "W", "M", "Q-DEC", "A", "1B30Min"] ) @@ -319,11 +320,16 @@ def test_irregular_datetime64_repr_bug(self): def test_business_freq(self): bts = tm.makePeriodSeries() + msg = r"PeriodDtype\[B\] is deprecated" + dt = bts.index[0].to_timestamp() + with tm.assert_produces_warning(FutureWarning, match=msg): + bts.index = period_range(start=dt, periods=len(bts), freq="B") _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) assert ax.get_lines()[0].get_xydata()[0, 0] == bts.index[0].ordinal idx = ax.get_lines()[0].get_xdata() - assert PeriodIndex(data=idx).freqstr == "B" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert PeriodIndex(data=idx).freqstr == "B" def test_business_freq_convert(self): bts = tm.makeTimeSeries(300).asfreq("BM") @@ -360,8 +366,13 @@ def test_dataframe(self): _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) idx = ax.get_lines()[0].get_xdata() - tm.assert_index_equal(bts.index.to_period(), PeriodIndex(idx)) + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + tm.assert_index_equal(bts.index.to_period(), PeriodIndex(idx)) + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) @pytest.mark.parametrize( "obj", [ @@ -407,7 +418,9 @@ def test_get_finder(self): def test_finder_daily(self): day_lst = [10, 40, 252, 400, 950, 2750, 10000] - xpl1 = xpl2 = [Period("1999-1-1", freq="B").ordinal] * len(day_lst) + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + xpl1 = xpl2 = [Period("1999-1-1", freq="B").ordinal] * len(day_lst) rs1 = [] rs2 = [] for n in day_lst: @@ -698,14 +711,16 @@ def test_mixed_freq_regular_first(self): ax2 = s2.plot(style="g", ax=ax) lines = ax2.get_lines() - idx1 = PeriodIndex(lines[0].get_xdata()) - idx2 = PeriodIndex(lines[1].get_xdata()) + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx1 = PeriodIndex(lines[0].get_xdata()) + idx2 = PeriodIndex(lines[1].get_xdata()) - tm.assert_index_equal(idx1, s1.index.to_period("B")) - tm.assert_index_equal(idx2, s2.index.to_period("B")) + tm.assert_index_equal(idx1, s1.index.to_period("B")) + tm.assert_index_equal(idx2, s2.index.to_period("B")) - left, right = ax2.get_xlim() - pidx = s1.index.to_period() + left, right = ax2.get_xlim() + pidx = s1.index.to_period() assert left <= pidx[0].ordinal assert right >= pidx[-1].ordinal @@ -730,12 +745,14 @@ def test_mixed_freq_regular_first_df(self): s1.plot(ax=ax) ax2 = s2.plot(style="g", ax=ax) lines = ax2.get_lines() - idx1 = PeriodIndex(lines[0].get_xdata()) - idx2 = PeriodIndex(lines[1].get_xdata()) - assert idx1.equals(s1.index.to_period("B")) - assert idx2.equals(s2.index.to_period("B")) - left, right = ax2.get_xlim() - pidx = s1.index.to_period() + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx1 = PeriodIndex(lines[0].get_xdata()) + idx2 = PeriodIndex(lines[1].get_xdata()) + assert idx1.equals(s1.index.to_period("B")) + assert idx2.equals(s2.index.to_period("B")) + left, right = ax2.get_xlim() + pidx = s1.index.to_period() assert left <= pidx[0].ordinal assert right >= pidx[-1].ordinal @@ -802,10 +819,13 @@ def test_mixed_freq_lf_first_hourly(self): for line in ax.get_lines(): assert PeriodIndex(data=line.get_xdata()).freq == "T" + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_mixed_freq_irreg_period(self): ts = tm.makeTimeSeries() irreg = ts.iloc[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]] - rng = period_range("1/3/2000", periods=30, freq="B") + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rng = period_range("1/3/2000", periods=30, freq="B") ps = Series(np.random.randn(len(rng)), rng) _, ax = mpl.pyplot.subplots() irreg.plot(ax=ax) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 2f5deb7b2bbd5..57381352163e7 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -49,6 +49,9 @@ def get_objs(): class TestReductions: + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) @pytest.mark.parametrize("opname", ["max", "min"]) @pytest.mark.parametrize("obj", get_objs()) def test_ops(self, opname, obj): diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py index b1462d109561f..5f6fcba50142c 100644 --- a/pandas/tests/reductions/test_stat_reductions.py +++ b/pandas/tests/reductions/test_stat_reductions.py @@ -50,7 +50,10 @@ def test_period_mean(self, box, freq): # shuffle so that we are not just working with monotone-increasing dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6]) - parr = dti._data.to_period(freq) + warn = FutureWarning if freq == "B" else None + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(warn, match=msg): + parr = dti._data.to_period(freq) obj = box(parr) with pytest.raises(TypeError, match="ambiguous"): obj.mean() diff --git a/pandas/tests/resample/conftest.py b/pandas/tests/resample/conftest.py index 38f682c9c4f5a..2708ab3f8184f 100644 --- a/pandas/tests/resample/conftest.py +++ b/pandas/tests/resample/conftest.py @@ -1,4 +1,5 @@ from datetime import datetime +import warnings import numpy as np import pytest @@ -63,7 +64,15 @@ def simple_period_range_series(): """ def _simple_period_range_series(start, end, freq="D"): - rng = period_range(start, end, freq=freq) + with warnings.catch_warnings(): + # suppress Period[B] deprecation warning + msg = "|".join(["Period with BDay freq", r"PeriodDtype\[B\] is deprecated"]) + warnings.filterwarnings( + "ignore", + msg, + category=FutureWarning, + ) + rng = period_range(start, end, freq=freq) return Series(np.random.randn(len(rng)), index=rng) return _simple_period_range_series diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index 22bd8f9c8ced3..7a76a21a6c579 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -277,15 +277,20 @@ def test_resample_size_empty_dataframe(freq, empty_frame_dti): tm.assert_series_equal(result, expected) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.parametrize("index", tm.all_timeseries_index_generator(0)) @pytest.mark.parametrize("dtype", [float, int, object, "datetime64[ns]"]) def test_resample_empty_dtypes(index, dtype, resample_method): # Empty series were sometimes causing a segfault (for the functions # with Cython bounds-checking disabled) or an IndexError. We just run # them to ensure they no longer do. (GH #10228) + if isinstance(index, PeriodIndex): + # GH#53511 + index = PeriodIndex([], freq="B", name=index.name) empty_series_dti = Series([], index, dtype) + rs = empty_series_dti.resample("d", group_keys=False) try: - getattr(empty_series_dti.resample("d", group_keys=False), resample_method)() + getattr(rs, resample_method)() except DataError: # Ignore these since some combinations are invalid # (ex: doing mean with dtype of np.object_) diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 20b997bdca873..9246ed4647e63 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -108,10 +108,12 @@ def test_annual_upsample_cases( self, targ, conv, meth, month, simple_period_range_series ): ts = simple_period_range_series("1/1/1990", "12/31/1991", freq=f"A-{month}") - - result = getattr(ts.resample(targ, convention=conv), meth)() - expected = result.to_timestamp(targ, how=conv) - expected = expected.asfreq(targ, meth).to_period() + warn = FutureWarning if targ == "B" else None + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = getattr(ts.resample(targ, convention=conv), meth)() + expected = result.to_timestamp(targ, how=conv) + expected = expected.asfreq(targ, meth).to_period() tm.assert_series_equal(result, expected) def test_basic_downsample(self, simple_period_range_series): @@ -187,18 +189,25 @@ def test_quarterly_upsample( ): freq = f"Q-{month}" ts = simple_period_range_series("1/1/1990", "12/31/1995", freq=freq) - result = ts.resample(target, convention=convention).ffill() - expected = result.to_timestamp(target, how=convention) - expected = expected.asfreq(target, "ffill").to_period() + warn = FutureWarning if target == "B" else None + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = ts.resample(target, convention=convention).ffill() + expected = result.to_timestamp(target, how=convention) + expected = expected.asfreq(target, "ffill").to_period() tm.assert_series_equal(result, expected) @pytest.mark.parametrize("target", ["D", "B"]) @pytest.mark.parametrize("convention", ["start", "end"]) def test_monthly_upsample(self, target, convention, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="M") - result = ts.resample(target, convention=convention).ffill() - expected = result.to_timestamp(target, how=convention) - expected = expected.asfreq(target, "ffill").to_period() + + warn = None if target == "D" else FutureWarning + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = ts.resample(target, convention=convention).ffill() + expected = result.to_timestamp(target, how=convention) + expected = expected.asfreq(target, "ffill").to_period() tm.assert_series_equal(result, expected) def test_resample_basic(self): @@ -363,9 +372,13 @@ def test_fill_method_and_how_upsample(self): def test_weekly_upsample(self, day, target, convention, simple_period_range_series): freq = f"W-{day}" ts = simple_period_range_series("1/1/1990", "12/31/1995", freq=freq) - result = ts.resample(target, convention=convention).ffill() - expected = result.to_timestamp(target, how=convention) - expected = expected.asfreq(target, "ffill").to_period() + + warn = None if target == "D" else FutureWarning + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = ts.resample(target, convention=convention).ffill() + expected = result.to_timestamp(target, how=convention) + expected = expected.asfreq(target, "ffill").to_period() tm.assert_series_equal(result, expected) def test_resample_to_timestamps(self, simple_period_range_series): diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index e652c63d46f18..f6c1675766210 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -9,11 +9,15 @@ Timestamp, offsets, ) +import pandas._testing as tm + +bday_msg = "Period with BDay freq is deprecated" class TestFreqConversion: """Test frequency conversion of date objects""" + @pytest.mark.filterwarnings("ignore:Period with BDay:FutureWarning") @pytest.mark.parametrize("freq", ["A", "Q", "M", "W", "B", "D"]) def test_asfreq_near_zero(self, freq): # GH#19643, GH#19650 @@ -37,10 +41,12 @@ def test_asfreq_near_zero_weekly(self): def test_to_timestamp_out_of_bounds(self): # GH#19643, used to incorrectly give Timestamp in 1754 - per = Period("0001-01-01", freq="B") + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per = Period("0001-01-01", freq="B") msg = "Out of bounds nanosecond timestamp" with pytest.raises(OutOfBoundsDatetime, match=msg): - per.to_timestamp() + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per.to_timestamp() def test_asfreq_corner(self): val = Period(freq="A", year=2007) @@ -67,8 +73,9 @@ def test_conv_annual(self): ival_A_to_M_end = Period(freq="M", year=2007, month=12) ival_A_to_W_start = Period(freq="W", year=2007, month=1, day=1) ival_A_to_W_end = Period(freq="W", year=2007, month=12, day=31) - ival_A_to_B_start = Period(freq="B", year=2007, month=1, day=1) - ival_A_to_B_end = Period(freq="B", year=2007, month=12, day=31) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_A_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_A_to_B_end = Period(freq="B", year=2007, month=12, day=31) ival_A_to_D_start = Period(freq="D", year=2007, month=1, day=1) ival_A_to_D_end = Period(freq="D", year=2007, month=12, day=31) ival_A_to_H_start = Period(freq="H", year=2007, month=1, day=1, hour=0) @@ -99,8 +106,9 @@ def test_conv_annual(self): assert ival_A.asfreq("M", "E") == ival_A_to_M_end assert ival_A.asfreq("W", "S") == ival_A_to_W_start assert ival_A.asfreq("W", "E") == ival_A_to_W_end - assert ival_A.asfreq("B", "S") == ival_A_to_B_start - assert ival_A.asfreq("B", "E") == ival_A_to_B_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_A.asfreq("B", "S") == ival_A_to_B_start + assert ival_A.asfreq("B", "E") == ival_A_to_B_end assert ival_A.asfreq("D", "S") == ival_A_to_D_start assert ival_A.asfreq("D", "E") == ival_A_to_D_end assert ival_A.asfreq("H", "S") == ival_A_to_H_start @@ -137,8 +145,9 @@ def test_conv_quarterly(self): ival_Q_to_M_end = Period(freq="M", year=2007, month=3) ival_Q_to_W_start = Period(freq="W", year=2007, month=1, day=1) ival_Q_to_W_end = Period(freq="W", year=2007, month=3, day=31) - ival_Q_to_B_start = Period(freq="B", year=2007, month=1, day=1) - ival_Q_to_B_end = Period(freq="B", year=2007, month=3, day=30) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_Q_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_Q_to_B_end = Period(freq="B", year=2007, month=3, day=30) ival_Q_to_D_start = Period(freq="D", year=2007, month=1, day=1) ival_Q_to_D_end = Period(freq="D", year=2007, month=3, day=31) ival_Q_to_H_start = Period(freq="H", year=2007, month=1, day=1, hour=0) @@ -169,8 +178,9 @@ def test_conv_quarterly(self): assert ival_Q.asfreq("M", "E") == ival_Q_to_M_end assert ival_Q.asfreq("W", "S") == ival_Q_to_W_start assert ival_Q.asfreq("W", "E") == ival_Q_to_W_end - assert ival_Q.asfreq("B", "S") == ival_Q_to_B_start - assert ival_Q.asfreq("B", "E") == ival_Q_to_B_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_Q.asfreq("B", "S") == ival_Q_to_B_start + assert ival_Q.asfreq("B", "E") == ival_Q_to_B_end assert ival_Q.asfreq("D", "S") == ival_Q_to_D_start assert ival_Q.asfreq("D", "E") == ival_Q_to_D_end assert ival_Q.asfreq("H", "S") == ival_Q_to_H_start @@ -197,8 +207,9 @@ def test_conv_monthly(self): ival_M_to_Q = Period(freq="Q", year=2007, quarter=1) ival_M_to_W_start = Period(freq="W", year=2007, month=1, day=1) ival_M_to_W_end = Period(freq="W", year=2007, month=1, day=31) - ival_M_to_B_start = Period(freq="B", year=2007, month=1, day=1) - ival_M_to_B_end = Period(freq="B", year=2007, month=1, day=31) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_M_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_M_to_B_end = Period(freq="B", year=2007, month=1, day=31) ival_M_to_D_start = Period(freq="D", year=2007, month=1, day=1) ival_M_to_D_end = Period(freq="D", year=2007, month=1, day=31) ival_M_to_H_start = Period(freq="H", year=2007, month=1, day=1, hour=0) @@ -223,8 +234,9 @@ def test_conv_monthly(self): assert ival_M.asfreq("W", "S") == ival_M_to_W_start assert ival_M.asfreq("W", "E") == ival_M_to_W_end - assert ival_M.asfreq("B", "S") == ival_M_to_B_start - assert ival_M.asfreq("B", "E") == ival_M_to_B_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_M.asfreq("B", "S") == ival_M_to_B_start + assert ival_M.asfreq("B", "E") == ival_M_to_B_end assert ival_M.asfreq("D", "S") == ival_M_to_D_start assert ival_M.asfreq("D", "E") == ival_M_to_D_end assert ival_M.asfreq("H", "S") == ival_M_to_H_start @@ -285,8 +297,9 @@ def test_conv_weekly(self): else: ival_W_to_M_end_of_month = Period(freq="M", year=2007, month=2) - ival_W_to_B_start = Period(freq="B", year=2007, month=1, day=1) - ival_W_to_B_end = Period(freq="B", year=2007, month=1, day=5) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_W_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_W_to_B_end = Period(freq="B", year=2007, month=1, day=5) ival_W_to_D_start = Period(freq="D", year=2007, month=1, day=1) ival_W_to_D_end = Period(freq="D", year=2007, month=1, day=7) ival_W_to_H_start = Period(freq="H", year=2007, month=1, day=1, hour=0) @@ -313,8 +326,9 @@ def test_conv_weekly(self): assert ival_W.asfreq("M") == ival_W_to_M assert ival_W_end_of_month.asfreq("M") == ival_W_to_M_end_of_month - assert ival_W.asfreq("B", "S") == ival_W_to_B_start - assert ival_W.asfreq("B", "E") == ival_W_to_B_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_W.asfreq("B", "S") == ival_W_to_B_start + assert ival_W.asfreq("B", "E") == ival_W_to_B_end assert ival_W.asfreq("D", "S") == ival_W_to_D_start assert ival_W.asfreq("D", "E") == ival_W_to_D_end @@ -369,11 +383,12 @@ def test_conv_weekly_legacy(self): def test_conv_business(self): # frequency conversion tests: from Business Frequency" - ival_B = Period(freq="B", year=2007, month=1, day=1) - ival_B_end_of_year = Period(freq="B", year=2007, month=12, day=31) - ival_B_end_of_quarter = Period(freq="B", year=2007, month=3, day=30) - ival_B_end_of_month = Period(freq="B", year=2007, month=1, day=31) - ival_B_end_of_week = Period(freq="B", year=2007, month=1, day=5) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_B = Period(freq="B", year=2007, month=1, day=1) + ival_B_end_of_year = Period(freq="B", year=2007, month=12, day=31) + ival_B_end_of_quarter = Period(freq="B", year=2007, month=3, day=30) + ival_B_end_of_month = Period(freq="B", year=2007, month=1, day=31) + ival_B_end_of_week = Period(freq="B", year=2007, month=1, day=5) ival_B_to_A = Period(freq="A", year=2007) ival_B_to_Q = Period(freq="Q", year=2007, quarter=1) @@ -413,7 +428,8 @@ def test_conv_business(self): assert ival_B.asfreq("S", "S") == ival_B_to_S_start assert ival_B.asfreq("S", "E") == ival_B_to_S_end - assert ival_B.asfreq("B") == ival_B + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_B.asfreq("B") == ival_B def test_conv_daily(self): # frequency conversion tests: from Business Frequency" @@ -428,8 +444,9 @@ def test_conv_daily(self): ival_D_saturday = Period(freq="D", year=2007, month=1, day=6) ival_D_sunday = Period(freq="D", year=2007, month=1, day=7) - ival_B_friday = Period(freq="B", year=2007, month=1, day=5) - ival_B_monday = Period(freq="B", year=2007, month=1, day=8) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_B_friday = Period(freq="B", year=2007, month=1, day=5) + ival_B_monday = Period(freq="B", year=2007, month=1, day=8) ival_D_to_A = Period(freq="A", year=2007) @@ -475,11 +492,12 @@ def test_conv_daily(self): assert ival_D.asfreq("W") == ival_D_to_W assert ival_D_end_of_week.asfreq("W") == ival_D_to_W - assert ival_D_friday.asfreq("B") == ival_B_friday - assert ival_D_saturday.asfreq("B", "S") == ival_B_friday - assert ival_D_saturday.asfreq("B", "E") == ival_B_monday - assert ival_D_sunday.asfreq("B", "S") == ival_B_friday - assert ival_D_sunday.asfreq("B", "E") == ival_B_monday + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_D_friday.asfreq("B") == ival_B_friday + assert ival_D_saturday.asfreq("B", "S") == ival_B_friday + assert ival_D_saturday.asfreq("B", "E") == ival_B_monday + assert ival_D_sunday.asfreq("B", "S") == ival_B_friday + assert ival_D_sunday.asfreq("B", "E") == ival_B_monday assert ival_D.asfreq("H", "S") == ival_D_to_H_start assert ival_D.asfreq("H", "E") == ival_D_to_H_end @@ -506,7 +524,8 @@ def test_conv_hourly(self): ival_H_to_M = Period(freq="M", year=2007, month=1) ival_H_to_W = Period(freq="W", year=2007, month=1, day=7) ival_H_to_D = Period(freq="D", year=2007, month=1, day=1) - ival_H_to_B = Period(freq="B", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_H_to_B = Period(freq="B", year=2007, month=1, day=1) ival_H_to_T_start = Period( freq="Min", year=2007, month=1, day=1, hour=0, minute=0 @@ -531,8 +550,9 @@ def test_conv_hourly(self): assert ival_H_end_of_week.asfreq("W") == ival_H_to_W assert ival_H.asfreq("D") == ival_H_to_D assert ival_H_end_of_day.asfreq("D") == ival_H_to_D - assert ival_H.asfreq("B") == ival_H_to_B - assert ival_H_end_of_bus.asfreq("B") == ival_H_to_B + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_H.asfreq("B") == ival_H_to_B + assert ival_H_end_of_bus.asfreq("B") == ival_H_to_B assert ival_H.asfreq("Min", "S") == ival_H_to_T_start assert ival_H.asfreq("Min", "E") == ival_H_to_T_end @@ -572,7 +592,8 @@ def test_conv_minutely(self): ival_T_to_M = Period(freq="M", year=2007, month=1) ival_T_to_W = Period(freq="W", year=2007, month=1, day=7) ival_T_to_D = Period(freq="D", year=2007, month=1, day=1) - ival_T_to_B = Period(freq="B", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_T_to_B = Period(freq="B", year=2007, month=1, day=1) ival_T_to_H = Period(freq="H", year=2007, month=1, day=1, hour=0) ival_T_to_S_start = Period( @@ -592,8 +613,9 @@ def test_conv_minutely(self): assert ival_T_end_of_week.asfreq("W") == ival_T_to_W assert ival_T.asfreq("D") == ival_T_to_D assert ival_T_end_of_day.asfreq("D") == ival_T_to_D - assert ival_T.asfreq("B") == ival_T_to_B - assert ival_T_end_of_bus.asfreq("B") == ival_T_to_B + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_T.asfreq("B") == ival_T_to_B + assert ival_T_end_of_bus.asfreq("B") == ival_T_to_B assert ival_T.asfreq("H") == ival_T_to_H assert ival_T_end_of_hour.asfreq("H") == ival_T_to_H @@ -636,7 +658,8 @@ def test_conv_secondly(self): ival_S_to_M = Period(freq="M", year=2007, month=1) ival_S_to_W = Period(freq="W", year=2007, month=1, day=7) ival_S_to_D = Period(freq="D", year=2007, month=1, day=1) - ival_S_to_B = Period(freq="B", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_S_to_B = Period(freq="B", year=2007, month=1, day=1) ival_S_to_H = Period(freq="H", year=2007, month=1, day=1, hour=0) ival_S_to_T = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0) @@ -650,8 +673,9 @@ def test_conv_secondly(self): assert ival_S_end_of_week.asfreq("W") == ival_S_to_W assert ival_S.asfreq("D") == ival_S_to_D assert ival_S_end_of_day.asfreq("D") == ival_S_to_D - assert ival_S.asfreq("B") == ival_S_to_B - assert ival_S_end_of_bus.asfreq("B") == ival_S_to_B + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_S.asfreq("B") == ival_S_to_B + assert ival_S_end_of_bus.asfreq("B") == ival_S_to_B assert ival_S.asfreq("H") == ival_S_to_H assert ival_S_end_of_hour.asfreq("H") == ival_S_to_H assert ival_S.asfreq("Min") == ival_S_to_T diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 1e8c2bce1d90d..b1fb657bb2051 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -32,6 +32,8 @@ ) import pandas._testing as tm +bday_msg = "Period with BDay freq is deprecated" + class TestPeriodConstruction: def test_custom_business_day_freq_raises(self): @@ -142,20 +144,21 @@ def test_construction_from_timestamp_nanos(self): def test_construction_bday(self): # Biz day construction, roll forward if non-weekday - i1 = Period("3/10/12", freq="B") - i2 = Period("3/10/12", freq="D") - assert i1 == i2.asfreq("B") - i2 = Period("3/11/12", freq="D") - assert i1 == i2.asfreq("B") - i2 = Period("3/12/12", freq="D") - assert i1 == i2.asfreq("B") - - i3 = Period("3/10/12", freq="b") - assert i1 == i3 - - i1 = Period(year=2012, month=3, day=10, freq="B") - i2 = Period("3/12/12", freq="B") - assert i1 == i2 + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + i1 = Period("3/10/12", freq="B") + i2 = Period("3/10/12", freq="D") + assert i1 == i2.asfreq("B") + i2 = Period("3/11/12", freq="D") + assert i1 == i2.asfreq("B") + i2 = Period("3/12/12", freq="D") + assert i1 == i2.asfreq("B") + + i3 = Period("3/10/12", freq="b") + assert i1 == i3 + + i1 = Period(year=2012, month=3, day=10, freq="B") + i2 = Period("3/12/12", freq="B") + assert i1 == i2 def test_construction_quarter(self): i1 = Period(year=2005, quarter=1, freq="Q") @@ -226,9 +229,10 @@ def test_period_constructor_offsets(self): ) assert Period("2005", freq=offsets.YearEnd()) == Period("2005", freq="A") assert Period("2005", freq=offsets.MonthEnd()) == Period("2005", freq="M") - assert Period("3/10/12", freq=offsets.BusinessDay()) == Period( - "3/10/12", freq="B" - ) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period("3/10/12", freq=offsets.BusinessDay()) == Period( + "3/10/12", freq="B" + ) assert Period("3/10/12", freq=offsets.Day()) == Period("3/10/12", freq="D") assert Period( @@ -241,17 +245,19 @@ def test_period_constructor_offsets(self): assert Period(year=2005, month=3, day=1, freq=offsets.Day()) == Period( year=2005, month=3, day=1, freq="D" ) - assert Period(year=2012, month=3, day=10, freq=offsets.BDay()) == Period( - year=2012, month=3, day=10, freq="B" - ) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period(year=2012, month=3, day=10, freq=offsets.BDay()) == Period( + year=2012, month=3, day=10, freq="B" + ) expected = Period("2005-03-01", freq="3D") assert Period(year=2005, month=3, day=1, freq=offsets.Day(3)) == expected assert Period(year=2005, month=3, day=1, freq="3D") == expected - assert Period(year=2012, month=3, day=10, freq=offsets.BDay(3)) == Period( - year=2012, month=3, day=10, freq="3B" - ) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period(year=2012, month=3, day=10, freq=offsets.BDay(3)) == Period( + year=2012, month=3, day=10, freq="3B" + ) assert Period(200701, freq=offsets.MonthEnd()) == Period(200701, freq="M") @@ -614,6 +620,9 @@ def test_to_timestamp_mult(self): expected = Timestamp("2011-04-01") - Timedelta(1, "ns") assert p.to_timestamp(how="E") == expected + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) def test_to_timestamp(self): p = Period("1982", freq="A") start_ts = p.to_timestamp(how="S") @@ -678,8 +687,9 @@ def _ex(p): assert result == expected def test_to_timestamp_business_end(self): - per = Period("1990-01-05", "B") # Friday - result = per.to_timestamp("B", how="E") + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per = Period("1990-01-05", "B") # Friday + result = per.to_timestamp("B", how="E") expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1) assert result == expected @@ -733,6 +743,9 @@ def test_to_timestamp_microsecond(self, ts, expected, freq): ("2000-12-15", "B", "2000-12-15", "B"), ), ) + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) def test_repr(self, str_ts, freq, str_res, str_freq): p = Period(str_ts, freq=freq) assert str(p) == str_res @@ -790,6 +803,9 @@ def test_freq_str(self): assert i1.freq == offsets.Minute() assert i1.freqstr == "T" + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) def test_period_deprecated_freq(self): cases = { "M": ["MTH", "MONTH", "MONTHLY", "Mth", "month", "monthly"], @@ -853,7 +869,8 @@ def test_start_time(self): for f in freq_lst: p = Period("2012", freq=f) assert p.start_time == xp - assert Period("2012", freq="B").start_time == datetime(2012, 1, 2) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period("2012", freq="B").start_time == datetime(2012, 1, 2) assert Period("2012", freq="W").start_time == datetime(2011, 12, 26) def test_end_time(self): @@ -881,9 +898,10 @@ def _ex(*args): xp = _ex(2012, 1, 1, 1) assert xp == p.end_time - p = Period("2012", freq="B") - xp = _ex(2012, 1, 3) - assert xp == p.end_time + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + p = Period("2012", freq="B") + xp = _ex(2012, 1, 3) + assert xp == p.end_time p = Period("2012", freq="W") xp = _ex(2012, 1, 2) @@ -904,8 +922,9 @@ def _ex(*args): def test_end_time_business_friday(self): # GH#34449 - per = Period("1990-01-05", "B") - result = per.end_time + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per = Period("1990-01-05", "B") + result = per.end_time expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1) assert result == expected @@ -981,7 +1000,8 @@ def test_properties_weekly_legacy(self): def test_properties_daily(self): # Test properties on Periods with daily frequency. - b_date = Period(freq="B", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + b_date = Period(freq="B", year=2007, month=1, day=1) # assert b_date.year == 2007 assert b_date.quarter == 1 @@ -990,7 +1010,8 @@ def test_properties_daily(self): assert b_date.weekday == 0 assert b_date.dayofyear == 1 assert b_date.days_in_month == 31 - assert Period(freq="B", year=2012, month=2, day=1).days_in_month == 29 + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert Period(freq="B", year=2012, month=2, day=1).days_in_month == 29 d_date = Period(freq="D", year=2007, month=1, day=1) @@ -1582,7 +1603,8 @@ def test_negone_ordinals(): repr(period) assert period.year == 1969 - period = Period(ordinal=-1, freq="B") + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + period = Period(ordinal=-1, freq="B") repr(period) period = Period(ordinal=-1, freq="W") repr(period)
- [x] closes #53446 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. There's a place in the plotting code where we apparently cast to Period, not sure why that would be necessary. Need to find an alternative before the deprecation is enforced.
https://api.github.com/repos/pandas-dev/pandas/pulls/53511
2023-06-03T03:21:20Z
2023-07-24T17:35:42Z
2023-07-24T17:35:42Z
2023-07-24T18:34:37Z
STY: Enable Ruff specific checks
diff --git a/pandas/_config/config.py b/pandas/_config/config.py index e14f51df24a8a..920a33d39e1d1 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -66,8 +66,10 @@ ) import warnings -from pandas._typing import F # noqa: TCH001 -from pandas._typing import T # noqa: TCH001 +from pandas._typing import ( + F, + T, +) from pandas.util._exceptions import find_stack_level diff --git a/pandas/_libs/__init__.py b/pandas/_libs/__init__.py index 29ed375134a2b..b084a25917163 100644 --- a/pandas/_libs/__init__.py +++ b/pandas/_libs/__init__.py @@ -13,7 +13,7 @@ # Below imports needs to happen first to ensure pandas top level # module gets monkeypatched with the pandas_datetime_CAPI # see pandas_datetime_exec in pd_datetime.c -import pandas._libs.pandas_parser # noqa: F401,E501 # isort: skip # type: ignore[reportUnusedImport] +import pandas._libs.pandas_parser # noqa: E501 # isort: skip # type: ignore[reportUnusedImport] import pandas._libs.pandas_datetime # noqa: F401,E501 # isort: skip # type: ignore[reportUnusedImport] from pandas._libs.interval import Interval from pandas._libs.tslibs import ( diff --git a/pandas/api/types/__init__.py b/pandas/api/types/__init__.py index fb1abdd5b18ec..c601086bb9f86 100644 --- a/pandas/api/types/__init__.py +++ b/pandas/api/types/__init__.py @@ -4,7 +4,7 @@ from pandas._libs.lib import infer_dtype -from pandas.core.dtypes.api import * # noqa: F401, F403 +from pandas.core.dtypes.api import * # noqa: F403 from pandas.core.dtypes.concat import union_categoricals from pandas.core.dtypes.dtypes import ( CategoricalDtype, diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 2d0ec66dbc9cb..34a7c0c0fc10f 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -1992,7 +1992,7 @@ class ArrowDtype(StorageExtensionDtype): timestamp[s, tz=America/New_York][pyarrow] >>> pd.ArrowDtype(pa.list_(pa.int64())) list<item: int64>[pyarrow] - """ # noqa: E501 + """ _metadata = ("storage", "pyarrow_dtype") # type: ignore[assignment] diff --git a/pyproject.toml b/pyproject.toml index 4440c65cfb777..6f91aa2360406 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -236,7 +236,9 @@ select = [ # comprehensions "C4", # pygrep-hooks - "PGH" + "PGH", + # Ruff-specific rules + "RUF", ] ignore = [ @@ -308,6 +310,18 @@ ignore = [ "PLR2004", # Consider `elif` instead of `else` then `if` to remove indentation level "PLR5501", + # ambiguous-unicode-character-string + "RUF001", + # ambiguous-unicode-character-docstring + "RUF002", + # ambiguous-unicode-character-comment + "RUF003", + # collection-literal-concatenation + "RUF005", + # pairwise-over-zipped (>=PY310 only) + "RUF007", + # explicit-f-string-type-conversion + "RUF010" ] exclude = [
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53510
2023-06-02T22:55:10Z
2023-06-03T00:02:39Z
2023-06-03T00:02:38Z
2023-06-03T00:02:42Z
DOC: Added Nav Links to Discussion and Development section on README
diff --git a/README.md b/README.md index bbe080c52ab9b..1bff2941f86ca 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,13 @@ For usage questions, the best place to go to is [StackOverflow](https://stackove Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata). ## Discussion and Development -Most development discussions take place on GitHub in this repo. Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Slack channel](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) is available for quick development related questions. +Most development discussions take place on GitHub in this repo, via the [GitHub issue tracker](https://github.com/pandas-dev/pandas/issues). + +Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Slack channel](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) is available for quick development related questions. + +There are also frequent [community meetings](https://pandas.pydata.org/docs/dev/development/community.html#community-meeting) for project maintainers open to the community as well as monthly [new contributor meetings](https://pandas.pydata.org/docs/dev/development/community.html#new-contributor-meeting) to help support new contributors. + +Additional information on the communication channels can be found on the [contributor community](https://pandas.pydata.org/docs/development/community.html) page. ## Contributing to pandas
- [x] closes #53507 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. I have added a direct link to the contributor community webpage in the Discussion and Development Section on the project README and I also listed the community meetings (with links). I tested the nav links on my branch and it all works. I wanted to provide a suggestion to the issue I opened referenced above if this is helpful in aiding future contributors and their understanding of the communication channels.
https://api.github.com/repos/pandas-dev/pandas/pulls/53509
2023-06-02T22:13:25Z
2023-06-05T18:01:02Z
2023-06-05T18:01:02Z
2023-06-05T18:01:10Z
CI: Bump builds to 3.11, update numpy nightly wheels location
diff --git a/.circleci/config.yml b/.circleci/config.yml index 999bba1f9f77f..dfaade1d69c75 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -6,7 +6,7 @@ jobs: image: ubuntu-2004:2022.04.1 resource_class: arm.large environment: - ENV_FILE: ci/deps/circle-39-arm64.yaml + ENV_FILE: ci/deps/circle-310-arm64.yaml PYTEST_WORKERS: auto PATTERN: "not single_cpu and not slow and not network and not clipboard and not arm_slow and not db" PYTEST_TARGET: "pandas" diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index bec07c077ad59..9ebe147008451 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -31,14 +31,14 @@ jobs: pattern: [""] include: - name: "Downstream Compat" - env_file: actions-39-downstream_compat.yaml + env_file: actions-311-downstream_compat.yaml pattern: "not slow and not network and not single_cpu" pytest_target: "pandas/tests/test_downstream.py" - name: "Minimum Versions" env_file: actions-39-minimum_versions.yaml pattern: "not slow and not network and not single_cpu" - name: "Locale: it_IT" - env_file: actions-310.yaml + env_file: actions-311.yaml pattern: "not slow and not network and not single_cpu" extra_apt: "language-pack-it" # Use the utf8 version as the default, it has no bad side-effect. @@ -48,7 +48,7 @@ jobs: # It will be temporarily activated during tests with locale.setlocale extra_loc: "it_IT" - name: "Locale: zh_CN" - env_file: actions-310.yaml + env_file: actions-311.yaml pattern: "not slow and not network and not single_cpu" extra_apt: "language-pack-zh-hans" # Use the utf8 version as the default, it has no bad side-effect. @@ -58,7 +58,7 @@ jobs: # It will be temporarily activated during tests with locale.setlocale extra_loc: "zh_CN" - name: "Copy-on-Write" - env_file: actions-310.yaml + env_file: actions-311.yaml pattern: "not slow and not network and not single_cpu" pandas_copy_on_write: "1" - name: "Pypy" @@ -66,7 +66,7 @@ jobs: pattern: "not slow and not network and not single_cpu" test_args: "--max-worker-restart 0" - name: "Numpy Dev" - env_file: actions-310-numpydev.yaml + env_file: actions-311-numpydev.yaml pattern: "not slow and not network and not single_cpu" test_args: "-W error::DeprecationWarning -W error::FutureWarning" # TODO(cython3): Re-enable once next-beta(after beta 1) comes out diff --git a/ci/deps/actions-39-downstream_compat.yaml b/ci/deps/actions-311-downstream_compat.yaml similarity index 98% rename from ci/deps/actions-39-downstream_compat.yaml rename to ci/deps/actions-311-downstream_compat.yaml index a036849cf01ba..2115ee8f7d86a 100644 --- a/ci/deps/actions-39-downstream_compat.yaml +++ b/ci/deps/actions-311-downstream_compat.yaml @@ -3,7 +3,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.9 + - python=3.11 # build dependencies - versioneer[toml] diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-311-numpydev.yaml similarity index 84% rename from ci/deps/actions-310-numpydev.yaml rename to ci/deps/actions-311-numpydev.yaml index 4556b4567f2e0..5379c2fddec21 100644 --- a/ci/deps/actions-310-numpydev.yaml +++ b/ci/deps/actions-311-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.10 + - python=3.11 # build dependencies - versioneer[toml] @@ -26,7 +26,7 @@ dependencies: - pip: - "cython" - - "--extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple" + - "--extra-index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple" - "--pre" - "numpy" - "scipy" diff --git a/ci/deps/circle-39-arm64.yaml b/ci/deps/circle-310-arm64.yaml similarity index 98% rename from ci/deps/circle-39-arm64.yaml rename to ci/deps/circle-310-arm64.yaml index 37e01d2d0b2f9..1813dbe3a1df5 100644 --- a/ci/deps/circle-39-arm64.yaml +++ b/ci/deps/circle-310-arm64.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.9 + - python=3.10 # build dependencies - versioneer[toml] diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index b63f3f28b8f6c..0c0b312c11c48 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -424,7 +424,7 @@ def lexsort_indexer( def nargsort( items: ArrayLike | Index | Series, - kind: SortKind = "quicksort", + kind: SortKind = "stable", ascending: bool = True, na_position: str = "last", key: Callable | None = None, diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 86b4e399fa461..7220b44c7af9d 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1140,7 +1140,7 @@ def _validate(self): if not isinstance(self.win_type, str): raise ValueError(f"Invalid win_type {self.win_type}") signal = import_optional_dependency( - "scipy.signal", extra="Scipy is required to generate window weight." + "scipy.signal.windows", extra="Scipy is required to generate window weight." ) self._scipy_weight_generator = getattr(signal, self.win_type, None) if self._scipy_weight_generator is None:
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53508
2023-06-02T22:10:47Z
2023-06-06T18:04:27Z
2023-06-06T18:04:27Z
2023-06-06T18:17:11Z
Cython Groupby unused argument removal
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 796ebaca14c91..61f448cbe0c3f 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -495,7 +495,6 @@ def group_fillna_indexer( ndarray[intp_t] labels, ndarray[intp_t] sorted_labels, ndarray[uint8_t] mask, - str direction, int64_t limit, bint dropna, ) -> None: @@ -510,14 +509,11 @@ def group_fillna_indexer( Array containing unique label for each group, with its ordering matching up to the corresponding record in `values`. sorted_labels : np.ndarray[np.intp] - obtained by `np.argsort(labels, kind="mergesort")`; reversed if - direction == "bfill" + obtained by `np.argsort(labels, kind="mergesort")` values : np.ndarray[np.uint8] Containing the truth value of each element. mask : np.ndarray[np.uint8] Indicating whether a value is na or not. - direction : {'ffill', 'bfill'} - Direction for fill to be applied (forwards or backwards, respectively) limit : Consecutive values to fill before stopping, or -1 for no limit dropna : Flag to indicate if NaN groups should return all NaN values diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index bdab641719ded..caed6c9747d3b 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2924,7 +2924,6 @@ def _fill(self, direction: Literal["ffill", "bfill"], limit: int | None = None): libgroupby.group_fillna_indexer, labels=ids, sorted_labels=sorted_labels, - direction=direction, limit=limit, dropna=self.dropna, )
Seeing these cleanups going through the exercise of building in Rust
https://api.github.com/repos/pandas-dev/pandas/pulls/53506
2023-06-02T20:58:29Z
2023-06-03T20:53:42Z
2023-06-03T20:53:42Z
2023-06-03T20:53:42Z
BUG: reindex with expansion and non-nanosecond dtype
diff --git a/doc/source/whatsnew/v2.0.3.rst b/doc/source/whatsnew/v2.0.3.rst index 3da469c2e1fe6..a40d8e333abed 100644 --- a/doc/source/whatsnew/v2.0.3.rst +++ b/doc/source/whatsnew/v2.0.3.rst @@ -22,6 +22,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Bug in :func:`RangeIndex.union` when using ``sort=True`` with another :class:`RangeIndex` (:issue:`53490`) +- Bug in :func:`Series.reindex` when expanding a non-nanosecond datetime or timedelta :class:`Series` would not fill with ``NaT`` correctly (:issue:`53497`) - Bug in :func:`read_csv` when defining ``dtype`` with ``bool[pyarrow]`` for the ``"c"`` and ``"python"`` engines (:issue:`53390`) - Bug in :meth:`Series.str.split` and :meth:`Series.str.rsplit` with ``expand=True`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`53532`) - diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 831b368f58225..be23911165138 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -562,9 +562,16 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan): If fill_value is a non-scalar and dtype is not object. """ orig = fill_value + orig_is_nat = False if checknull(fill_value): # https://github.com/pandas-dev/pandas/pull/39692#issuecomment-1441051740 # avoid cache misses with NaN/NaT values that are not singletons + if fill_value is not NA: + try: + orig_is_nat = np.isnat(fill_value) + except TypeError: + pass + fill_value = _canonical_nans.get(type(fill_value), fill_value) # for performance, we are using a cached version of the actual implementation @@ -580,8 +587,10 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan): # if fill_value is not hashable (required for caching) dtype, fill_value = _maybe_promote(dtype, fill_value) - if dtype == _dtype_obj and orig is not None: - # GH#51592 restore our potentially non-canonical fill_value + if (dtype == _dtype_obj and orig is not None) or ( + orig_is_nat and np.datetime_data(orig)[0] != "ns" + ): + # GH#51592,53497 restore our potentially non-canonical fill_value fill_value = orig return dtype, fill_value diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py index 16fc04d588a52..614002d755b6d 100644 --- a/pandas/tests/series/methods/test_reindex.py +++ b/pandas/tests/series/methods/test_reindex.py @@ -12,6 +12,7 @@ NaT, Period, PeriodIndex, + RangeIndex, Series, Timedelta, Timestamp, @@ -422,3 +423,14 @@ def test_reindexing_with_float64_NA_log(): result_log = np.log(s_reindex) expected_log = Series([0, np.NaN, np.NaN], dtype=Float64Dtype()) tm.assert_series_equal(result_log, expected_log) + + +@pytest.mark.parametrize("dtype", ["timedelta64", "datetime64"]) +def test_reindex_expand_nonnano_nat(dtype): + # GH 53497 + ser = Series(np.array([1], dtype=f"{dtype}[s]")) + result = ser.reindex(RangeIndex(2)) + expected = Series( + np.array([1, getattr(np, dtype)("nat", "s")], dtype=f"{dtype}[s]") + ) + tm.assert_series_equal(result, expected)
- [x] closes #53497 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/53505
2023-06-02T20:55:22Z
2023-06-20T20:44:36Z
2023-06-20T20:44:36Z
2023-06-21T15:25:52Z
DOC: Add Visible Table of Contents to Project README Documentation
diff --git a/README.md b/README.md index 9f2bc800e8479..bbe080c52ab9b 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,19 @@ the broader goal of becoming **the most powerful and flexible open source data analysis / manipulation tool available in any language**. It is already well on its way towards this goal. +## Table of Contents + +- [Main Features](#main-features) +- [Where to get it](#where-to-get-it) +- [Dependencies](#dependencies) +- [Installation from sources](#installation-from-sources) +- [License](#license) +- [Documentation](#documentation) +- [Background](#background) +- [Getting Help](#getting-help) +- [Discussion and Development](#discussion-and-development) +- [Contributing to pandas](#contributing-to-pandas) + ## Main Features Here are just a few of the things that pandas does well: @@ -157,7 +170,9 @@ Further, general questions and discussions can also take place on the [pydata ma ## Discussion and Development Most development discussions take place on GitHub in this repo. Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Slack channel](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) is available for quick development related questions. -## Contributing to pandas [![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas) +## Contributing to pandas + +[![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas) All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome. @@ -172,3 +187,7 @@ Or maybe through using pandas you have an idea of your own or are looking for so Feel free to ask questions on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Slack](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack). As contributors and maintainers to this project, you are expected to abide by pandas' code of conduct. More information can be found at: [Contributor Code of Conduct](https://github.com/pandas-dev/.github/blob/master/CODE_OF_CONDUCT.md) + +<hr> + +[Go to Top](#table-of-contents)
- [x] closes #53503 I have added a table of contents to the projects main README markdown file on my feature branch. I applied the same header styling to match the rest of the README. I tested the links on my branch and it all works. I typically look for a table of contents on READMEs and I find it to be a valuable resource so I wanted to provide a suggestion to the issue I opened referenced above.
https://api.github.com/repos/pandas-dev/pandas/pulls/53504
2023-06-02T17:59:33Z
2023-06-02T20:59:27Z
2023-06-02T20:59:27Z
2023-06-02T20:59:35Z
DEPR: deprecated `sheetname` from ExcelFile.parse
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index c194d98a89789..c463043b388a6 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -956,6 +956,7 @@ Deprecations retain the previous behavior, use a list instead of a tuple (:issue:`18314`) - ``Series.valid`` is deprecated. Use :meth:`Series.dropna` instead (:issue:`18800`). - :func:`read_excel` has deprecated the ``skip_footer`` parameter. Use ``skipfooter`` instead (:issue:`18836`) +- :meth:`ExcelFile.parse` has deprecated ``sheetname`` in favor of ``sheet_name`` for consistency with :func:`read_excel` (:issue:`20920`). - The ``is_copy`` attribute is deprecated and will be removed in a future version (:issue:`18801`). - ``IntervalIndex.from_intervals`` is deprecated in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) - ``DataFrame.from_items`` is deprecated. Use :func:`DataFrame.from_dict` instead, or ``DataFrame.from_dict(OrderedDict())`` if you wish to preserve the key order (:issue:`17320`, :issue:`17312`) diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 5bce37b9d7735..5608c29637447 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -303,20 +303,11 @@ def read_excel(io, convert_float=True, **kwds): - # Can't use _deprecate_kwarg since sheetname=None has a special meaning - if is_integer(sheet_name) and sheet_name == 0 and 'sheetname' in kwds: - warnings.warn("The `sheetname` keyword is deprecated, use " - "`sheet_name` instead", FutureWarning, stacklevel=2) - sheet_name = kwds.pop("sheetname") - elif 'sheetname' in kwds: - raise TypeError("Cannot specify both `sheet_name` and `sheetname`. " - "Use just `sheet_name`") - if not isinstance(io, ExcelFile): io = ExcelFile(io, engine=engine) - return io._parse_excel( - sheetname=sheet_name, + return io.parse( + sheet_name=sheet_name, header=header, names=names, index_col=index_col, @@ -435,7 +426,16 @@ def parse(self, docstring for more info on accepted parameters """ - return self._parse_excel(sheetname=sheet_name, + # Can't use _deprecate_kwarg since sheetname=None has a special meaning + if is_integer(sheet_name) and sheet_name == 0 and 'sheetname' in kwds: + warnings.warn("The `sheetname` keyword is deprecated, use " + "`sheet_name` instead", FutureWarning, stacklevel=2) + sheet_name = kwds.pop("sheetname") + elif 'sheetname' in kwds: + raise TypeError("Cannot specify both `sheet_name` " + "and `sheetname`. Use just `sheet_name`") + + return self._parse_excel(sheet_name=sheet_name, header=header, names=names, index_col=index_col, @@ -489,7 +489,7 @@ def _excel2num(x): return i in usecols def _parse_excel(self, - sheetname=0, + sheet_name=0, header=0, names=None, index_col=None, @@ -585,14 +585,14 @@ def _parse_cell(cell_contents, cell_typ): ret_dict = False # Keep sheetname to maintain backwards compatibility. - if isinstance(sheetname, list): - sheets = sheetname + if isinstance(sheet_name, list): + sheets = sheet_name ret_dict = True - elif sheetname is None: + elif sheet_name is None: sheets = self.sheet_names ret_dict = True else: - sheets = [sheetname] + sheets = [sheet_name] # handle same-type duplicates. sheets = list(OrderedDict.fromkeys(sheets).keys()) diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 5ef6dc07a5c22..05423474f330a 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -503,20 +503,35 @@ def test_sheet_name_and_sheetname(self, ext): # GH10559: Minor improvement: Change "sheet_name" to "sheetname" # GH10969: DOC: Consistent var names (sheetname vs sheet_name) # GH12604: CLN GH10559 Rename sheetname variable to sheet_name + # GH20920: ExcelFile.parse() and pd.read_xlsx() have different + # behavior for "sheetname" argument dfref = self.get_csv_refdf('test1') - df1 = self.get_exceldf('test1', ext, sheet_name='Sheet1') # doc + df1 = self.get_exceldf('test1', ext, + sheet_name='Sheet1') # doc with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): df2 = self.get_exceldf('test1', ext, sheetname='Sheet1') # bkwrd compat + excel = self.get_excelfile('test1', ext) + df1_parse = excel.parse(sheet_name='Sheet1') # doc + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + df2_parse = excel.parse(sheetname='Sheet1') # bkwrd compat + tm.assert_frame_equal(df1, dfref, check_names=False) tm.assert_frame_equal(df2, dfref, check_names=False) + tm.assert_frame_equal(df1_parse, dfref, check_names=False) + tm.assert_frame_equal(df2_parse, dfref, check_names=False) def test_sheet_name_both_raises(self, ext): with tm.assert_raises_regex(TypeError, "Cannot specify both"): self.get_exceldf('test1', ext, sheetname='Sheet1', sheet_name='Sheet1') + excel = self.get_excelfile('test1', ext) + with tm.assert_raises_regex(TypeError, "Cannot specify both"): + excel.parse(sheetname='Sheet1', + sheet_name='Sheet1') + @pytest.mark.parametrize("ext", ['.xls', '.xlsx', '.xlsm']) class TestXlrdReader(ReadingTestsBase):
* ExcelFile.parse * Made to raise FutureWarning and TypeError when using `sheetname` * ExcelFile._parse_excel * Changed parameter name from `sheetname` to `sheet_name` - [ ] closes #20920 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20938
2018-05-03T01:02:09Z
2018-05-04T10:09:39Z
2018-05-04T10:09:39Z
2018-05-04T10:09:45Z
CLN: removed unused "convert" parameter to _take
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7a2bd2708b711..ffb124af4f5fc 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2641,7 +2641,7 @@ def _ixs(self, i, axis=0): return self.loc[:, lab_slice] else: if isinstance(label, Index): - return self._take(i, axis=1, convert=True) + return self._take(i, axis=1) index_len = len(self.index) @@ -2720,10 +2720,10 @@ def _getitem_array(self, key): # be reindexed to match DataFrame rows key = check_bool_indexer(self.index, key) indexer = key.nonzero()[0] - return self._take(indexer, axis=0, convert=False) + return self._take(indexer, axis=0) else: indexer = self.loc._convert_to_indexer(key, axis=1) - return self._take(indexer, axis=1, convert=True) + return self._take(indexer, axis=1) def _getitem_multilevel(self, key): loc = self.columns.get_loc(key) @@ -4292,7 +4292,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None, else: raise TypeError('must specify how or thresh') - result = self._take(mask.nonzero()[0], axis=axis, convert=False) + result = self._take(mask.nonzero()[0], axis=axis) if inplace: self._update_inplace(result) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 96340f9e82992..e96a2a9f08520 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -37,7 +37,6 @@ from pandas.core.index import (Index, MultiIndex, _ensure_index, InvalidIndexError, RangeIndex) import pandas.core.indexing as indexing -from pandas.core.indexing import maybe_convert_indices from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.period import PeriodIndex, Period from pandas.core.internals import BlockManager @@ -2510,8 +2509,7 @@ def _iget_item_cache(self, item): if ax.is_unique: lower = self._get_item_cache(ax[item]) else: - lower = self._take(item, axis=self._info_axis_number, - convert=True) + lower = self._take(item, axis=self._info_axis_number) return lower def _box_item_values(self, key, values): @@ -2765,11 +2763,6 @@ def __delitem__(self, key): axis : int, default 0 The axis on which to select elements. "0" means that we are selecting rows, "1" means that we are selecting columns, etc. - convert : bool, default True - Whether to convert negative indices into positive ones. - For example, ``-1`` would map to the ``len(axis) - 1``. - The conversions are similar to the behavior of indexing a - regular Python list. is_copy : bool, default True Whether to return a copy of the original object or not. @@ -2785,12 +2778,9 @@ def __delitem__(self, key): """ @Appender(_shared_docs['_take']) - def _take(self, indices, axis=0, convert=True, is_copy=True): + def _take(self, indices, axis=0, is_copy=True): self._consolidate_inplace() - if convert: - indices = maybe_convert_indices(indices, len(self._get_axis(axis))) - new_data = self._data.take(indices, axis=self._get_block_manager_axis(axis), verify=True) @@ -2893,11 +2883,9 @@ def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs): msg = ("The 'convert' parameter is deprecated " "and will be removed in a future version.") warnings.warn(msg, FutureWarning, stacklevel=2) - else: - convert = True - convert = nv.validate_take(tuple(), kwargs) - return self._take(indices, axis=axis, convert=convert, is_copy=is_copy) + nv.validate_take(tuple(), kwargs) + return self._take(indices, axis=axis, is_copy=is_copy) def xs(self, key, axis=0, level=None, drop_level=True): """ @@ -2998,9 +2986,9 @@ def xs(self, key, axis=0, level=None, drop_level=True): if isinstance(loc, np.ndarray): if loc.dtype == np.bool_: inds, = loc.nonzero() - return self._take(inds, axis=axis, convert=False) + return self._take(inds, axis=axis) else: - return self._take(loc, axis=axis, convert=True) + return self._take(loc, axis=axis) if not is_scalar(loc): new_index = self.index[loc] @@ -6784,7 +6772,7 @@ def at_time(self, time, asof=False): """ try: indexer = self.index.indexer_at_time(time, asof=asof) - return self._take(indexer, convert=False) + return self._take(indexer) except AttributeError: raise TypeError('Index must be DatetimeIndex') @@ -6808,7 +6796,7 @@ def between_time(self, start_time, end_time, include_start=True, indexer = self.index.indexer_between_time( start_time, end_time, include_start=include_start, include_end=include_end) - return self._take(indexer, convert=False) + return self._take(indexer) except AttributeError: raise TypeError('Index must be DatetimeIndex') diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 2fe1f303236bb..f78f7cb625218 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -508,8 +508,7 @@ def _set_grouper(self, obj, sort=False): # use stable sort to support first, last, nth indexer = self.indexer = ax.argsort(kind='mergesort') ax = ax.take(indexer) - obj = obj._take(indexer, axis=self.axis, - convert=False, is_copy=False) + obj = obj._take(indexer, axis=self.axis, is_copy=False) self.obj = obj self.grouper = ax @@ -860,7 +859,7 @@ def get_group(self, name, obj=None): if not len(inds): raise KeyError(name) - return obj._take(inds, axis=self.axis, convert=False) + return obj._take(inds, axis=self.axis) def __iter__(self): """ @@ -1437,9 +1436,9 @@ def last(x): cls.min = groupby_function('min', 'min', np.min, numeric_only=False) cls.max = groupby_function('max', 'max', np.max, numeric_only=False) cls.first = groupby_function('first', 'first', first_compat, - numeric_only=False, _convert=True) + numeric_only=False) cls.last = groupby_function('last', 'last', last_compat, - numeric_only=False, _convert=True) + numeric_only=False) @Substitution(name='groupby') @Appender(_doc_template) @@ -2653,7 +2652,7 @@ def _aggregate_series_fast(self, obj, func): # avoids object / Series creation overhead dummy = obj._get_values(slice(None, 0)).to_dense() indexer = get_group_index_sorter(group_index, ngroups) - obj = obj._take(indexer, convert=False).to_dense() + obj = obj._take(indexer).to_dense() group_index = algorithms.take_nd( group_index, indexer, allow_fill=False) grouper = reduction.SeriesGrouper(obj, func, group_index, ngroups, @@ -5032,7 +5031,7 @@ def __iter__(self): yield i, self._chop(sdata, slice(start, end)) def _get_sorted_data(self): - return self.data._take(self.sort_idx, axis=self.axis, convert=False) + return self.data._take(self.sort_idx, axis=self.axis) def _chop(self, sdata, slice_obj): return sdata.iloc[slice_obj] diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index d23beba1c534d..7a7e47803c240 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1126,7 +1126,7 @@ def _getitem_iterable(self, key, axis=None): if com.is_bool_indexer(key): key = check_bool_indexer(labels, key) inds, = key.nonzero() - return self.obj._take(inds, axis=axis, convert=False) + return self.obj._take(inds, axis=axis) else: # Have the index compute an indexer or return None # if it cannot handle; we only act on all found values @@ -1158,8 +1158,7 @@ def _getitem_iterable(self, key, axis=None): keyarr) if new_indexer is not None: - result = self.obj._take(indexer[indexer != -1], axis=axis, - convert=False) + result = self.obj._take(indexer[indexer != -1], axis=axis) self._validate_read_indexer(key, new_indexer, axis) result = result._reindex_with_indexers( @@ -1356,7 +1355,7 @@ def _get_slice_axis(self, slice_obj, axis=None): if isinstance(indexer, slice): return self._slice(indexer, axis=axis, kind='iloc') else: - return self.obj._take(indexer, axis=axis, convert=False) + return self.obj._take(indexer, axis=axis) class _IXIndexer(_NDFrameIndexer): @@ -1494,7 +1493,7 @@ def _getbool_axis(self, key, axis=None): key = check_bool_indexer(labels, key) inds, = key.nonzero() try: - return self.obj._take(inds, axis=axis, convert=False) + return self.obj._take(inds, axis=axis) except Exception as detail: raise self._exception(detail) @@ -1514,7 +1513,7 @@ def _get_slice_axis(self, slice_obj, axis=None): if isinstance(indexer, slice): return self._slice(indexer, axis=axis, kind='iloc') else: - return self.obj._take(indexer, axis=axis, convert=False) + return self.obj._take(indexer, axis=axis) class _LocIndexer(_LocationIndexer): @@ -2050,7 +2049,7 @@ def _get_slice_axis(self, slice_obj, axis=None): if isinstance(slice_obj, slice): return self._slice(slice_obj, axis=axis, kind='iloc') else: - return self.obj._take(slice_obj, axis=axis, convert=False) + return self.obj._take(slice_obj, axis=axis) def _get_list_axis(self, key, axis=None): """ @@ -2068,7 +2067,7 @@ def _get_list_axis(self, key, axis=None): if axis is None: axis = self.axis or 0 try: - return self.obj._take(key, axis=axis, convert=False) + return self.obj._take(key, axis=axis) except IndexError: # re-raise with different error message raise IndexError("positional indexers are out-of-bounds") diff --git a/pandas/core/series.py b/pandas/core/series.py index 951227f381b1c..0e2ae22f35af7 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3503,9 +3503,7 @@ def memory_usage(self, index=True, deep=False): return v @Appender(generic._shared_docs['_take']) - def _take(self, indices, axis=0, convert=True, is_copy=False): - if convert: - indices = maybe_convert_indices(indices, len(self._get_axis(axis))) + def _take(self, indices, axis=0, is_copy=False): indices = _ensure_platform_int(indices) new_index = self.index.take(indices) @@ -3513,6 +3511,7 @@ def _take(self, indices, axis=0, convert=True, is_copy=False): if is_categorical_dtype(self): # https://github.com/pandas-dev/pandas/issues/20664 # TODO: remove when the default Categorical.take behavior changes + indices = maybe_convert_indices(indices, len(self._get_axis(axis))) kwargs = {'allow_fill': False} else: kwargs = {}
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Followup to #20841: the ``convert`` parameter to ``_take`` is irrelevant: the conversion of negative to positive indices is required only for ``Categorical``s (and only until we normalize their ``take`` behavior with negative indices).
https://api.github.com/repos/pandas-dev/pandas/pulls/20934
2018-05-02T21:40:48Z
2018-05-03T00:23:48Z
2018-05-03T00:23:48Z
2018-05-03T05:42:34Z
Fixes Update docs on reserved attributes #20878
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 66d183d910000..e834efd1cb6d1 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -96,7 +96,7 @@ of multi-axis indexing. .. versionadded:: 0.18.1 - See more at :ref:`Selection by Position <indexing.integer>`, + See more at :ref:`Selection by Position <indexing.integer>`, :ref:`Advanced Indexing <advanced>` and :ref:`Advanced Hierarchical <advanced.advanced_hierarchical>`. @@ -125,7 +125,7 @@ Basics As mentioned when introducing the data structures in the :ref:`last section <basics>`, the primary function of indexing with ``[]`` (a.k.a. ``__getitem__`` for those familiar with implementing class behavior in Python) is selecting out -lower-dimensional slices. The following table shows return type values when +lower-dimensional slices. The following table shows return type values when indexing pandas objects with ``[]``: .. csv-table:: @@ -235,7 +235,7 @@ as an attribute: - The attribute will not be available if it conflicts with an existing method name, e.g. ``s.min`` is not allowed. - Similarly, the attribute will not be available if it conflicts with any of the following list: ``index``, - ``major_axis``, ``minor_axis``, ``items``, ``labels``. + ``major_axis``, ``minor_axis``, ``items``. - In any of these cases, standard indexing will still work, e.g. ``s['1']``, ``s['min']``, and ``s['index']`` will access the corresponding element or column. @@ -888,10 +888,10 @@ Boolean indexing .. _indexing.boolean: Another common operation is the use of boolean vectors to filter the data. -The operators are: ``|`` for ``or``, ``&`` for ``and``, and ``~`` for ``not``. +The operators are: ``|`` for ``or``, ``&`` for ``and``, and ``~`` for ``not``. These **must** be grouped by using parentheses, since by default Python will -evaluate an expression such as ``df.A > 2 & df.B < 3`` as -``df.A > (2 & df.B) < 3``, while the desired evaluation order is +evaluate an expression such as ``df.A > 2 & df.B < 3`` as +``df.A > (2 & df.B) < 3``, while the desired evaluation order is ``(df.A > 2) & (df.B < 3)``. Using a boolean vector to index a Series works exactly as in a NumPy ndarray: @@ -944,8 +944,8 @@ and :ref:`Advanced Indexing <advanced>` you may select along more than one axis Indexing with isin ------------------ -Consider the :meth:`~Series.isin` method of ``Series``, which returns a boolean -vector that is true wherever the ``Series`` elements exist in the passed list. +Consider the :meth:`~Series.isin` method of ``Series``, which returns a boolean +vector that is true wherever the ``Series`` elements exist in the passed list. This allows you to select rows where one or more columns have values you want: .. ipython:: python @@ -1666,7 +1666,7 @@ Set an index .. _indexing.set_index: -DataFrame has a :meth:`~DataFrame.set_index` method which takes a column name +DataFrame has a :meth:`~DataFrame.set_index` method which takes a column name (for a regular ``Index``) or a list of column names (for a ``MultiIndex``). To create a new, re-indexed DataFrame: @@ -1707,9 +1707,9 @@ the index in-place (without creating a new object): Reset the index ~~~~~~~~~~~~~~~ -As a convenience, there is a new function on DataFrame called -:meth:`~DataFrame.reset_index` which transfers the index values into the -DataFrame's columns and sets a simple integer index. +As a convenience, there is a new function on DataFrame called +:meth:`~DataFrame.reset_index` which transfers the index values into the +DataFrame's columns and sets a simple integer index. This is the inverse operation of :meth:`~DataFrame.set_index`.
- [x] closes #20878 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20933
2018-05-02T21:14:13Z
2018-05-08T00:30:29Z
2018-05-08T00:30:28Z
2018-05-08T00:30:29Z
Base Index Tests Cleanup Part 3
diff --git a/pandas/conftest.py b/pandas/conftest.py index c4aab1b632b00..137afaa3b3490 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -108,6 +108,9 @@ def nulls_fixture(request): return request.param +nulls_fixture2 = nulls_fixture # Generate cartesian product of nulls_fixture + + TIMEZONES = [None, 'UTC', 'US/Eastern', 'Asia/Tokyo', 'dateutil/US/Pacific'] diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 0a686ebdf5c3e..377b17d45265c 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -13,7 +13,7 @@ from pandas.tests.indexes.common import Base from pandas.compat import (range, lrange, lzip, u, - text_type, zip, PY3, PY36, PYPY) + text_type, zip, PY3, PY35, PY36, PYPY) import operator import numpy as np @@ -1285,150 +1285,204 @@ def test_get_indexer_numeric_index_boolean_target(self): expected = np.array([-1, -1, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) - def test_get_loc(self): - idx = pd.Index([0, 1, 2]) - all_methods = [None, 'pad', 'backfill', 'nearest'] - for method in all_methods: - assert idx.get_loc(1, method=method) == 1 - if method is not None: - assert idx.get_loc(1, method=method, tolerance=0) == 1 - with pytest.raises(TypeError): - idx.get_loc([1, 2], method=method) - - for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: - assert idx.get_loc(1.1, method) == loc - - for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: - assert idx.get_loc(1.1, method, tolerance=1) == loc - - for method in ['pad', 'backfill', 'nearest']: - with pytest.raises(KeyError): - idx.get_loc(1.1, method, tolerance=0.05) - + @pytest.mark.parametrize("method", [None, 'pad', 'backfill', 'nearest']) + def test_get_loc(self, method): + index = pd.Index([0, 1, 2]) + assert index.get_loc(1, method=method) == 1 + + if method: + assert index.get_loc(1, method=method, tolerance=0) == 1 + + @pytest.mark.parametrize("method", [None, 'pad', 'backfill', 'nearest']) + def test_get_loc_raises_bad_label(self, method): + index = pd.Index([0, 1, 2]) + if method: + # Messages vary across versions + if PY36: + msg = 'not supported between' + elif PY35: + msg = 'unorderable types' + else: + if method == 'nearest': + msg = 'unsupported operand' + else: + msg = 'requires scalar valued input' + else: + msg = 'invalid key' + + with tm.assert_raises_regex(TypeError, msg): + index.get_loc([1, 2], method=method) + + @pytest.mark.parametrize("method,loc", [ + ('pad', 1), ('backfill', 2), ('nearest', 1)]) + def test_get_loc_tolerance(self, method, loc): + index = pd.Index([0, 1, 2]) + assert index.get_loc(1.1, method) == loc + assert index.get_loc(1.1, method, tolerance=1) == loc + + @pytest.mark.parametrize("method", ['pad', 'backfill', 'nearest']) + def test_get_loc_outside_tolerance_raises(self, method): + index = pd.Index([0, 1, 2]) + with tm.assert_raises_regex(KeyError, '1.1'): + index.get_loc(1.1, method, tolerance=0.05) + + def test_get_loc_bad_tolerance_raises(self): + index = pd.Index([0, 1, 2]) with tm.assert_raises_regex(ValueError, 'must be numeric'): - idx.get_loc(1.1, 'nearest', tolerance='invalid') - with tm.assert_raises_regex(ValueError, 'tolerance .* valid if'): - idx.get_loc(1.1, tolerance=1) - with pytest.raises(ValueError, match='tolerance size must match'): - idx.get_loc(1.1, 'nearest', tolerance=[1, 1]) - - idx = pd.Index(['a', 'c']) - with pytest.raises(TypeError): - idx.get_loc('a', method='nearest') - with pytest.raises(TypeError): - idx.get_loc('a', method='pad', tolerance='invalid') - - def test_slice_locs(self): - for dtype in [int, float]: - idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype)) - n = len(idx) - - assert idx.slice_locs(start=2) == (2, n) - assert idx.slice_locs(start=3) == (3, n) - assert idx.slice_locs(3, 8) == (3, 6) - assert idx.slice_locs(5, 10) == (3, n) - assert idx.slice_locs(end=8) == (0, 6) - assert idx.slice_locs(end=9) == (0, 7) - - # reversed - idx2 = idx[::-1] - assert idx2.slice_locs(8, 2) == (2, 6) - assert idx2.slice_locs(7, 3) == (2, 5) - - # float slicing - idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=float)) - n = len(idx) - assert idx.slice_locs(5.0, 10.0) == (3, n) - assert idx.slice_locs(4.5, 10.5) == (3, 8) - idx2 = idx[::-1] - assert idx2.slice_locs(8.5, 1.5) == (2, 6) - assert idx2.slice_locs(10.5, -1) == (0, n) + index.get_loc(1.1, 'nearest', tolerance='invalid') + def test_get_loc_tolerance_no_method_raises(self): + index = pd.Index([0, 1, 2]) + with tm.assert_raises_regex(ValueError, 'tolerance .* valid if'): + index.get_loc(1.1, tolerance=1) + + def test_get_loc_raises_missized_tolerance(self): + index = pd.Index([0, 1, 2]) + with tm.assert_raises_regex(ValueError, 'tolerance size must match'): + index.get_loc(1.1, 'nearest', tolerance=[1, 1]) + + def test_get_loc_raises_object_nearest(self): + index = pd.Index(['a', 'c']) + with tm.assert_raises_regex(TypeError, 'unsupported operand type'): + index.get_loc('a', method='nearest') + + def test_get_loc_raises_object_tolerance(self): + index = pd.Index(['a', 'c']) + with tm.assert_raises_regex(TypeError, 'unsupported operand type'): + index.get_loc('a', method='pad', tolerance='invalid') + + @pytest.mark.parametrize("dtype", [int, float]) + def test_slice_locs(self, dtype): + index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype)) + n = len(index) + + assert index.slice_locs(start=2) == (2, n) + assert index.slice_locs(start=3) == (3, n) + assert index.slice_locs(3, 8) == (3, 6) + assert index.slice_locs(5, 10) == (3, n) + assert index.slice_locs(end=8) == (0, 6) + assert index.slice_locs(end=9) == (0, 7) + + # reversed + index2 = index[::-1] + assert index2.slice_locs(8, 2) == (2, 6) + assert index2.slice_locs(7, 3) == (2, 5) + + def test_slice_float_locs(self): + index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=float)) + n = len(index) + assert index.slice_locs(5.0, 10.0) == (3, n) + assert index.slice_locs(4.5, 10.5) == (3, 8) + + index2 = index[::-1] + assert index2.slice_locs(8.5, 1.5) == (2, 6) + assert index2.slice_locs(10.5, -1) == (0, n) + + @pytest.mark.xfail(reason="Assertions were not correct - see GH 20915") + def test_slice_ints_with_floats_raises(self): # int slicing with floats # GH 4892, these are all TypeErrors - idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=int)) + index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=int)) + n = len(index) + pytest.raises(TypeError, - lambda: idx.slice_locs(5.0, 10.0), (3, n)) + lambda: index.slice_locs(5.0, 10.0)) pytest.raises(TypeError, - lambda: idx.slice_locs(4.5, 10.5), (3, 8)) - idx2 = idx[::-1] + lambda: index.slice_locs(4.5, 10.5)) + + index2 = index[::-1] pytest.raises(TypeError, - lambda: idx2.slice_locs(8.5, 1.5), (2, 6)) + lambda: index2.slice_locs(8.5, 1.5), (2, 6)) pytest.raises(TypeError, - lambda: idx2.slice_locs(10.5, -1), (0, n)) + lambda: index2.slice_locs(10.5, -1), (0, n)) def test_slice_locs_dup(self): - idx = Index(['a', 'a', 'b', 'c', 'd', 'd']) - assert idx.slice_locs('a', 'd') == (0, 6) - assert idx.slice_locs(end='d') == (0, 6) - assert idx.slice_locs('a', 'c') == (0, 4) - assert idx.slice_locs('b', 'd') == (2, 6) - - idx2 = idx[::-1] - assert idx2.slice_locs('d', 'a') == (0, 6) - assert idx2.slice_locs(end='a') == (0, 6) - assert idx2.slice_locs('d', 'b') == (0, 4) - assert idx2.slice_locs('c', 'a') == (2, 6) - - for dtype in [int, float]: - idx = Index(np.array([10, 12, 12, 14], dtype=dtype)) - assert idx.slice_locs(12, 12) == (1, 3) - assert idx.slice_locs(11, 13) == (1, 3) - - idx2 = idx[::-1] - assert idx2.slice_locs(12, 12) == (1, 3) - assert idx2.slice_locs(13, 11) == (1, 3) + index = Index(['a', 'a', 'b', 'c', 'd', 'd']) + assert index.slice_locs('a', 'd') == (0, 6) + assert index.slice_locs(end='d') == (0, 6) + assert index.slice_locs('a', 'c') == (0, 4) + assert index.slice_locs('b', 'd') == (2, 6) + + index2 = index[::-1] + assert index2.slice_locs('d', 'a') == (0, 6) + assert index2.slice_locs(end='a') == (0, 6) + assert index2.slice_locs('d', 'b') == (0, 4) + assert index2.slice_locs('c', 'a') == (2, 6) + + @pytest.mark.parametrize("dtype", [int, float]) + def test_slice_locs_dup_numeric(self, dtype): + index = Index(np.array([10, 12, 12, 14], dtype=dtype)) + assert index.slice_locs(12, 12) == (1, 3) + assert index.slice_locs(11, 13) == (1, 3) + + index2 = index[::-1] + assert index2.slice_locs(12, 12) == (1, 3) + assert index2.slice_locs(13, 11) == (1, 3) def test_slice_locs_na(self): - idx = Index([np.nan, 1, 2]) - pytest.raises(KeyError, idx.slice_locs, start=1.5) - pytest.raises(KeyError, idx.slice_locs, end=1.5) - assert idx.slice_locs(1) == (1, 3) - assert idx.slice_locs(np.nan) == (0, 3) - - idx = Index([0, np.nan, np.nan, 1, 2]) - assert idx.slice_locs(np.nan) == (1, 5) - - def test_slice_locs_negative_step(self): - idx = Index(list('bcdxy')) - - SLC = pd.IndexSlice + index = Index([np.nan, 1, 2]) + assert index.slice_locs(1) == (1, 3) + assert index.slice_locs(np.nan) == (0, 3) + + index = Index([0, np.nan, np.nan, 1, 2]) + assert index.slice_locs(np.nan) == (1, 5) + + def test_slice_locs_na_raises(self): + index = Index([np.nan, 1, 2]) + with tm.assert_raises_regex(KeyError, ''): + index.slice_locs(start=1.5) + + with tm.assert_raises_regex(KeyError, ''): + index.slice_locs(end=1.5) + + @pytest.mark.parametrize("in_slice,expected", [ + (pd.IndexSlice[::-1], 'yxdcb'), (pd.IndexSlice['b':'y':-1], ''), + (pd.IndexSlice['b'::-1], 'b'), (pd.IndexSlice[:'b':-1], 'yxdcb'), + (pd.IndexSlice[:'y':-1], 'y'), (pd.IndexSlice['y'::-1], 'yxdcb'), + (pd.IndexSlice['y'::-4], 'yb'), + # absent labels + (pd.IndexSlice[:'a':-1], 'yxdcb'), (pd.IndexSlice[:'a':-2], 'ydb'), + (pd.IndexSlice['z'::-1], 'yxdcb'), (pd.IndexSlice['z'::-3], 'yc'), + (pd.IndexSlice['m'::-1], 'dcb'), (pd.IndexSlice[:'m':-1], 'yx'), + (pd.IndexSlice['a':'a':-1], ''), (pd.IndexSlice['z':'z':-1], ''), + (pd.IndexSlice['m':'m':-1], '') + ]) + def test_slice_locs_negative_step(self, in_slice, expected): + index = Index(list('bcdxy')) - def check_slice(in_slice, expected): - s_start, s_stop = idx.slice_locs(in_slice.start, in_slice.stop, - in_slice.step) - result = idx[s_start:s_stop:in_slice.step] - expected = pd.Index(list(expected)) - tm.assert_index_equal(result, expected) + s_start, s_stop = index.slice_locs(in_slice.start, in_slice.stop, + in_slice.step) + result = index[s_start:s_stop:in_slice.step] + expected = pd.Index(list(expected)) + tm.assert_index_equal(result, expected) - for in_slice, expected in [ - (SLC[::-1], 'yxdcb'), (SLC['b':'y':-1], ''), - (SLC['b'::-1], 'b'), (SLC[:'b':-1], 'yxdcb'), - (SLC[:'y':-1], 'y'), (SLC['y'::-1], 'yxdcb'), - (SLC['y'::-4], 'yb'), - # absent labels - (SLC[:'a':-1], 'yxdcb'), (SLC[:'a':-2], 'ydb'), - (SLC['z'::-1], 'yxdcb'), (SLC['z'::-3], 'yc'), - (SLC['m'::-1], 'dcb'), (SLC[:'m':-1], 'yx'), - (SLC['a':'a':-1], ''), (SLC['z':'z':-1], ''), - (SLC['m':'m':-1], '') - ]: - check_slice(in_slice, expected) - - def test_drop(self): + def test_drop_by_str_label(self): + # TODO: Parametrize these after replacing self.strIndex with fixture n = len(self.strIndex) - drop = self.strIndex[lrange(5, 10)] dropped = self.strIndex.drop(drop) + expected = self.strIndex[lrange(5) + lrange(10, n)] tm.assert_index_equal(dropped, expected) - pytest.raises(KeyError, self.strIndex.drop, ['foo', 'bar']) - pytest.raises(KeyError, self.strIndex.drop, ['1', 'bar']) + dropped = self.strIndex.drop(self.strIndex[0]) + expected = self.strIndex[1:] + tm.assert_index_equal(dropped, expected) + + @pytest.mark.parametrize("keys", [['foo', 'bar'], ['1', 'bar']]) + def test_drop_by_str_label_raises_missing_keys(self, keys): + with tm.assert_raises_regex(KeyError, ''): + self.strIndex.drop(keys) + + def test_drop_by_str_label_errors_ignore(self): + # TODO: Parametrize these after replacing self.strIndex with fixture # errors='ignore' + n = len(self.strIndex) + drop = self.strIndex[lrange(5, 10)] mixed = drop.tolist() + ['foo'] dropped = self.strIndex.drop(mixed, errors='ignore') + expected = self.strIndex[lrange(5) + lrange(10, n)] tm.assert_index_equal(dropped, expected) @@ -1436,24 +1490,25 @@ def test_drop(self): expected = self.strIndex[lrange(n)] tm.assert_index_equal(dropped, expected) - dropped = self.strIndex.drop(self.strIndex[0]) - expected = self.strIndex[1:] - tm.assert_index_equal(dropped, expected) - - ser = Index([1, 2, 3]) - dropped = ser.drop(1) + def test_drop_by_numeric_label_loc(self): + # TODO: Parametrize numeric and str tests after self.strIndex fixture + index = Index([1, 2, 3]) + dropped = index.drop(1) expected = Index([2, 3]) + tm.assert_index_equal(dropped, expected) - # errors='ignore' - pytest.raises(KeyError, ser.drop, [3, 4]) + def test_drop_by_numeric_label_raises_missing_keys(self): + index = Index([1, 2, 3]) + with tm.assert_raises_regex(KeyError, ''): + index.drop([3, 4]) - dropped = ser.drop(4, errors='ignore') - expected = Index([1, 2, 3]) - tm.assert_index_equal(dropped, expected) + @pytest.mark.parametrize("key,expected", [ + (4, Index([1, 2, 3])), ([3, 4, 5], Index([1, 2]))]) + def test_drop_by_numeric_label_errors_ignore(self, key, expected): + index = Index([1, 2, 3]) + dropped = index.drop(key, errors='ignore') - dropped = ser.drop([3, 4, 5], errors='ignore') - expected = Index([1, 2]) tm.assert_index_equal(dropped, expected) @pytest.mark.parametrize("values", [['a', 'b', ('c', 'd')], @@ -1477,40 +1532,35 @@ def test_drop_tuple(self, values, to_drop): for drop_me in to_drop[1], [to_drop[1]]: pytest.raises(KeyError, removed.drop, drop_me) - def test_tuple_union_bug(self): - import pandas - import numpy as np - - aidx1 = np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B')], - dtype=[('num', int), ('let', 'a1')]) - aidx2 = np.array([(1, 'A'), (2, 'A'), (1, 'B'), - (2, 'B'), (1, 'C'), (2, 'C')], - dtype=[('num', int), ('let', 'a1')]) - - idx1 = pandas.Index(aidx1) - idx2 = pandas.Index(aidx2) - - # intersection broken? - int_idx = idx1.intersection(idx2) - # needs to be 1d like idx1 and idx2 - expected = idx1[:4] # pandas.Index(sorted(set(idx1) & set(idx2))) - assert int_idx.ndim == 1 - tm.assert_index_equal(int_idx, expected) - - # union broken - union_idx = idx1.union(idx2) - expected = idx2 - assert union_idx.ndim == 1 - tm.assert_index_equal(union_idx, expected) - - def test_is_monotonic_incomparable(self): + @pytest.mark.parametrize("method,expected", [ + ('intersection', np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B')], + dtype=[('num', int), ('let', 'a1')])), + ('union', np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B'), (1, 'C'), + (2, 'C')], dtype=[('num', int), ('let', 'a1')])) + ]) + def test_tuple_union_bug(self, method, expected): + index1 = Index(np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B')], + dtype=[('num', int), ('let', 'a1')])) + index2 = Index(np.array([(1, 'A'), (2, 'A'), (1, 'B'), + (2, 'B'), (1, 'C'), (2, 'C')], + dtype=[('num', int), ('let', 'a1')])) + + result = getattr(index1, method)(index2) + assert result.ndim == 1 + + expected = Index(expected) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("attr", [ + 'is_monotonic_increasing', 'is_monotonic_decreasing', + '_is_strictly_monotonic_increasing', + '_is_strictly_monotonic_decreasing']) + def test_is_monotonic_incomparable(self, attr): index = Index([5, datetime.now(), 7]) - assert not index.is_monotonic_increasing - assert not index.is_monotonic_decreasing - assert not index._is_strictly_monotonic_increasing - assert not index._is_strictly_monotonic_decreasing + assert not getattr(index, attr) def test_get_set_value(self): + # TODO: Remove function? GH 19728 values = np.random.randn(100) date = self.dateIndex[67] @@ -1519,110 +1569,112 @@ def test_get_set_value(self): self.dateIndex.set_value(values, date, 10) assert values[67] == 10 - def test_isin(self): - values = ['foo', 'bar', 'quux'] - - idx = Index(['qux', 'baz', 'foo', 'bar']) - result = idx.isin(values) - expected = np.array([False, False, True, True]) + @pytest.mark.parametrize("values", [ + ['foo', 'bar', 'quux'], {'foo', 'bar', 'quux'}]) + @pytest.mark.parametrize("index,expected", [ + (Index(['qux', 'baz', 'foo', 'bar']), + np.array([False, False, True, True])), + (Index([]), np.array([], dtype=bool)) # empty + ]) + def test_isin(self, values, index, expected): + result = index.isin(values) tm.assert_numpy_array_equal(result, expected) - # set - result = idx.isin(set(values)) - tm.assert_numpy_array_equal(result, expected) + def test_isin_nan_common_object(self, 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) - # empty, return dtype bool - idx = Index([]) - result = idx.isin(values) - assert len(result) == 0 - assert result.dtype == np.bool_ - - @pytest.mark.skipif(PYPY, reason="np.nan is float('nan') on PyPy") - def test_isin_nan_not_pypy(self): - tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([float('nan')]), - np.array([False, False])) - - @pytest.mark.skipif(not PYPY, reason="np.nan is float('nan') on PyPy") - def test_isin_nan_pypy(self): - tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([float('nan')]), - np.array([False, True])) - - def test_isin_nan_common(self): - tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([np.nan]), - np.array([False, True])) - tm.assert_numpy_array_equal(Index(['a', pd.NaT]).isin([pd.NaT]), - np.array([False, True])) - tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([pd.NaT]), - np.array([False, False])) + if PYPY and nulls_fixture is np.nan: # np.nan is float('nan') on PyPy + tm.assert_numpy_array_equal(Index(['a', nulls_fixture]).isin( + [float('nan')]), np.array([False, True])) - # Float64Index overrides isin, so must be checked separately - tm.assert_numpy_array_equal(Float64Index([1.0, np.nan]).isin([np.nan]), - np.array([False, True])) - tm.assert_numpy_array_equal( - Float64Index([1.0, np.nan]).isin([float('nan')]), - np.array([False, True])) + elif nulls_fixture is nulls_fixture2: # should preserve NA type + tm.assert_numpy_array_equal(Index(['a', nulls_fixture]).isin( + [nulls_fixture2]), np.array([False, True])) - # we cannot compare NaT with NaN - tm.assert_numpy_array_equal(Float64Index([1.0, np.nan]).isin([pd.NaT]), - np.array([False, False])) + else: + tm.assert_numpy_array_equal(Index(['a', nulls_fixture]).isin( + [nulls_fixture2]), np.array([False, False])) - def test_isin_level_kwarg(self): - def check_idx(idx): - values = idx.tolist()[-2:] + ['nonexisting'] + def test_isin_nan_common_float64(self, nulls_fixture): + if nulls_fixture is pd.NaT: + pytest.skip("pd.NaT not compatible with Float64Index") - expected = np.array([False, False, True, True]) - tm.assert_numpy_array_equal(expected, idx.isin(values, level=0)) - tm.assert_numpy_array_equal(expected, idx.isin(values, level=-1)) + # Float64Index overrides isin, so must be checked separately + tm.assert_numpy_array_equal(Float64Index([1.0, nulls_fixture]).isin( + [np.nan]), np.array([False, True])) - pytest.raises(IndexError, idx.isin, values, level=1) - pytest.raises(IndexError, idx.isin, values, level=10) - pytest.raises(IndexError, idx.isin, values, level=-2) + # we cannot compare NaT with NaN + tm.assert_numpy_array_equal(Float64Index([1.0, nulls_fixture]).isin( + [pd.NaT]), np.array([False, False])) - pytest.raises(KeyError, idx.isin, values, level=1.0) - pytest.raises(KeyError, idx.isin, values, level='foobar') + @pytest.mark.parametrize("level", [0, -1]) + @pytest.mark.parametrize("index", [ + Index(['qux', 'baz', 'foo', 'bar']), + # Float64Index overrides isin, so must be checked separately + Float64Index([1.0, 2.0, 3.0, 4.0])]) + def test_isin_level_kwarg(self, level, index): + values = index.tolist()[-2:] + ['nonexisting'] - idx.name = 'foobar' - tm.assert_numpy_array_equal(expected, - idx.isin(values, level='foobar')) + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(expected, index.isin(values, level=level)) - pytest.raises(KeyError, idx.isin, values, level='xyzzy') - pytest.raises(KeyError, idx.isin, values, level=np.nan) + index.name = 'foobar' + tm.assert_numpy_array_equal(expected, + index.isin(values, level='foobar')) - check_idx(Index(['qux', 'baz', 'foo', 'bar'])) + @pytest.mark.parametrize("level", [1, 10, -2]) + @pytest.mark.parametrize("index", [ + Index(['qux', 'baz', 'foo', 'bar']), # Float64Index overrides isin, so must be checked separately - check_idx(Float64Index([1.0, 2.0, 3.0, 4.0])) + Float64Index([1.0, 2.0, 3.0, 4.0])]) + def test_isin_level_kwarg_raises_bad_index(self, level, index): + with tm.assert_raises_regex(IndexError, 'Too many levels'): + index.isin([], level=level) + + @pytest.mark.parametrize("level", [1.0, 'foobar', 'xyzzy', np.nan]) + @pytest.mark.parametrize("index", [ + Index(['qux', 'baz', 'foo', 'bar']), + Float64Index([1.0, 2.0, 3.0, 4.0])]) + def test_isin_level_kwarg_raises_key(self, level, index): + with tm.assert_raises_regex(KeyError, 'must be same as name'): + index.isin([], level=level) @pytest.mark.parametrize("empty", [[], Series(), np.array([])]) def test_isin_empty(self, empty): # see gh-16991 - idx = Index(["a", "b"]) + index = Index(["a", "b"]) expected = np.array([False, False]) - result = idx.isin(empty) + result = index.isin(empty) tm.assert_numpy_array_equal(expected, result) - def test_boolean_cmp(self): - values = [1, 2, 3, 4] - - idx = Index(values) - res = (idx == values) + @pytest.mark.parametrize("values", [ + [1, 2, 3, 4], + [1., 2., 3., 4.], + [True, True, True, True], + ["foo", "bar", "baz", "qux"], + pd.date_range('2018-01-01', freq='D', periods=4)]) + def test_boolean_cmp(self, values): + index = Index(values) + result = (index == values) + expected = np.array([True, True, True, True], dtype=bool) - tm.assert_numpy_array_equal(res, np.array( - [True, True, True, True], dtype=bool)) + tm.assert_numpy_array_equal(result, expected) - def test_get_level_values(self): - result = self.strIndex.get_level_values(0) - tm.assert_index_equal(result, self.strIndex) + @pytest.mark.parametrize("name,level", [ + (None, 0), ('a', 'a')]) + def test_get_level_values(self, name, level): + expected = self.strIndex.copy() + if name: + expected.name = name - # test for name (GH 17414) - index_with_name = self.strIndex.copy() - index_with_name.name = 'a' - result = index_with_name.get_level_values('a') - tm.assert_index_equal(result, index_with_name) + result = expected.get_level_values(level) + tm.assert_index_equal(result, expected) def test_slice_keep_name(self): - idx = Index(['a', 'b'], name='asdf') - assert idx.name == idx[1:].name + index = Index(['a', 'b'], name='asdf') + assert index.name == index[1:].name # instance attributes of the form self.<name>Index @pytest.mark.parametrize('index_kind', @@ -1634,159 +1686,158 @@ def test_join_self(self, join_type, index_kind): joined = res.join(res, how=join_type) assert res is joined - def test_str_attribute(self): + @pytest.mark.parametrize("method", ['strip', 'rstrip', 'lstrip']) + def test_str_attribute(self, method): # GH9068 - methods = ['strip', 'rstrip', 'lstrip'] - idx = Index([' jack', 'jill ', ' jesse ', 'frank']) - for method in methods: - expected = Index([getattr(str, method)(x) for x in idx.values]) - tm.assert_index_equal( - getattr(Index.str, method)(idx.str), expected) - - # create a few instances that are not able to use .str accessor - indices = [Index(range(5)), tm.makeDateIndex(10), - MultiIndex.from_tuples([('foo', '1'), ('bar', '3')]), - PeriodIndex(start='2000', end='2010', freq='A')] - for idx in indices: - with tm.assert_raises_regex(AttributeError, - 'only use .str accessor'): - idx.str.repeat(2) - - idx = Index(['a b c', 'd e', 'f']) - expected = Index([['a', 'b', 'c'], ['d', 'e'], ['f']]) - tm.assert_index_equal(idx.str.split(), expected) - tm.assert_index_equal(idx.str.split(expand=False), expected) - - expected = MultiIndex.from_tuples([('a', 'b', 'c'), ('d', 'e', np.nan), - ('f', np.nan, np.nan)]) - tm.assert_index_equal(idx.str.split(expand=True), expected) + index = Index([' jack', 'jill ', ' jesse ', 'frank']) + expected = Index([getattr(str, method)(x) for x in index.values]) + + result = getattr(index.str, method)() + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("index", [ + Index(range(5)), tm.makeDateIndex(10), + MultiIndex.from_tuples([('foo', '1'), ('bar', '3')]), + PeriodIndex(start='2000', end='2010', freq='A')]) + def test_str_attribute_raises(self, index): + with tm.assert_raises_regex(AttributeError, 'only use .str accessor'): + index.str.repeat(2) + + @pytest.mark.parametrize("expand,expected", [ + (None, Index([['a', 'b', 'c'], ['d', 'e'], ['f']])), + (False, Index([['a', 'b', 'c'], ['d', 'e'], ['f']])), + (True, MultiIndex.from_tuples([('a', 'b', 'c'), ('d', 'e', np.nan), + ('f', np.nan, np.nan)]))]) + def test_str_split(self, expand, expected): + index = Index(['a b c', 'd e', 'f']) + if expand is not None: + result = index.str.split(expand=expand) + else: + result = index.str.split() + + tm.assert_index_equal(result, expected) + def test_str_bool_return(self): # test boolean case, should return np.array instead of boolean Index - idx = Index(['a1', 'a2', 'b1', 'b2']) + index = Index(['a1', 'a2', 'b1', 'b2']) + result = index.str.startswith('a') expected = np.array([True, True, False, False]) - tm.assert_numpy_array_equal(idx.str.startswith('a'), expected) - assert isinstance(idx.str.startswith('a'), np.ndarray) - s = Series(range(4), index=idx) + + tm.assert_numpy_array_equal(result, expected) + assert isinstance(result, np.ndarray) + + def test_str_bool_series_indexing(self): + index = Index(['a1', 'a2', 'b1', 'b2']) + s = Series(range(4), index=index) + + result = s[s.index.str.startswith('a')] expected = Series(range(2), index=['a1', 'a2']) - tm.assert_series_equal(s[s.index.str.startswith('a')], expected) + tm.assert_series_equal(result, expected) - def test_tab_completion(self): + @pytest.mark.parametrize("index,expected", [ + (Index(list('abcd')), True), (Index(range(4)), False)]) + def test_tab_completion(self, index, expected): # GH 9910 - idx = Index(list('abcd')) - assert 'str' in dir(idx) - - idx = Index(range(4)) - assert 'str' not in dir(idx) + result = 'str' in dir(index) + assert result == expected def test_indexing_doesnt_change_class(self): - idx = Index([1, 2, 3, 'a', 'b', 'c']) + index = Index([1, 2, 3, 'a', 'b', 'c']) - assert idx[1:3].identical(pd.Index([2, 3], dtype=np.object_)) - assert idx[[0, 1]].identical(pd.Index([1, 2], dtype=np.object_)) + assert index[1:3].identical(pd.Index([2, 3], dtype=np.object_)) + assert index[[0, 1]].identical(pd.Index([1, 2], dtype=np.object_)) def test_outer_join_sort(self): left_idx = Index(np.random.permutation(15)) right_idx = tm.makeDateIndex(10) with tm.assert_produces_warning(RuntimeWarning): - joined = left_idx.join(right_idx, how='outer') + result = left_idx.join(right_idx, how='outer') # right_idx in this case because DatetimeIndex has join precedence over # Int64Index with tm.assert_produces_warning(RuntimeWarning): expected = right_idx.astype(object).union(left_idx.astype(object)) - tm.assert_index_equal(joined, expected) + tm.assert_index_equal(result, expected) def test_nan_first_take_datetime(self): - idx = Index([pd.NaT, Timestamp('20130101'), Timestamp('20130102')]) - res = idx.take([-1, 0, 1]) - exp = Index([idx[-1], idx[0], idx[1]]) - tm.assert_index_equal(res, exp) + index = Index([pd.NaT, Timestamp('20130101'), Timestamp('20130102')]) + result = index.take([-1, 0, 1]) + expected = Index([index[-1], index[0], index[1]]) + tm.assert_index_equal(result, expected) def test_take_fill_value(self): # GH 12631 - idx = pd.Index(list('ABC'), name='xxx') - result = idx.take(np.array([1, 0, -1])) + index = pd.Index(list('ABC'), name='xxx') + result = index.take(np.array([1, 0, -1])) expected = pd.Index(list('BAC'), name='xxx') tm.assert_index_equal(result, expected) # fill_value - result = idx.take(np.array([1, 0, -1]), fill_value=True) + result = index.take(np.array([1, 0, -1]), fill_value=True) expected = pd.Index(['B', 'A', np.nan], name='xxx') tm.assert_index_equal(result, expected) # allow_fill=False - result = idx.take(np.array([1, 0, -1]), allow_fill=False, - fill_value=True) + result = index.take(np.array([1, 0, -1]), allow_fill=False, + fill_value=True) expected = pd.Index(['B', 'A', 'C'], name='xxx') tm.assert_index_equal(result, expected) + def test_take_fill_value_none_raises(self): + index = pd.Index(list('ABC'), name='xxx') msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') + with tm.assert_raises_regex(ValueError, msg): - idx.take(np.array([1, 0, -2]), fill_value=True) + index.take(np.array([1, 0, -2]), fill_value=True) with tm.assert_raises_regex(ValueError, msg): - idx.take(np.array([1, 0, -5]), fill_value=True) - - with pytest.raises(IndexError): - idx.take(np.array([1, -5])) - - def test_reindex_preserves_name_if_target_is_list_or_ndarray(self): + index.take(np.array([1, 0, -5]), fill_value=True) + + def test_take_bad_bounds_raises(self): + index = pd.Index(list('ABC'), name='xxx') + with tm.assert_raises_regex(IndexError, 'out of bounds'): + index.take(np.array([1, -5])) + + @pytest.mark.parametrize("name", [None, 'foobar']) + @pytest.mark.parametrize("labels", [ + [], np.array([]), ['A', 'B', 'C'], ['C', 'B', 'A'], + np.array(['A', 'B', 'C']), np.array(['C', 'B', 'A']), + # Must preserve name even if dtype changes + pd.date_range('20130101', periods=3).values, + pd.date_range('20130101', periods=3).tolist()]) + def test_reindex_preserves_name_if_target_is_list_or_ndarray(self, name, + labels): # GH6552 - idx = pd.Index([0, 1, 2]) - - dt_idx = pd.date_range('20130101', periods=3) - - idx.name = None - assert idx.reindex([])[0].name is None - assert idx.reindex(np.array([]))[0].name is None - assert idx.reindex(idx.tolist())[0].name is None - assert idx.reindex(idx.tolist()[:-1])[0].name is None - assert idx.reindex(idx.values)[0].name is None - assert idx.reindex(idx.values[:-1])[0].name is None - - # Must preserve name even if dtype changes. - assert idx.reindex(dt_idx.values)[0].name is None - assert idx.reindex(dt_idx.tolist())[0].name is None - - idx.name = 'foobar' - assert idx.reindex([])[0].name == 'foobar' - assert idx.reindex(np.array([]))[0].name == 'foobar' - assert idx.reindex(idx.tolist())[0].name == 'foobar' - assert idx.reindex(idx.tolist()[:-1])[0].name == 'foobar' - assert idx.reindex(idx.values)[0].name == 'foobar' - assert idx.reindex(idx.values[:-1])[0].name == 'foobar' - - # Must preserve name even if dtype changes. - assert idx.reindex(dt_idx.values)[0].name == 'foobar' - assert idx.reindex(dt_idx.tolist())[0].name == 'foobar' - - def test_reindex_preserves_type_if_target_is_empty_list_or_array(self): + index = pd.Index([0, 1, 2]) + index.name = name + assert index.reindex(labels)[0].name == name + + @pytest.mark.parametrize("labels", [ + [], np.array([]), np.array([], dtype=np.int64)]) + def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, + labels): # GH7774 - idx = pd.Index(list('abc')) - - def get_reindex_type(target): - return idx.reindex(target)[0].dtype.type - - assert get_reindex_type([]) == np.object_ - assert get_reindex_type(np.array([])) == np.object_ - assert get_reindex_type(np.array([], dtype=np.int64)) == np.object_ - - def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self): + index = pd.Index(list('abc')) + assert index.reindex(labels)[0].dtype.type == np.object_ + + @pytest.mark.parametrize("labels,dtype", [ + (pd.Int64Index([]), np.int64), + (pd.Float64Index([]), np.float64), + (pd.DatetimeIndex([]), np.datetime64)]) + def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, + labels, + dtype): # GH7774 - idx = pd.Index(list('abc')) - - def get_reindex_type(target): - return idx.reindex(target)[0].dtype.type - - assert get_reindex_type(pd.Int64Index([])) == np.int64 - assert get_reindex_type(pd.Float64Index([])) == np.float64 - assert get_reindex_type(pd.DatetimeIndex([])) == np.datetime64 + index = pd.Index(list('abc')) + assert index.reindex(labels)[0].dtype.type == dtype - reindexed = idx.reindex(pd.MultiIndex( + def test_reindex_no_type_preserve_target_empty_mi(self): + index = pd.Index(list('abc')) + result = index.reindex(pd.MultiIndex( [pd.Int64Index([]), pd.Float64Index([])], [[], []]))[0] - assert reindexed.levels[0].dtype.type == np.int64 - assert reindexed.levels[1].dtype.type == np.float64 + assert result.levels[0].dtype.type == np.int64 + assert result.levels[1].dtype.type == np.float64 def test_groupby(self): idx = Index(range(5))
progress towards #20812
https://api.github.com/repos/pandas-dev/pandas/pulls/20931
2018-05-02T18:09:29Z
2018-05-03T10:38:38Z
2018-05-03T10:38:38Z
2018-05-03T22:18:19Z
CLN: Fix typo in deprecation warning - "strudes" --> "strides"
diff --git a/pandas/core/base.py b/pandas/core/base.py index 2f25a9ce41369..5022beabef76b 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -758,7 +758,7 @@ def nbytes(self): @property def strides(self): """ return the strides of the underlying data """ - warnings.warn("{obj}.strudes is deprecated and will be removed " + warnings.warn("{obj}.strides is deprecated and will be removed " "in a future version".format(obj=type(self).__name__), FutureWarning, stacklevel=2) return self._ndarray_values.strides
xref #20721 Minor typo, but might be nice to fix prior to the official 0.23.0 release.
https://api.github.com/repos/pandas-dev/pandas/pulls/20929
2018-05-02T17:40:50Z
2018-05-03T00:33:29Z
2018-05-03T00:33:29Z
2018-05-03T01:43:33Z
Added script to fetch wheels [ci skip]
diff --git a/scripts/download_wheels.py b/scripts/download_wheels.py new file mode 100644 index 0000000000000..a4705d0e4e63c --- /dev/null +++ b/scripts/download_wheels.py @@ -0,0 +1,44 @@ +"""Fetch wheels from wheels.scipy.org for a pandas version.""" +import argparse +import pathlib +import sys +import urllib.parse +import urllib.request + +from lxml import html + + +def parse_args(args=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("version", type=str, help="Pandas version (0.23.0)") + return parser.parse_args(args) + + +def fetch(version): + base = 'http://wheels.scipy.org' + tree = html.parse(base) + root = tree.getroot() + + dest = pathlib.Path('dist') + dest.mkdir(exist_ok=True) + + files = [x for x in root.xpath("//a/text()") + if x.startswith(f'pandas-{version}') + and not dest.joinpath(x).exists()] + + N = len(files) + + for i, filename in enumerate(files, 1): + out = str(dest.joinpath(filename)) + link = urllib.request.urljoin(base, filename) + urllib.request.urlretrieve(link, out) + print(f"Downloaded {link} to {out} [{i}/{N}]") + + +def main(args=None): + args = parse_args(args) + fetch(args.version) + + +if __name__ == '__main__': + sys.exit(main())
[ci skip]
https://api.github.com/repos/pandas-dev/pandas/pulls/20928
2018-05-02T16:27:05Z
2018-05-14T23:40:03Z
2018-05-14T23:40:03Z
2018-05-15T01:18:19Z
BLD: Use relative path in setup.py for pxd includes
diff --git a/setup.py b/setup.py index 973b4c0abcde2..a436f451a2a55 100755 --- a/setup.py +++ b/setup.py @@ -450,7 +450,7 @@ def srcpath(name=None, suffix='.pyx', subdir='src'): def pxd(name): - return os.path.abspath(pjoin('pandas', name + '.pxd')) + return pjoin('pandas', name + '.pxd') # args to ignore warnings
This caused failures on the conda-forge build xref https://github.com/conda-forge/pandas-feedstock/pull/41
https://api.github.com/repos/pandas-dev/pandas/pulls/20924
2018-05-02T13:52:29Z
2018-05-02T14:46:02Z
2018-05-02T14:46:02Z
2018-05-02T14:46:09Z
Follow-up #20347: incorporate review about _get_series_list
diff --git a/doc/source/text.rst b/doc/source/text.rst index 02fa2d882f8b1..4af64d9f791cc 100644 --- a/doc/source/text.rst +++ b/doc/source/text.rst @@ -311,7 +311,7 @@ All one-dimensional list-likes can be arbitrarily combined in a list-like contai s u - s.str.cat([u, pd.Index(u.values), ['A', 'B', 'C', 'D'], map(int, u.index)], na_rep='-') + s.str.cat([u, pd.Index(u.values), ['A', 'B', 'C', 'D'], map(str, u.index)], na_rep='-') All elements must match in length to the calling ``Series`` (or ``Index``), except those having an index if ``join`` is not None: diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index d3746d9e0b61e..0fda57b74892b 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -314,7 +314,7 @@ The :func:`DataFrame.assign` now accepts dependent keyword arguments for python ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Previously, :meth:`Series.str.cat` did not -- in contrast to most of ``pandas`` -- align :class:`Series` on their index before concatenation (see :issue:`18657`). -The method has now gained a keyword ``join`` to control the manner of alignment, see examples below and in :ref:`here <text.concatenate>`. +The method has now gained a keyword ``join`` to control the manner of alignment, see examples below and :ref:`here <text.concatenate>`. In v.0.23 `join` will default to None (meaning no alignment), but this default will change to ``'left'`` in a future version of pandas. @@ -325,7 +325,7 @@ In v.0.23 `join` will default to None (meaning no alignment), but this default w s.str.cat(t) s.str.cat(t, join='left', na_rep='-') -Furthermore, meth:`Series.str.cat` now works for ``CategoricalIndex`` as well (previously raised a ``ValueError``; see :issue:`20842`). +Furthermore, :meth:`Series.str.cat` now works for ``CategoricalIndex`` as well (previously raised a ``ValueError``; see :issue:`20842`). .. _whatsnew_0230.enhancements.astype_category: diff --git a/pandas/core/strings.py b/pandas/core/strings.py index da4845fcdfc8e..1f6711e13fd3e 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1943,21 +1943,21 @@ def _get_series_list(self, others, ignore_index=False): Parameters ---------- - input : Series, DataFrame, np.ndarray, list-like or list-like of + others : Series, DataFrame, np.ndarray, list-like or list-like of objects that are either Series, np.ndarray (1-dim) or list-like ignore_index : boolean, default False - Determines whether to forcefully align with index of the caller + Determines whether to forcefully align others with index of caller Returns ------- - tuple : (input transformed into list of Series, - Boolean whether FutureWarning should be raised) + tuple : (others transformed into list of Series, + boolean whether FutureWarning should be raised) """ # once str.cat defaults to alignment, this function can be simplified; # will not need `ignore_index` and the second boolean output anymore - from pandas import Index, Series, DataFrame, isnull + from pandas import Index, Series, DataFrame # self._orig is either Series or Index idx = self._orig if isinstance(self._orig, Index) else self._orig.index @@ -1966,66 +1966,69 @@ def _get_series_list(self, others, ignore_index=False): 'list-like (either containing only strings or containing ' 'only objects of type Series/Index/list-like/np.ndarray)') + # Generally speaking, all objects without an index inherit the index + # `idx` of the calling Series/Index - i.e. must have matching length. + # Objects with an index (i.e. Series/Index/DataFrame) keep their own + # index, *unless* ignore_index is set to True. if isinstance(others, Series): - fu_wrn = not others.index.equals(idx) + warn = not others.index.equals(idx) + # only reconstruct Series when absolutely necessary los = [Series(others.values, index=idx) - if ignore_index and fu_wrn else others] - return (los, fu_wrn) + if ignore_index and warn else others] + return (los, warn) elif isinstance(others, Index): - fu_wrn = not others.equals(idx) + warn = not others.equals(idx) los = [Series(others.values, index=(idx if ignore_index else others))] - return (los, fu_wrn) + return (los, warn) elif isinstance(others, DataFrame): - fu_wrn = not others.index.equals(idx) - if ignore_index and fu_wrn: + warn = not others.index.equals(idx) + if ignore_index and warn: # without copy, this could change "others" # that was passed to str.cat others = others.copy() others.index = idx - return ([others[x] for x in others], fu_wrn) + return ([others[x] for x in others], warn) elif isinstance(others, np.ndarray) and others.ndim == 2: others = DataFrame(others, index=idx) return ([others[x] for x in others], False) elif is_list_like(others): others = list(others) # ensure iterators do not get read twice etc + + # in case of list-like `others`, all elements must be + # either one-dimensional list-likes or scalars if all(is_list_like(x) for x in others): los = [] - fu_wrn = False + warn = False + # iterate through list and append list of series for each + # element (which we check to be one-dimensional and non-nested) while others: - nxt = others.pop(0) # list-like as per check above - # safety for iterators and other non-persistent list-likes - # do not map indexed/typed objects; would lose information + nxt = others.pop(0) # nxt is guaranteed list-like by above if not isinstance(nxt, (DataFrame, Series, Index, np.ndarray)): + # safety for non-persistent list-likes (e.g. iterators) + # do not map indexed/typed objects; info needed below nxt = list(nxt) - # known types without deep inspection + # known types for which we can avoid deep inspection no_deep = ((isinstance(nxt, np.ndarray) and nxt.ndim == 1) or isinstance(nxt, (Series, Index))) - # Nested list-likes are forbidden - elements of nxt must be - # strings/NaN/None. Need to robustify NaN-check against - # x in nxt being list-like (otherwise ambiguous boolean) + # nested list-likes are forbidden: + # -> elements of nxt must not be list-like is_legal = ((no_deep and nxt.dtype == object) - or all((isinstance(x, compat.string_types) - or (not is_list_like(x) and isnull(x)) - or x is None) - for x in nxt)) + or all(not is_list_like(x) for x in nxt)) + # DataFrame is false positive of is_legal # because "x in df" returns column names if not is_legal or isinstance(nxt, DataFrame): raise TypeError(err_msg) - nxt, fwn = self._get_series_list(nxt, + nxt, wnx = self._get_series_list(nxt, ignore_index=ignore_index) los = los + nxt - fu_wrn = fu_wrn or fwn - return (los, fu_wrn) - # test if there is a mix of list-like and non-list-like (e.g. str) - elif (any(is_list_like(x) for x in others) - and any(not is_list_like(x) for x in others)): - raise TypeError(err_msg) - else: # all elements in others are _not_ list-like + warn = warn or wnx + return (los, warn) + elif all(not is_list_like(x) for x in others): return ([Series(others, index=idx)], False) raise TypeError(err_msg) @@ -2187,8 +2190,8 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): try: # turn anything in "others" into lists of Series - others, fu_wrn = self._get_series_list(others, - ignore_index=(join is None)) + others, warn = self._get_series_list(others, + ignore_index=(join is None)) except ValueError: # do not catch TypeError raised by _get_series_list if join is None: raise ValueError('All arrays must be same length, except ' @@ -2199,7 +2202,7 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): 'must all be of the same length as the ' 'calling Series/Index.') - if join is None and fu_wrn: + if join is None and warn: warnings.warn("A future version of pandas will perform index " "alignment when `others` is a Series/Index/" "DataFrame (or a list-like containing one). To "
Closes #20922 recap of #20347 : Enabling alignment on top of the (v.0.22-)legal list of lists was relatively complex. The allowed argument types implemented in #20347 are as follows: ``` Type of (element of) "others" | alone | within list-like --------------------------------------------------------------------- pd.Series | yes | yes pd.Index | yes | yes np.ndarray (1-dim) | yes | yes DataFrame | yes | no np.ndarray (2-dim) | yes | no iterators, dict-views, etc. | yes | ** anything else w/ is_list_like = True | yes | ** ``` ** to be permitted, list-likes (say `nxt`) within a list-like `others` must pass (essentially) ```all(not is_list_like(x) for x in nxt)``` and not be a DF. Open review points from #20347 from @jreback (and my responses) reproduced in review comments. PS. Managed to have a brainfart and there's a bug in the RC docs - very sorry. Fixed in this PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/20923
2018-05-02T12:28:24Z
2018-05-04T10:11:14Z
2018-05-04T10:11:13Z
2018-05-04T11:00:25Z
DOC: update the Series.str.ismethods docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index c6d45ce5413ac..4af5b0ee5dd98 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- import numpy as np from pandas.compat import zip @@ -2400,12 +2401,144 @@ def rindex(self, sub, start=0, end=None): _shared_docs['swapcase']) _shared_docs['ismethods'] = (""" - Check whether all characters in each string in the Series/Index - are %(type)s. Equivalent to :meth:`str.%(method)s`. + Check whether all characters in each string are %(type)s. + + This is equivalent to running the Python string method + :meth:`str.%(method)s` for each element of the Series/Index. If a string + has zero characters, ``False`` is returned for that check. Returns ------- - is : Series/array of boolean values + Series or Index of bool + Series or Index of boolean values with the same length as the original + Series/Index. + + See Also + -------- + Series.str.isalpha : Check whether all characters are alphabetic. + Series.str.isnumeric : Check whether all characters are numeric. + Series.str.isalnum : Check whether all characters are alphanumeric. + Series.str.isdigit : Check whether all characters are digits. + Series.str.isdecimal : Check whether all characters are decimal. + Series.str.isspace : Check whether all characters are whitespace. + Series.str.islower : Check whether all characters are lowercase. + Series.str.isupper : Check whether all characters are uppercase. + Series.str.istitle : Check whether all characters are titlecase. + + Examples + -------- + **Checks for Alphabetic and Numeric Characters** + + >>> s1 = pd.Series(['one', 'one1', '1', '']) + + >>> s1.str.isalpha() + 0 True + 1 False + 2 False + 3 False + dtype: bool + + >>> s1.str.isnumeric() + 0 False + 1 False + 2 True + 3 False + dtype: bool + + >>> s1.str.isalnum() + 0 True + 1 True + 2 True + 3 False + dtype: bool + + Note that checks against characters mixed with any additional punctuation + or whitespace will evaluate to false for an alphanumeric check. + + >>> s2 = pd.Series(['A B', '1.5', '3,000']) + >>> s2.str.isalnum() + 0 False + 1 False + 2 False + dtype: bool + + **More Detailed Checks for Numeric Characters** + + There are several different but overlapping sets of numeric characters that + can be checked for. + + >>> s3 = pd.Series(['23', '³', '⅕', '']) + + The ``s3.str.isdecimal`` method checks for characters used to form numbers + in base 10. + + >>> s3.str.isdecimal() + 0 True + 1 False + 2 False + 3 False + dtype: bool + + The ``s.str.isdigit`` method is the same as ``s3.str.isdecimal`` but also + includes special digits, like superscripted and subscripted digits in + unicode. + + >>> s3.str.isdigit() + 0 True + 1 True + 2 False + 3 False + dtype: bool + + The ``s.str.isnumeric`` method is the same as ``s3.str.isdigit`` but also + includes other characters that can represent quantities such as unicode + fractions. + + >>> s3.str.isnumeric() + 0 True + 1 True + 2 True + 3 False + dtype: bool + + **Checks for Whitespace** + + >>> s4 = pd.Series([' ', '\\t\\r\\n ', '']) + >>> s4.str.isspace() + 0 True + 1 True + 2 False + dtype: bool + + **Checks for Character Case** + + >>> s5 = pd.Series(['leopard', 'Golden Eagle', 'SNAKE', '']) + + >>> s5.str.islower() + 0 True + 1 False + 2 False + 3 False + dtype: bool + + >>> s5.str.isupper() + 0 False + 1 False + 2 True + 3 False + dtype: bool + + The ``s5.str.istitle`` method checks for whether all words are in title + case (whether only the first letter of each word is capitalized). Words are + assumed to be as any sequence of non-numeric characters seperated by + whitespace characters. + + >>> s5.str.istitle() + 0 False + 1 True + 2 False + 3 False + dtype: bool """) _shared_docs['isalnum'] = dict(type='alphanumeric', method='isalnum') _shared_docs['isalpha'] = dict(type='alphabetic', method='isalpha')
- [ ] closes #xxxx - [x] tests ~added~ / passed (using scripts/validate_docstrings.py) - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry A result of the Pandas Sprint at PyData London 2018.
https://api.github.com/repos/pandas-dev/pandas/pulls/20913
2018-05-01T22:34:50Z
2018-07-22T00:22:42Z
2018-07-22T00:22:42Z
2018-07-22T00:23:25Z
BUG: DatetimeIndex._data should return an ndarray
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 3d7c4762d21ca..78fa6f8217157 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -506,6 +506,10 @@ def _shallow_copy(self, values=None, **kwargs): attributes.update(kwargs) if not len(values) and 'dtype' not in kwargs: attributes['dtype'] = self.dtype + + # _simple_new expects an ndarray + values = getattr(values, 'values', values) + return self._simple_new(values, **attributes) def _shallow_copy_with_infer(self, values=None, **kwargs): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 96c30eeb92628..b8a89ac26c9d9 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -12,7 +12,6 @@ from pandas.core.dtypes.common import ( _INT64_DTYPE, _NS_DTYPE, - is_object_dtype, is_datetime64_dtype, is_datetimetz, is_dtype_equal, @@ -551,10 +550,11 @@ def _generate(cls, start, end, periods, name, freq, index = _generate_regular_range(start, end, periods, freq) if tz is not None and getattr(index, 'tz', None) is None: - index = conversion.tz_localize_to_utc(_ensure_int64(index), - tz, - ambiguous=ambiguous) - index = index.view(_NS_DTYPE) + arr = conversion.tz_localize_to_utc(_ensure_int64(index), + tz, + ambiguous=ambiguous) + + index = DatetimeIndex(arr) # index is localized datetime64 array -> have to convert # start/end as well to compare @@ -575,7 +575,9 @@ def _generate(cls, start, end, periods, name, freq, index = index[1:] if not right_closed and len(index) and index[-1] == end: index = index[:-1] - index = cls._simple_new(index, name=name, freq=freq, tz=tz) + + index = cls._simple_new(index.values, name=name, freq=freq, tz=tz) + return index def _convert_for_op(self, value): @@ -606,12 +608,14 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, dtype=dtype, **kwargs) values = np.array(values, copy=False) - if is_object_dtype(values): - return cls(values, name=name, freq=freq, tz=tz, - dtype=dtype, **kwargs).values - elif not is_datetime64_dtype(values): + if not is_datetime64_dtype(values): values = _ensure_int64(values).view(_NS_DTYPE) + values = getattr(values, 'values', values) + + assert isinstance(values, np.ndarray), "values is not an np.ndarray" + assert is_datetime64_dtype(values) + result = super(DatetimeIndex, cls)._simple_new(values, freq, tz, **kwargs) result.name = name @@ -1000,7 +1004,7 @@ def unique(self, level=None): else: naive = self result = super(DatetimeIndex, naive).unique(level=level) - return self._simple_new(result, name=self.name, tz=self.tz, + return self._simple_new(result.values, name=self.name, tz=self.tz, freq=self.freq) def union(self, other): @@ -1855,7 +1859,7 @@ def _generate_regular_range(start, end, periods, freq): "if a 'period' is given.") data = np.arange(b, e, stride, dtype=np.int64) - data = DatetimeIndex._simple_new(data, None, tz=tz) + data = DatetimeIndex._simple_new(data.view(_NS_DTYPE), None, tz=tz) else: if isinstance(start, Timestamp): start = start.to_pydatetime() diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 6b5714bcadba1..bb31e8927cba3 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2472,7 +2472,8 @@ def _get_index_factory(self, klass): if klass == DatetimeIndex: def f(values, freq=None, tz=None): # data are already in UTC, localize and convert if tz present - result = DatetimeIndex._simple_new(values, None, freq=freq) + result = DatetimeIndex._simple_new(values.values, None, + freq=freq) if tz is not None: result = result.tz_localize('UTC').tz_convert(tz) return result diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index daba56e0c1e29..639e51e9361ab 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -329,7 +329,7 @@ def test_index_ctor_infer_periodindex(self): ]) def test_constructor_simple_new(self, vals, dtype): index = Index(vals, name=dtype) - result = index._simple_new(index, dtype) + result = index._simple_new(index.values, dtype) tm.assert_index_equal(result, index) @pytest.mark.parametrize("vals", [
- [x] closes #20810 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The change I made seems to fix the case in the original issue without breaking any tests. On my branch: ``` In [1]: idx1 = pd.DatetimeIndex(start="2012-01-01", periods=3, freq='D') # date_range kind of construction In [2]: idx1._data array(['2012-01-01T00:00:00.000000000', '2012-01-02T00:00:00.000000000', '2012-01-03T00:00:00.000000000'], dtype='datetime64[ns]') In [3]: idx2 = pd.DatetimeIndex(idx1) In [4]: idx2._data Out[4]: array(['2012-01-01T00:00:00.000000000', '2012-01-02T00:00:00.000000000', '2012-01-03T00:00:00.000000000'], dtype='datetime64[ns]') ``` But is the solution too simple or is something more sophisticated required? And do we need tests for this issue?
https://api.github.com/repos/pandas-dev/pandas/pulls/20912
2018-05-01T22:23:35Z
2018-07-10T10:08:47Z
2018-07-10T10:08:46Z
2018-07-10T20:40:41Z
Doc: Added docstring to Groupby mean
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c019572f4324e..aa4c7452bcea9 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1297,9 +1297,48 @@ def count(self): @Appender(_doc_template) def mean(self, *args, **kwargs): """ - Compute mean of groups, excluding missing values + Compute mean of groups, excluding missing values. - For multiple groupings, the result index will be a MultiIndex + Returns + ------- + pandas.Series or pandas.DataFrame + + Examples + -------- + >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], + ... 'B': [np.nan, 2, 3, 4, 5], + ... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C']) + + Groupby one column and return the mean of the remaining columns in + each group. + + >>> df.groupby('A').mean() + >>> + B C + A + 1 3.0 1.333333 + 2 4.0 1.500000 + + Groupby two columns and return the mean of the remaining column. + + >>> df.groupby(['A', 'B']).mean() + >>> + C + A B + 1 2.0 2 + 4.0 1 + 2 3.0 1 + 5.0 2 + + Groupby one column and return the mean of only particular column in + the group. + + >>> df.groupby('A')['B'].mean() + >>> + A + 1 3.0 + 2 4.0 + Name: B, dtype: float64 """ nv.validate_groupby_func('mean', args, kwargs, ['numeric_only']) try:
Added examples of the usage and what is returned
https://api.github.com/repos/pandas-dev/pandas/pulls/20910
2018-05-01T20:11:59Z
2018-07-07T22:42:03Z
2018-07-07T22:42:03Z
2018-07-07T22:42:13Z
missing one https
diff --git a/README.md b/README.md index 5ff256158aa1b..cd2cb99992977 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ pip install pandas ``` ## Dependencies -- [NumPy](http://www.numpy.org): 1.9.0 or higher +- [NumPy](https://www.numpy.org): 1.9.0 or higher - [python-dateutil](https://labix.org/python-dateutil): 2.5.0 or higher - [pytz](https://pythonhosted.org/pytz): 2011k or higher
www.numpy.org supports https now.
https://api.github.com/repos/pandas-dev/pandas/pulls/20908
2018-05-01T16:58:44Z
2018-05-02T10:26:38Z
2018-05-02T10:26:38Z
2018-05-02T10:26:40Z
Use right assert raises
diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index a6a38e005b9b6..4ba181384b3b3 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -4877,15 +4877,17 @@ def test_to_hdf_with_object_column_names(self): if compat.PY3: types_should_run.append(tm.makeUnicodeIndex) else: - types_should_fail.append(tm.makeUnicodeIndex) + # TODO: Add back to types_should_fail + # https://github.com/pandas-dev/pandas/issues/20907 + pass for index in types_should_fail: df = DataFrame(np.random.randn(10, 2), columns=index(2)) with ensure_clean_path(self.path) as path: with catch_warnings(record=True): - with pytest.raises( - ValueError, msg=("cannot have non-object label " - "DataIndexableCol")): + with tm.assert_raises_regex( + ValueError, ("cannot have non-object label " + "DataIndexableCol")): df.to_hdf(path, 'df', format='table', data_columns=True)
Closes https://github.com/pandas-dev/pandas/issues/20904 closes #20904
https://api.github.com/repos/pandas-dev/pandas/pulls/20906
2018-05-01T15:19:50Z
2018-05-01T17:46:51Z
2018-05-01T17:46:50Z
2018-05-01T17:46:54Z
DOC: whatsnew for GH #18819
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 604b68b650201..6c8a89ed9a80c 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1225,6 +1225,7 @@ Reshaping - Bug in :func:`DataFrame.unstack` which raises an error if ``index`` is a ``MultiIndex`` with unused labels on the unstacked level (:issue:`18562`) - Fixed construction of a :class:`Series` from a ``dict`` containing ``NaN`` as key (:issue:`18480`) - Fixed construction of a :class:`DataFrame` from a ``dict`` containing ``NaN`` as key (:issue:`18455`) +- Disabled construction of a :class:`Series` where len(index) > len(data) = 1, which previously would broadcast the data item, and now raises a ``ValueError`` (:issue:`18819`) - Suppressed error in the construction of a :class:`DataFrame` from a ``dict`` containing scalar values when the corresponding keys are not included in the passed index (:issue:`18600`) - Fixed (changed from ``object`` to ``float64``) dtype of :class:`DataFrame` initialized with axes, no data, and ``dtype=int`` (:issue:`19646`)
- [x] closes #18819 - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Just a whatsnew entry warning about the more strict check
https://api.github.com/repos/pandas-dev/pandas/pulls/20901
2018-05-01T13:44:09Z
2018-05-01T14:04:10Z
2018-05-01T14:04:10Z
2018-05-01T14:16:34Z
Mention NaN handling in dtype description
diff --git a/doc/source/io.rst b/doc/source/io.rst index c5b7eff292722..aa2484b0cb5c3 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -168,7 +168,8 @@ General Parsing Configuration dtype : Type name or dict of column -> type, default ``None`` Data type for data or columns. E.g. ``{'a': np.float64, 'b': np.int32}`` - (unsupported with ``engine='python'``). Use `str` or `object` to preserve and + (unsupported with ``engine='python'``). Use `str` or `object` together + with suitable ``na_values`` settings to preserve and not interpret dtype. .. versionadded:: 0.20.0 support for the Python parser. diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 780aa5d02f598..2c8f98732c92f 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -125,7 +125,8 @@ are duplicate names in the columns. dtype : Type name or dict of column -> type, default None Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} - Use `str` or `object` to preserve and not interpret dtype. + Use `str` or `object` together with suitable `na_values` settings + to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. %s
To achieve preservation and avoid interpretation of string or object dtypes, NaN value interpretation must be switched off. - [x] closes issue #20875 - [ ] tests passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] `pandas.read_csv.html` renders text as intended
https://api.github.com/repos/pandas-dev/pandas/pulls/20895
2018-05-01T08:06:29Z
2018-05-14T19:16:15Z
2018-05-14T19:16:15Z
2018-05-15T08:44:56Z
Preserve None in Series unique
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index dbeb8bda3e454..b92eb0e651276 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -870,7 +870,12 @@ cdef class PyObjectHashTable(HashTable): for i in range(n): val = values[i] hash(val) - if not checknull(val): + + # `val is None` below is exception to prevent mangling of None and + # other NA values; note however that other NA values (ex: pd.NaT + # and np.nan) will still get mangled, so many not be a permanent + # solution; see GH 20866 + if not checknull(val) or val is None: k = kh_get_pymap(self.table, <PyObject*>val) if k == self.table.n_buckets: kh_put_pymap(self.table, <PyObject*>val, &ret) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 8a8a6f7de70d7..46bd879c2db87 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -491,6 +491,14 @@ def test_tuple_with_strings(self, arg, expected): result = pd.unique(arg) tm.assert_numpy_array_equal(result, expected) + def test_obj_none_preservation(self): + # GH 20866 + arr = np.array(['foo', None], dtype=object) + result = pd.unique(arr) + expected = np.array(['foo', None], dtype=object) + + tm.assert_numpy_array_equal(result, expected, strict_nan=True) + class TestIsin(object):
- [X] closes #20866 - [X] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20893
2018-05-01T04:00:33Z
2018-05-11T18:29:48Z
2018-05-11T18:29:47Z
2018-05-11T18:30:11Z
Read from multiple <tbody> within a <table>
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 567a720fa5e32..35683701efdfd 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -443,6 +443,7 @@ Other Enhancements - :meth:`DataFrame.to_sql` now performs a multivalue insert if the underlying connection supports itk rather than inserting row by row. ``SQLAlchemy`` dialects supporting multivalue inserts include: ``mysql``, ``postgresql``, ``sqlite`` and any dialect with ``supports_multivalues_insert``. (:issue:`14315`, :issue:`8953`) - :func:`read_html` now accepts a ``displayed_only`` keyword argument to controls whether or not hidden elements are parsed (``True`` by default) (:issue:`20027`) +- :func:`read_html` now reads all ``<tbody>`` elements in a ``<table>``, not just the first. (:issue:`20690`) - :meth:`~pandas.core.window.Rolling.quantile` and :meth:`~pandas.core.window.Expanding.quantile` now accept the ``interpolation`` keyword, ``linear`` by default (:issue:`20497`) - zip compression is supported via ``compression=zip`` in :func:`DataFrame.to_pickle`, :func:`Series.to_pickle`, :func:`DataFrame.to_csv`, :func:`Series.to_csv`, :func:`DataFrame.to_json`, :func:`Series.to_json`. (:issue:`17778`) - :class:`pandas.tseries.api.offsets.WeekOfMonth` constructor now supports ``n=0`` (:issue:`20517`). diff --git a/pandas/io/html.py b/pandas/io/html.py index ba5da1b4e3a76..8fd876e85889f 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -324,7 +324,7 @@ def _parse_thead(self, table): raise com.AbstractMethodError(self) def _parse_tbody(self, table): - """Return the body of the table. + """Return the list of tbody elements from the parsed table element. Parameters ---------- @@ -333,8 +333,8 @@ def _parse_tbody(self, table): Returns ------- - tbody : node-like - A <tbody>...</tbody> element. + tbodys : list of node-like + A list of <tbody>...</tbody> elements """ raise com.AbstractMethodError(self) @@ -388,13 +388,17 @@ def _parse_raw_tfoot(self, table): np.array(res).squeeze()) if res and len(res) == 1 else res def _parse_raw_tbody(self, table): - tbody = self._parse_tbody(table) + tbodies = self._parse_tbody(table) - try: - res = self._parse_tr(tbody[0]) - except IndexError: - res = self._parse_tr(table) - return self._parse_raw_data(res) + raw_data = [] + + if tbodies: + for tbody in tbodies: + raw_data.extend(self._parse_tr(tbody)) + else: + raw_data.extend(self._parse_tr(table)) + + return self._parse_raw_data(raw_data) def _handle_hidden_tables(self, tbl_list, attr_name): """Returns list of tables, potentially removing hidden elements diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 078b5f8448d46..a56946b82b027 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -396,6 +396,33 @@ def test_empty_tables(self): res2 = self.read_html(StringIO(data2)) assert_framelist_equal(res1, res2) + def test_multiple_tbody(self): + # GH-20690 + # Read all tbody tags within a single table. + data = '''<table> + <thead> + <tr> + <th>A</th> + <th>B</th> + </tr> + </thead> + <tbody> + <tr> + <td>1</td> + <td>2</td> + </tr> + </tbody> + <tbody> + <tr> + <td>3</td> + <td>4</td> + </tr> + </tbody> + </table>''' + expected = DataFrame({'A': [1, 3], 'B': [2, 4]}) + result = self.read_html(StringIO(data))[0] + tm.assert_frame_equal(result, expected) + def test_header_and_one_column(self): """ Don't fail with bs4 when there is a header and only one column
- [x] closes #20690 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20891
2018-05-01T01:28:15Z
2018-05-01T17:47:47Z
2018-05-01T17:47:47Z
2018-05-01T19:08:36Z
BUG: Fix Series.get() for ExtensionArray and Categorical
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 90ef80c958610..7837faf5b4c0f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3082,12 +3082,17 @@ def get_value(self, series, key): # use this, e.g. DatetimeIndex s = getattr(series, '_values', None) if isinstance(s, (ExtensionArray, Index)) and is_scalar(key): + # GH 20825 + # Unify Index and ExtensionArray treatment + # First try to convert the key to a location + # If that fails, see if key is an integer, and + # try that try: - return s[key] - except (IndexError, ValueError): - - # invalid type as an indexer - pass + iloc = self.get_loc(key) + return s[iloc] + except KeyError: + if is_integer(key): + return s[key] s = com._values_from_object(series) k = com._values_from_object(key) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 5c9ede1079079..883b3f5588aef 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -117,6 +117,36 @@ def test_getitem_slice(self, data): result = data[slice(1)] # scalar assert isinstance(result, type(data)) + def test_get(self, data): + # GH 20882 + s = pd.Series(data, index=[2 * i for i in range(len(data))]) + assert s.get(4) == s.iloc[2] + + result = s.get([4, 6]) + expected = s.iloc[[2, 3]] + self.assert_series_equal(result, expected) + + result = s.get(slice(2)) + expected = s.iloc[[0, 1]] + self.assert_series_equal(result, expected) + + assert s.get(-1) == s.iloc[-1] + assert s.get(s.index.max() + 1) is None + + s = pd.Series(data[:6], index=list('abcdef')) + assert s.get('c') == s.iloc[2] + + result = s.get(slice('b', 'd')) + expected = s.iloc[[1, 2, 3]] + self.assert_series_equal(result, expected) + + result = s.get('Z') + assert result is None + + assert s.get(4) == s.iloc[4] + assert s.get(-1) == s.iloc[-1] + assert s.get(len(s)) is None + def test_take_sequence(self, data): result = pd.Series(data)[[0, 1, 3]] assert result.iloc[0] == data[0]
- [x] closes #20882 - [x] tests added / passed - pandas/tests/extension/base/getitem.py::test_get() - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry - Not created - assume will go in v0.23 as part of ExtensionArray support
https://api.github.com/repos/pandas-dev/pandas/pulls/20885
2018-04-30T16:42:33Z
2018-05-09T11:00:03Z
2018-05-09T11:00:03Z
2018-05-09T13:39:15Z
BUG: Fix #20744. loffset ignored in resample ffill
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 2cf8e3cedf742..728fb938b49d6 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1203,6 +1203,7 @@ Groupby/Resample/Rolling - Bug in :func:`DataFrameGroupBy.cumsum` and :func:`DataFrameGroupBy.cumprod` when ``skipna`` was passed (:issue:`19806`) - Bug in :func:`DataFrame.resample` that dropped timezone information (:issue:`13238`) - Bug in :func:`DataFrame.groupby` where transformations using ``np.all`` and ``np.any`` were raising a ``ValueError`` (:issue:`20653`) +- Bug in :func:`DataFrame.resample` where ``ffill``, ``bfill``, ``pad``, ``backfill``, ``fillna``, ``interpolate``, and ``asfreq`` were ignoring ``loffset``. (:issue:`20744`) Sparse ^^^^^^ diff --git a/pandas/core/resample.py b/pandas/core/resample.py index bc7871a0d75c1..0707cc756682e 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -967,6 +967,7 @@ def _upsample(self, method, limit=None, fill_value=None): result = obj.reindex(res_index, method=method, limit=limit, fill_value=fill_value) + result = self._apply_loffset(result) return self._wrap_result(result) def _wrap_result(self, result): diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 778ea73b3ef25..c1257cce9a9a4 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -1182,6 +1182,19 @@ def test_resample_loffset(self): expected = ser.resample('w-sun', loffset=-bday).last() assert result.index[0] - bday == expected.index[0] + def test_resample_loffset_upsample(self): + # GH 20744 + rng = date_range('1/1/2000 00:00:00', '1/1/2000 00:13:00', freq='min') + s = Series(np.random.randn(14), index=rng) + + result = s.resample('5min', closed='right', label='right', + loffset=timedelta(minutes=1)).ffill() + idx = date_range('1/1/2000', periods=4, freq='5min') + expected = Series([s[0], s[5], s[10], s[-1]], + index=idx + timedelta(minutes=1)) + + assert_series_equal(result, expected) + def test_resample_loffset_count(self): # GH 12725 start_time = '1/1/2000 00:00:00'
- [x] closes #20744 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This replaces pull request #20867
https://api.github.com/repos/pandas-dev/pandas/pulls/20884
2018-04-30T16:40:05Z
2018-05-01T00:33:09Z
2018-05-01T00:33:09Z
2018-05-01T00:33:14Z
DOC: Handle whitespace in pathnames
diff --git a/doc/make.py b/doc/make.py index d85747458148d..cab5fa0ed4c52 100755 --- a/doc/make.py +++ b/doc/make.py @@ -233,10 +233,10 @@ def _sphinx_build(self, kind): '-b{}'.format(kind), '-{}'.format( 'v' * self.verbosity) if self.verbosity else '', - '-d{}'.format(os.path.join(BUILD_PATH, 'doctrees')), + '-d"{}"'.format(os.path.join(BUILD_PATH, 'doctrees')), '-Dexclude_patterns={}'.format(self.exclude_patterns), - SOURCE_PATH, - os.path.join(BUILD_PATH, kind)) + '"{}"'.format(SOURCE_PATH), + '"{}"'.format(os.path.join(BUILD_PATH, kind))) def _open_browser(self): base_url = os.path.join('file://', DOC_PATH, 'build', 'html')
Fixed make.py - Now should be able to run make.py in paths with whitespaces (#20862)
https://api.github.com/repos/pandas-dev/pandas/pulls/20880
2018-04-30T13:21:59Z
2018-09-26T19:41:12Z
2018-09-26T19:41:12Z
2018-09-26T19:41:37Z
DOC: Fix read_hdf docstring
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 4004a6ea8f6ff..78436bd74ec09 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -282,38 +282,60 @@ def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, def read_hdf(path_or_buf, key=None, mode='r', **kwargs): - """ read from the store, close it if we opened it - - Retrieve pandas object stored in file, optionally based on where - criteria + """ + Read from the store, close it if we opened it. - Parameters - ---------- - path_or_buf : path (string), buffer or path object (pathlib.Path or - py._path.local.LocalPath) designating the file to open, or an - already opened pd.HDFStore object + Retrieve pandas object stored in file, optionally based on where + criteria - .. versionadded:: 0.19.0 support for pathlib, py.path. + Parameters + ---------- + path_or_buf : string, buffer or path object + Path to the file to open, or an open :class:`pandas.HDFStore` object. + Supports any object implementing the ``__fspath__`` protocol. + This includes :class:`pathlib.Path` and py._path.local.LocalPath + objects. + + .. versionadded:: 0.19.0 support for pathlib, py.path. + .. versionadded:: 0.21.0 support for __fspath__ proptocol. + + key : object, optional + The group identifier in the store. Can be omitted if the HDF file + contains a single pandas object. + mode : {'r', 'r+', 'a'}, optional + Mode to use when opening the file. Ignored if path_or_buf is a + :class:`pandas.HDFStore`. Default is 'r'. + where : list, optional + A list of Term (or convertible) objects. + start : int, optional + Row number to start selection. + stop : int, optional + Row number to stop selection. + columns : list, optional + A list of columns names to return. + iterator : bool, optional + Return an iterator object. + chunksize : int, optional + Number of rows to include in an iteration when using an iterator. + kwargs : dict + Additional keyword arguments passed to HDFStore. - key : group identifier in the store. Can be omitted if the HDF file - contains a single pandas object. - mode : string, {'r', 'r+', 'a'}, default 'r'. Mode to use when opening - the file. Ignored if path_or_buf is a pd.HDFStore. - where : list of Term (or convertible) objects, optional - start : optional, integer (defaults to None), row number to start - selection - stop : optional, integer (defaults to None), row number to stop - selection - columns : optional, a list of columns that if not None, will limit the - return columns - iterator : optional, boolean, return an iterator, default False - chunksize : optional, nrows to include in iteration, return an iterator + Returns + ------- + item : object + The selected object. Return type depends on the object stored. - Returns - ------- - The selected object + See Also + -------- + pandas.DataFrame.to_hdf : write a HDF file from a DataFrame + pandas.HDFStore : low-level access to HDF files - """ + Examples + -------- + >>> df = pd.DataFrame([[1, 1.0, 'a']], columns=['x', 'y', 'z']) + >>> df.to_hdf('./store.h5', 'data') + >>> reread = pd.read_hdf('./store.h5') + """ if mode not in ['r', 'r+', 'a']: raise ValueError('mode {0} is not allowed while performing a read. '
Read HDF docstring was not in NumPy format. Corrects the formatting [skip ci] - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/20874
2018-04-30T07:46:01Z
2018-04-30T15:06:06Z
2018-04-30T15:06:06Z
2018-06-02T10:33:40Z
Allow `errors` keyword for HDF IO Encoding Err Handling
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 604b68b650201..776ff9709a749 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -450,6 +450,7 @@ Other Enhancements - Updated :meth:`DataFrame.to_gbq` and :meth:`pandas.read_gbq` signature and documentation to reflect changes from the Pandas-GBQ library version 0.4.0. Adds intersphinx mapping to Pandas-GBQ library. (:issue:`20564`) +- :func:`to_hdf` and :func:`read_hdf` now accept an ``errors`` keyword argument to control encoding error handling (:issue:`20835`) .. _whatsnew_0230.api_breaking: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index af19acbb416ee..d3506e069f8c2 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1946,6 +1946,10 @@ def to_hdf(self, path_or_buf, key, **kwargs): If applying compression use the fletcher32 checksum. dropna : bool, default False If true, ALL nan rows will not be written to store. + errors : str, default 'strict' + Specifies how encoding and decoding errors are to be handled. + See the errors argument for :func:`open` for a full list + of options. See Also -------- diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 78436bd74ec09..daa370d0ca61a 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -317,7 +317,11 @@ def read_hdf(path_or_buf, key=None, mode='r', **kwargs): Return an iterator object. chunksize : int, optional Number of rows to include in an iteration when using an iterator. - kwargs : dict + errors : str, default 'strict' + Specifies how encoding and decoding errors are to be handled. + See the errors argument for :func:`open` for a full list + of options. + **kwargs Additional keyword arguments passed to HDFStore. Returns @@ -727,7 +731,7 @@ def select(self, key, where=None, start=None, stop=None, columns=None, def func(_start, _stop, _where): return s.read(start=_start, stop=_stop, where=_where, - columns=columns, **kwargs) + columns=columns) # create the iterator it = TableIterator(self, s, func, where=where, nrows=s.nrows, @@ -1588,14 +1592,14 @@ def infer(self, handler): new_self.read_metadata(handler) return new_self - def convert(self, values, nan_rep, encoding): + def convert(self, values, nan_rep, encoding, errors): """ set the values from this selection: take = take ownership """ # values is a recarray if values.dtype.fields is not None: values = values[self.cname] - values = _maybe_convert(values, self.kind, encoding) + values = _maybe_convert(values, self.kind, encoding, errors) kwargs = dict() if self.freq is not None: @@ -1770,7 +1774,7 @@ class GenericIndexCol(IndexCol): def is_indexed(self): return False - def convert(self, values, nan_rep, encoding): + def convert(self, values, nan_rep, encoding, errors): """ set the values from this selection: take = take ownership """ self.values = Int64Index(np.arange(self.table.nrows)) @@ -1899,7 +1903,7 @@ def set_kind(self): self.typ = getattr(self.description, self.cname, None) def set_atom(self, block, block_items, existing_col, min_itemsize, - nan_rep, info, encoding=None, **kwargs): + nan_rep, info, encoding=None, errors='strict'): """ create and setup my atom from the block b """ self.values = list(block_items) @@ -1944,7 +1948,8 @@ def set_atom(self, block, block_items, existing_col, min_itemsize, existing_col, min_itemsize, nan_rep, - encoding) + encoding, + errors) # set as a data block else: @@ -1954,7 +1959,7 @@ def get_atom_string(self, block, itemsize): return _tables().StringCol(itemsize=itemsize, shape=block.shape[0]) def set_atom_string(self, block, block_items, existing_col, min_itemsize, - nan_rep, encoding): + nan_rep, encoding, errors): # fill nan items with myself, don't disturb the blocks by # trying to downcast block = block.fillna(nan_rep, downcast=False) @@ -1980,7 +1985,7 @@ def set_atom_string(self, block, block_items, existing_col, min_itemsize, ) # itemsize is the maximum length of a string (along any dimension) - data_converted = _convert_string_array(data, encoding) + data_converted = _convert_string_array(data, encoding, errors) itemsize = data_converted.itemsize # specified min_itemsize? @@ -2111,7 +2116,7 @@ def validate_attr(self, append): raise ValueError("appended items dtype do not match existing " "items dtype in table!") - def convert(self, values, nan_rep, encoding): + def convert(self, values, nan_rep, encoding, errors): """set the data from this selection (and convert to the correct dtype if we can) """ @@ -2185,7 +2190,7 @@ def convert(self, values, nan_rep, encoding): # convert nans / decode if _ensure_decoded(self.kind) == u('string'): self.data = _unconvert_string_array( - self.data, nan_rep=nan_rep, encoding=encoding) + self.data, nan_rep=nan_rep, encoding=encoding, errors=errors) return self @@ -2251,10 +2256,12 @@ class Fixed(StringMixin): ndim = None is_table = False - def __init__(self, parent, group, encoding=None, **kwargs): + def __init__(self, parent, group, encoding=None, errors='strict', + **kwargs): self.parent = parent self.group = group self.encoding = _ensure_encoding(encoding) + self.errors = errors self.set_version() @property @@ -2458,10 +2465,12 @@ def is_exists(self): def set_attrs(self): """ set our object attributes """ self.attrs.encoding = self.encoding + self.attrs.errors = self.errors def get_attrs(self): """ retrieve our attributes """ self.encoding = _ensure_encoding(getattr(self.attrs, 'encoding', None)) + self.errors = getattr(self.attrs, 'errors', 'strict') for n in self.attributes: setattr(self, n, _ensure_decoded(getattr(self.attrs, n, None))) @@ -2528,7 +2537,7 @@ def write_index(self, key, index): self.write_sparse_intindex(key, index) else: setattr(self.attrs, '%s_variety' % key, 'regular') - converted = _convert_index(index, self.encoding, + converted = _convert_index(index, self.encoding, self.errors, self.format_type).set_name('index') self.write_array(key, converted.values) @@ -2574,7 +2583,7 @@ def write_multi_index(self, key, index): index.names)): # write the level level_key = '%s_level%d' % (key, i) - conv_level = _convert_index(lev, self.encoding, + conv_level = _convert_index(lev, self.encoding, self.errors, self.format_type).set_name(level_key) self.write_array(level_key, conv_level.values) node = getattr(self.group, level_key) @@ -2635,11 +2644,13 @@ def read_index_node(self, node, start=None, stop=None): if kind in (u('date'), u('datetime')): index = factory(_unconvert_index(data, kind, - encoding=self.encoding), + encoding=self.encoding, + errors=self.errors), dtype=object, **kwargs) else: index = factory(_unconvert_index(data, kind, - encoding=self.encoding), **kwargs) + encoding=self.encoding, + errors=self.errors), **kwargs) index.name = name @@ -2752,7 +2763,8 @@ def read_index_legacy(self, key, start=None, stop=None): node = getattr(self.group, key) data = node[start:stop] kind = node._v_attrs.kind - return _unconvert_index_legacy(data, kind, encoding=self.encoding) + return _unconvert_index_legacy(data, kind, encoding=self.encoding, + errors=self.errors) class LegacySeriesFixed(LegacyFixed): @@ -3171,7 +3183,8 @@ def write_metadata(self, key, values): """ values = Series(values) self.parent.put(self._get_metadata_path(key), values, format='table', - encoding=self.encoding, nan_rep=self.nan_rep) + encoding=self.encoding, errors=self.errors, + nan_rep=self.nan_rep) def read_metadata(self, key): """ return the meta data array for this key """ @@ -3192,6 +3205,7 @@ def set_attrs(self): self.attrs.data_columns = self.data_columns self.attrs.nan_rep = self.nan_rep self.attrs.encoding = self.encoding + self.attrs.errors = self.errors self.attrs.levels = self.levels self.attrs.metadata = self.metadata self.set_info() @@ -3207,6 +3221,7 @@ def get_attrs(self): self.nan_rep = getattr(self.attrs, 'nan_rep', None) self.encoding = _ensure_encoding( getattr(self.attrs, 'encoding', None)) + self.errors = getattr(self.attrs, 'errors', 'strict') self.levels = getattr( self.attrs, 'levels', None) or [] self.index_axes = [ @@ -3364,7 +3379,8 @@ def read_axes(self, where, **kwargs): # convert the data for a in self.axes: a.set_info(self.info) - a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding) + a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding, + errors=self.errors) return True @@ -3446,6 +3462,7 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns = existing_table.data_columns nan_rep = existing_table.nan_rep self.encoding = existing_table.encoding + self.errors = existing_table.errors self.info = copy.copy(existing_table.info) else: existing_table = None @@ -3472,7 +3489,7 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, if i in axes: name = obj._AXIS_NAMES[i] index_axes_map[i] = _convert_index( - a, self.encoding, self.format_type + a, self.encoding, self.errors, self.format_type ).set_name(name).set_axis(i) else: @@ -3591,8 +3608,8 @@ def get_blk_items(mgr, blocks): min_itemsize=min_itemsize, nan_rep=nan_rep, encoding=self.encoding, - info=self.info, - **kwargs) + errors=self.errors, + info=self.info) col.set_pos(j) self.values_axes.append(col) @@ -3756,7 +3773,8 @@ def read_column(self, column, where=None, start=None, stop=None, **kwargs): a.set_info(self.info) return Series(_set_tz(a.convert(c[start:stop], nan_rep=self.nan_rep, - encoding=self.encoding + encoding=self.encoding, + errors=self.errors ).take_data(), a.tz, True), name=column) @@ -4437,7 +4455,7 @@ def _set_tz(values, tz, preserve_UTC=False, coerce=False): return values -def _convert_index(index, encoding=None, format_type=None): +def _convert_index(index, encoding=None, errors='strict', format_type=None): index_name = getattr(index, 'name', None) if isinstance(index, DatetimeIndex): @@ -4491,7 +4509,7 @@ def _convert_index(index, encoding=None, format_type=None): # atom = _tables().ObjectAtom() # return np.asarray(values, dtype='O'), 'object', atom - converted = _convert_string_array(values, encoding) + converted = _convert_string_array(values, encoding, errors) itemsize = converted.dtype.itemsize return IndexCol( converted, 'string', _tables().StringCol(itemsize), @@ -4522,7 +4540,7 @@ def _convert_index(index, encoding=None, format_type=None): index_name=index_name) -def _unconvert_index(data, kind, encoding=None): +def _unconvert_index(data, kind, encoding=None, errors='strict'): kind = _ensure_decoded(kind) if kind == u('datetime64'): index = DatetimeIndex(data) @@ -4541,7 +4559,8 @@ def _unconvert_index(data, kind, encoding=None): elif kind in (u('integer'), u('float')): index = np.asarray(data) elif kind in (u('string')): - index = _unconvert_string_array(data, nan_rep=None, encoding=encoding) + index = _unconvert_string_array(data, nan_rep=None, encoding=encoding, + errors=errors) elif kind == u('object'): index = np.asarray(data[0]) else: # pragma: no cover @@ -4549,20 +4568,22 @@ def _unconvert_index(data, kind, encoding=None): return index -def _unconvert_index_legacy(data, kind, legacy=False, encoding=None): +def _unconvert_index_legacy(data, kind, legacy=False, encoding=None, + errors='strict'): kind = _ensure_decoded(kind) if kind == u('datetime'): index = to_datetime(data) elif kind in (u('integer')): index = np.asarray(data, dtype=object) elif kind in (u('string')): - index = _unconvert_string_array(data, nan_rep=None, encoding=encoding) + index = _unconvert_string_array(data, nan_rep=None, encoding=encoding, + errors=errors) else: # pragma: no cover raise ValueError('unrecognized index type %s' % kind) return index -def _convert_string_array(data, encoding, itemsize=None): +def _convert_string_array(data, encoding, errors, itemsize=None): """ we take a string-like that is object dtype and coerce to a fixed size string type @@ -4571,6 +4592,7 @@ def _convert_string_array(data, encoding, itemsize=None): ---------- data : a numpy array of object dtype encoding : None or string-encoding + errors : handler for encoding errors itemsize : integer, optional, defaults to the max length of the strings Returns @@ -4581,7 +4603,7 @@ def _convert_string_array(data, encoding, itemsize=None): # encode if needed if encoding is not None and len(data): data = Series(data.ravel()).str.encode( - encoding).values.reshape(data.shape) + encoding, errors).values.reshape(data.shape) # create the sized dtype if itemsize is None: @@ -4592,7 +4614,8 @@ def _convert_string_array(data, encoding, itemsize=None): return data -def _unconvert_string_array(data, nan_rep=None, encoding=None): +def _unconvert_string_array(data, nan_rep=None, encoding=None, + errors='strict'): """ inverse of _convert_string_array @@ -4601,6 +4624,7 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None): data : fixed length string dtyped array nan_rep : the storage repr of NaN, optional encoding : the encoding of the data, optional + errors : handler for encoding errors, default 'strict' Returns ------- @@ -4622,7 +4646,7 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None): dtype = "S{0}".format(itemsize) if isinstance(data[0], compat.binary_type): - data = Series(data).str.decode(encoding).values + data = Series(data).str.decode(encoding, errors=errors).values else: data = data.astype(dtype, copy=False).astype(object, copy=False) @@ -4633,22 +4657,23 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None): return data.reshape(shape) -def _maybe_convert(values, val_kind, encoding): +def _maybe_convert(values, val_kind, encoding, errors): if _need_convert(val_kind): - conv = _get_converter(val_kind, encoding) + conv = _get_converter(val_kind, encoding, errors) # conv = np.frompyfunc(conv, 1, 1) values = conv(values) return values -def _get_converter(kind, encoding): +def _get_converter(kind, encoding, errors): kind = _ensure_decoded(kind) if kind == 'datetime64': return lambda x: np.asarray(x, dtype='M8[ns]') elif kind == 'datetime': return lambda x: to_datetime(x, cache=True).to_pydatetime() elif kind == 'string': - return lambda x: _unconvert_string_array(x, encoding=encoding) + return lambda x: _unconvert_string_array(x, encoding=encoding, + errors=errors) else: # pragma: no cover raise ValueError('invalid kind %s' % kind) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index a6a38e005b9b6..366d1645089f3 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -1462,6 +1462,18 @@ def test_to_hdf_with_min_itemsize(self): tm.assert_series_equal(pd.read_hdf(path, 'ss4'), pd.concat([df['B'], df2['B']])) + @pytest.mark.parametrize("format", ['fixed', 'table']) + def test_to_hdf_errors(self, format): + + data = ['\ud800foo'] + ser = pd.Series(data, index=pd.Index(data)) + with ensure_clean_path(self.path) as path: + # GH 20835 + ser.to_hdf(path, 'table', format=format, errors='surrogatepass') + + result = pd.read_hdf(path, 'table', errors='surrogatepass') + tm.assert_series_equal(result, ser) + def test_append_with_data_columns(self): with ensure_clean_store(self.path) as store:
- [X] closes #20835 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20873
2018-04-30T06:21:31Z
2018-05-01T17:48:41Z
2018-05-01T17:48:40Z
2018-05-01T20:06:16Z
DOC: Link to new PyPI instead of legacy PyPI
diff --git a/README.md b/README.md index 78e9b93ae535f..5ff256158aa1b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ <tr> <td>Latest Release</td> <td> - <a href="https://pypi.python.org/pypi/pandas/"> + <a href="https://pypi.org/project/pandas/"> <img src="https://img.shields.io/pypi/v/pandas.svg" alt="latest release" /> </a> </td> @@ -25,7 +25,7 @@ <tr> <td>Package Status</td> <td> - <a href="https://pypi.python.org/pypi/pandas/"> + <a href="https://pypi.org/project/pandas/"> <img src="https://img.shields.io/pypi/status/pandas.svg" alt="status" /></td> </a> </tr> @@ -158,7 +158,7 @@ The source code is currently hosted on GitHub at: https://github.com/pandas-dev/pandas Binary installers for the latest released version are available at the [Python -package index](https://pypi.python.org/pypi/pandas) and on conda. +package index](https://pypi.org/project/pandas) and on conda. ```sh # conda diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 6d5ac31c39a62..58f097c2fc5f3 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -473,7 +473,7 @@ Here are *some* of the more common ``cpplint`` issues: - every header file must include a header guard to avoid name collisions if re-included :ref:`Continuous Integration <contributing.ci>` will run the -`cpplint <https://pypi.python.org/pypi/cpplint>`_ tool +`cpplint <https://pypi.org/project/cpplint>`_ tool and report any stylistic errors in your code. Therefore, it is helpful before submitting code to run the check yourself:: @@ -521,7 +521,7 @@ the more common ``PEP8`` issues: - passing arguments should have spaces after commas, e.g. ``foo(arg1, arg2, kw1='bar')`` :ref:`Continuous Integration <contributing.ci>` will run -the `flake8 <http://pypi.python.org/pypi/flake8>`_ tool +the `flake8 <https://pypi.org/project/flake8>`_ tool and report any stylistic errors in your code. Therefore, it is helpful before submitting code to run the check yourself on the diff:: @@ -798,7 +798,7 @@ Or with one of the following constructs:: pytest pandas/tests/[test-module].py::[TestClass] pytest pandas/tests/[test-module].py::[TestClass]::[test_method] -Using `pytest-xdist <https://pypi.python.org/pypi/pytest-xdist>`_, one can +Using `pytest-xdist <https://pypi.org/project/pytest-xdist>`_, one can speed up local testing on multicore machines. To use this feature, you will need to install `pytest-xdist` via:: diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template index 82ed5e36b6c82..f5ac7b77f4db1 100644 --- a/doc/source/index.rst.template +++ b/doc/source/index.rst.template @@ -12,7 +12,7 @@ pandas: powerful Python data analysis toolkit **Date**: |today| **Version**: |version| -**Binary Installers:** http://pypi.python.org/pypi/pandas +**Binary Installers:** https://pypi.org/project/pandas **Source Repository:** http://github.com/pandas-dev/pandas diff --git a/doc/source/install.rst b/doc/source/install.rst index 4713bbb78d633..6054be112f52c 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -12,7 +12,7 @@ cross platform distribution for data analysis and scientific computing. This is the recommended installation method for most users. Instructions for installing from source, -`PyPI <http://pypi.python.org/pypi/pandas>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, various Linux distributions, or a +`PyPI <https://pypi.org/project/pandas>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, various Linux distributions, or a `development version <http://github.com/pandas-dev/pandas>`__ are also provided. .. _install.dropping-27: @@ -153,7 +153,7 @@ Installing from PyPI ~~~~~~~~~~~~~~~~~~~~ pandas can be installed via pip from -`PyPI <http://pypi.python.org/pypi/pandas>`__. +`PyPI <https://pypi.org/project/pandas>`__. :: @@ -258,7 +258,7 @@ Optional Dependencies * `xarray <http://xarray.pydata.org>`__: pandas like handling for > 2 dims, needed for converting Panels to xarray objects. Version 0.7.0 or higher is recommended. * `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage. Version 3.0.0 or higher required, Version 3.2.1 or higher highly recommended. * `Feather Format <https://github.com/wesm/feather>`__: necessary for feather-based storage, version 0.3.1 or higher. -* `Apache Parquet <https://parquet.apache.org/>`__, either `pyarrow <http://arrow.apache.org/docs/python/>`__ (>= 0.4.1) or `fastparquet <https://fastparquet.readthedocs.io/en/latest>`__ (>= 0.0.6) for parquet-based storage. The `snappy <https://pypi.python.org/pypi/python-snappy>`__ and `brotli <https://pypi.python.org/pypi/brotlipy>`__ are available for compression support. +* `Apache Parquet <https://parquet.apache.org/>`__, either `pyarrow <http://arrow.apache.org/docs/python/>`__ (>= 0.4.1) or `fastparquet <https://fastparquet.readthedocs.io/en/latest>`__ (>= 0.0.6) for parquet-based storage. The `snappy <https://pypi.org/project/python-snappy>`__ and `brotli <https://pypi.org/project/brotlipy>`__ are available for compression support. * `SQLAlchemy <http://www.sqlalchemy.org>`__: for SQL database support. Version 0.8.1 or higher recommended. Besides SQLAlchemy, you also need a database specific driver. You can find an overview of supported drivers for each SQL dialect in the `SQLAlchemy docs <http://docs.sqlalchemy.org/en/latest/dialects/index.html>`__. Some common drivers are: * `psycopg2 <http://initd.org/psycopg/>`__: for PostgreSQL @@ -271,11 +271,11 @@ Optional Dependencies * `xlrd/xlwt <http://www.python-excel.org/>`__: Excel reading (xlrd) and writing (xlwt) * `openpyxl <http://https://openpyxl.readthedocs.io/en/default/>`__: openpyxl version 2.4.0 for writing .xlsx files (xlrd >= 0.9.0) - * `XlsxWriter <https://pypi.python.org/pypi/XlsxWriter>`__: Alternative Excel writer + * `XlsxWriter <https://pypi.org/project/XlsxWriter>`__: Alternative Excel writer * `Jinja2 <http://jinja.pocoo.org/>`__: Template engine for conditional HTML formatting. * `s3fs <http://s3fs.readthedocs.io/>`__: necessary for Amazon S3 access (s3fs >= 0.0.7). -* `blosc <https://pypi.python.org/pypi/blosc>`__: for msgpack compression using ``blosc`` +* `blosc <https://pypi.org/project/blosc>`__: for msgpack compression using ``blosc`` * One of `qtpy <https://github.com/spyder-ide/qtpy>`__ (requires PyQt or PySide), `PyQt5 <https://www.riverbankcomputing.com/software/pyqt/download5>`__, @@ -287,7 +287,7 @@ Optional Dependencies * `pandas-gbq <https://pandas-gbq.readthedocs.io/en/latest/install.html#dependencies>`__: for Google BigQuery I/O. -* `Backports.lzma <https://pypi.python.org/pypi/backports.lzma/>`__: Only for Python 2, for writing to and/or reading from an xz compressed DataFrame in CSV; Python 3 support is built into the standard library. +* `Backports.lzma <https://pypi.org/project/backports.lzma/>`__: Only for Python 2, for writing to and/or reading from an xz compressed DataFrame in CSV; Python 3 support is built into the standard library. * One of the following combinations of libraries is needed to use the top-level :func:`~pandas.read_html` function: diff --git a/doc/source/release.rst b/doc/source/release.rst index da3362b47b29b..709c9b15b55f7 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -34,7 +34,7 @@ analysis / manipulation tool available in any language. **Where to get it** * Source code: http://github.com/pandas-dev/pandas -* Binary installers on PyPI: http://pypi.python.org/pypi/pandas +* Binary installers on PyPI: https://pypi.org/project/pandas * Documentation: http://pandas.pydata.org pandas 0.22.0 diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 82d5a0286b117..d7efd777f4176 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1892,7 +1892,7 @@ def to_parquet(self, fname, engine='auto', compression='snappy', Notes ----- This function requires either the `fastparquet - <https://pypi.python.org/pypi/fastparquet>`_ or `pyarrow + <https://pypi.org/project/fastparquet>`_ or `pyarrow <https://arrow.apache.org/docs/python/>`_ library. Examples diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index 37d398f20ef41..b76a843e3e7f2 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -71,7 +71,7 @@ def determine_clipboard(): try: # qtpy is a small abstraction layer that lets you write # applications using a single api call to either PyQt or PySide - # https://pypi.python.org/pypi/QtPy + # https://pypi.org/project/QtPy import qtpy # noqa except ImportError: # If qtpy isn't installed, fall back on importing PyQt5, or PyQt5 diff --git a/versioneer.py b/versioneer.py index 5dae3723ecf9c..2725fe98641a4 100644 --- a/versioneer.py +++ b/versioneer.py @@ -12,7 +12,7 @@ * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) +](https://pypi.org/project/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer)
The new PyPI site has [officially launched](https://pythoninsider.blogspot.ca/2018/04/new-pypi-launched-legacy-pypi-shutting.html), and they've recommended [linking to the new site](https://warehouse.readthedocs.io/api-reference/integration-guide/#migrating-to-the-new-pypi). Links to the legacy site are currently redirecting to the new site, so the content of what users will actually see isn't different than with the existing links, but seems best to avoid the redirect.
https://api.github.com/repos/pandas-dev/pandas/pulls/20872
2018-04-29T23:42:02Z
2018-04-29T23:49:02Z
2018-04-29T23:49:02Z
2018-04-30T00:05:46Z
DOC: Improve the docstring of Str.contains()
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index c6d45ce5413ac..339c1e057a10f 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -295,29 +295,123 @@ def str_count(arr, pat, flags=0): def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): """ - Return boolean Series/``array`` whether given pattern/regex is - contained in each string in the Series/Index. + Test if pattern or regex is contained within a string of a Series or Index. + + Return boolean Series or Index based on whether a given pattern or regex is + contained within a string of a Series or Index. Parameters ---------- - pat : string - Character sequence or regular expression - case : boolean, default True - If True, case sensitive + pat : str + Character sequence or regular expression. + case : bool, default True + If True, case sensitive. flags : int, default 0 (no flags) - re module flags, e.g. re.IGNORECASE - na : default NaN, fill value for missing values. + Flags to pass through to the re module, e.g. re.IGNORECASE. + na : default NaN + Fill value for missing values. regex : bool, default True - If True use re.search, otherwise use Python in operator + If True, assumes the pat is a regular expression. + + If False, treats the pat as a literal string. Returns ------- - contained : Series/array of boolean values + Series or Index of boolean values + A Series or Index of boolean values indicating whether the + given pattern is contained within the string of each element + of the Series or Index. See Also -------- match : analogous, but stricter, relying on re.match instead of re.search + Examples + -------- + + Returning a Series of booleans using only a literal pattern. + + >>> s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN]) + >>> s1.str.contains('og', regex=False) + 0 False + 1 True + 2 False + 3 False + 4 NaN + dtype: object + + Returning an Index of booleans using only a literal pattern. + + >>> ind = pd.Index(['Mouse', 'dog', 'house and parrot', '23.0', np.NaN]) + >>> ind.str.contains('23', regex=False) + Index([False, False, False, True, nan], dtype='object') + + Specifying case sensitivity using `case`. + + >>> s1.str.contains('oG', case=True, regex=True) + 0 False + 1 False + 2 False + 3 False + 4 NaN + dtype: object + + Specifying `na` to be `False` instead of `NaN` replaces NaN values + with `False`. If Series or Index does not contain NaN values + the resultant dtype will be `bool`, otherwise, an `object` dtype. + + >>> s1.str.contains('og', na=False, regex=True) + 0 False + 1 True + 2 False + 3 False + 4 False + dtype: bool + + Returning 'house' and 'parrot' within same string. + + >>> s1.str.contains('house|parrot', regex=True) + 0 False + 1 False + 2 True + 3 False + 4 NaN + dtype: object + + Ignoring case sensitivity using `flags` with regex. + + >>> import re + >>> s1.str.contains('PARROT', flags=re.IGNORECASE, regex=True) + 0 False + 1 False + 2 True + 3 False + 4 NaN + dtype: object + + Returning any digit using regular expression. + + >>> s1.str.contains('\d', regex=True) + 0 False + 1 False + 2 False + 3 True + 4 NaN + dtype: object + + Ensure `pat` is a not a literal pattern when `regex` is set to True. + Note in the following example one might expect only `s2[1]` and `s2[3]` to + return `True`. However, '.0' as a regex matches any character + followed by a 0. + + >>> s2 = pd.Series(['40','40.0','41','41.0','35']) + >>> s2.str.contains('.0', regex=True) + 0 True + 1 True + 2 False + 3 True + 4 False + dtype: bool """ if regex: if not case:
- [ ] closes #xxxx - [ ] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry ```############################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameter "flags" description should start with capital letter ``` `Achieved through PyData 2018 pandas sprint.`
https://api.github.com/repos/pandas-dev/pandas/pulls/20870
2018-04-29T19:05:31Z
2018-05-10T11:29:53Z
2018-05-10T11:29:53Z
2018-05-10T12:31:16Z
PERF: Fixed regression in Series(index=idx) constructor
diff --git a/pandas/core/series.py b/pandas/core/series.py index 7abd95c68ea2b..1ef6f2d7eee22 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -41,7 +41,11 @@ maybe_cast_to_datetime, maybe_castable, construct_1d_arraylike_from_scalar, construct_1d_object_array_from_listlike) -from pandas.core.dtypes.missing import isna, notna, remove_na_arraylike +from pandas.core.dtypes.missing import ( + isna, + notna, + remove_na_arraylike, + na_value_for_dtype) from pandas.core.index import (Index, MultiIndex, InvalidIndexError, Float64Index, _ensure_index) @@ -300,6 +304,11 @@ def _init_dict(self, data, index=None, dtype=None): if data: keys, values = zip(*compat.iteritems(data)) values = list(values) + elif index is not None: + # fastpath for Series(data=None). Just use broadcasting a scalar + # instead of reindexing. + values = na_value_for_dtype(dtype) + keys = index else: keys, values = [], [] @@ -307,9 +316,11 @@ def _init_dict(self, data, index=None, dtype=None): s = Series(values, index=keys, dtype=dtype) # Now we just make sure the order is respected, if any - if index is not None: + if data and index is not None: s = s.reindex(index, copy=False) - elif not PY36 and not isinstance(data, OrderedDict): + elif not PY36 and not isinstance(data, OrderedDict) and data: + # Need the `and data` to avoid sorting Series(None, index=[...]) + # since that isn't really dict-like try: s = s.sort_index() except TypeError: diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 82b5b1c10fa2d..7e59325c32ddc 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -122,6 +122,21 @@ def test_constructor_nan(self, input_arg): assert_series_equal(empty, empty2, check_index_type=False) + @pytest.mark.parametrize('dtype', [ + 'f8', 'i8', 'M8[ns]', 'm8[ns]', 'category', 'object', + 'datetime64[ns, UTC]', + ]) + @pytest.mark.parametrize('index', [None, pd.Index([])]) + def test_constructor_dtype_only(self, dtype, index): + # GH-20865 + result = pd.Series(dtype=dtype, index=index) + assert result.dtype == dtype + assert len(result) == 0 + + def test_constructor_no_data_index_order(self): + result = pd.Series(index=['b', 'a', 'c']) + assert result.index.tolist() == ['b', 'a', 'c'] + def test_constructor_series(self): index1 = ['d', 'b', 'a', 'c'] index2 = sorted(index1)
From https://github.com/pandas-dev/pandas/pull/18496/ Special cases empty series construction, since the reindex is not necessary. xref https://github.com/pandas-dev/pandas/issues/18532#issuecomment-385190350 Setup ```python data = None idx = date_range(start=datetime(2015, 10, 26), end=datetime(2016, 1, 1), freq='50s') dict_data = dict(zip(idx, range(len(idx)))) data = None if data is None else dict_data ``` benchmark ``` %timeit out = Series(data, index=idx) ``` HEAD: ``` 113 µs ± 6.22 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` 0.21.0 ``` 96.5 µs ± 6.05 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` Master ``` 320 ms ± 11.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20865
2018-04-29T12:00:38Z
2018-04-30T19:01:55Z
2018-04-30T19:01:55Z
2018-04-30T19:02:00Z
DOC: Improve the docstring of String.str.zfill()
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index b27cfdfe3f1bd..93e6f8a53c804 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2473,18 +2473,63 @@ def rjust(self, width, fillchar=' '): def zfill(self, width): """ - Filling left side of strings in the Series/Index with 0. - Equivalent to :meth:`str.zfill`. + Pad strings in the Series/Index by prepending '0' characters. + + Strings in the Series/Index are padded with '0' characters on the + left of the string to reach a total string length `width`. Strings + in the Series/Index with length greater or equal to `width` are + unchanged. Parameters ---------- width : int - Minimum width of resulting string; additional characters will be - filled with 0 + Minimum length of resulting string; strings with length less + than `width` be prepended with '0' characters. Returns ------- - filled : Series/Index of objects + Series/Index of objects + + See Also + -------- + Series.str.rjust: Fills the left side of strings with an arbitrary + character. + Series.str.ljust: Fills the right side of strings with an arbitrary + character. + Series.str.pad: Fills the specified sides of strings with an arbitrary + character. + Series.str.center: Fills boths sides of strings with an arbitrary + character. + + Notes + ----- + Differs from :meth:`str.zfill` which has special handling + for '+'/'-' in the string. + + Examples + -------- + >>> s = pd.Series(['-1', '1', '1000', 10, np.nan]) + >>> s + 0 -1 + 1 1 + 2 1000 + 3 10 + 4 NaN + dtype: object + + Note that ``10`` and ``NaN`` are not strings, therefore they are + converted to ``NaN``. The minus sign in ``'-1'`` is treated as a + regular character and the zero is added to the left of it + (:meth:`str.zfill` would have moved it to the left). ``1000`` + remains unchanged as it is longer than `width`. + + >>> s.str.zfill(3) + 0 0-1 + 1 001 + 2 1000 + 3 NaN + 4 NaN + dtype: object """ result = str_pad(self._data, width, side='left', fillchar='0') return self._wrap_result(result)
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Result of the Pandas sprint at PyData London 2018. Includes work by @owlas.
https://api.github.com/repos/pandas-dev/pandas/pulls/20864
2018-04-29T11:25:24Z
2018-07-07T14:21:51Z
2018-07-07T14:21:51Z
2018-07-07T14:59:55Z
DOC: update the pandas.Series.str.strip docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 9028ce1a77304..e422027b9b500 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2557,12 +2557,66 @@ def encode(self, encoding, errors="strict"): return self._wrap_result(result) _shared_docs['str_strip'] = (""" - Strip whitespace (including newlines) from each string in the - Series/Index from %(side)s. Equivalent to :meth:`str.%(method)s`. + Remove leading and trailing characters. + + Strip whitespaces (including newlines) or a set of specified characters + from each string in the Series/Index from %(side)s. + Equivalent to :meth:`str.%(method)s`. + + Parameters + ---------- + to_strip : str or None, default None. + Specifying the set of characters to be removed. + All combinations of this set of characters will be stripped. + If None then whitespaces are removed. Returns ------- - stripped : Series/Index of objects + Series/Index of objects + + See Also + -------- + Series.str.strip : Remove leading and trailing characters in Series/Index + Series.str.lstrip : Remove leading characters in Series/Index + Series.str.rstrip : Remove trailing characters in Series/Index + + Examples + -------- + >>> s = pd.Series(['1. Ant. ', '2. Bee!\n', '3. Cat?\t', np.nan]) + >>> s + 0 1. Ant. + 1 2. Bee!\n + 2 3. Cat?\t + 3 NaN + dtype: object + + >>> s.str.strip() + 0 1. Ant. + 1 2. Bee! + 2 3. Cat? + 3 NaN + dtype: object + + >>> s.str.lstrip('123.') + 0 Ant. + 1 Bee!\n + 2 Cat?\t + 3 NaN + dtype: object + + >>> s.str.rstrip('.!? \n\t') + 0 1. Ant + 1 2. Bee + 2 3. Cat + 3 NaN + dtype: object + + >>> s.str.strip('123.!? \n\t') + 0 Ant + 1 Bee + 2 Cat + 3 NaN + dtype: object """) @Appender(_shared_docs['str_strip'] % dict(side='left and right sides',
- [ ] closes #xxxx - [ ] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20863
2018-04-29T11:24:12Z
2018-07-07T22:12:44Z
2018-07-07T22:12:43Z
2018-07-07T22:12:44Z
BUG: Correct Escaping for LaTeX, #20859
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index c128058858c17..5f62d1176bc87 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1164,6 +1164,7 @@ I/O - Bug in :func:`DataFrame.to_latex()` where a non-string index-level name would result in an ``AttributeError`` (:issue:`19981`) - Bug in :func:`DataFrame.to_latex()` where the combination of an index name and the `index_names=False` option would result in incorrect output (:issue:`18326`) - Bug in :func:`DataFrame.to_latex()` where a ``MultiIndex`` with an empty string as its name would result in incorrect output (:issue:`18669`) +- Bug in :func:`DataFrame.to_latex()` where missing space characters caused wrong escaping and produced non-valid latex in some cases (:issue:`20859`) - Bug in :func:`read_json` where large numeric values were causing an ``OverflowError`` (:issue:`18842`) - Bug in :func:`DataFrame.to_parquet` where an exception was raised if the write destination is S3 (:issue:`19134`) - :class:`Interval` now supported in :func:`DataFrame.to_excel` for all Excel file types (:issue:`19242`) diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py index 94d48e7f98286..666f124e7d544 100644 --- a/pandas/io/formats/latex.py +++ b/pandas/io/formats/latex.py @@ -134,11 +134,13 @@ def pad_empties(x): buf.write('\\endlastfoot\n') if self.fmt.kwds.get('escape', True): # escape backslashes first - crow = [(x.replace('\\', '\\textbackslash').replace('_', '\\_') + crow = [(x.replace('\\', '\\textbackslash ') + .replace('_', '\\_') .replace('%', '\\%').replace('$', '\\$') .replace('#', '\\#').replace('{', '\\{') - .replace('}', '\\}').replace('~', '\\textasciitilde') - .replace('^', '\\textasciicircum').replace('&', '\\&') + .replace('}', '\\}').replace('~', '\\textasciitilde ') + .replace('^', '\\textasciicircum ') + .replace('&', '\\&') if (x and x != '{}') else '{}') for x in row] else: crow = [x if x else '{}' for x in row] diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index ddd34e0c1626d..73517890565c7 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -369,7 +369,7 @@ def test_to_latex_escape(self): escaped_expected = r'''\begin{tabular}{lll} \toprule -{} & co\$e\textasciicircumx\$ & co\textasciicircuml1 \\ +{} & co\$e\textasciicircum x\$ & co\textasciicircum l1 \\ \midrule a & a & a \\ b & b & b \\ @@ -380,6 +380,22 @@ def test_to_latex_escape(self): assert unescaped_result == unescaped_expected assert escaped_result == escaped_expected + def test_to_latex_special_escape(self): + df = DataFrame([r"a\b\c", r"^a^b^c", r"~a~b~c"]) + + escaped_result = df.to_latex() + escaped_expected = r"""\begin{tabular}{ll} +\toprule +{} & 0 \\ +\midrule +0 & a\textbackslash b\textbackslash c \\ +1 & \textasciicircum a\textasciicircum b\textasciicircum c \\ +2 & \textasciitilde a\textasciitilde b\textasciitilde c \\ +\bottomrule +\end{tabular} +""" + assert escaped_result == escaped_expected + def test_to_latex_longtable(self, frame): frame.to_latex(longtable=True) @@ -447,9 +463,9 @@ def test_to_latex_escape_special_chars(self): 4 & \_ \\ 5 & \{ \\ 6 & \} \\ -7 & \textasciitilde \\ -8 & \textasciicircum \\ -9 & \textbackslash \\ +7 & \textasciitilde \\ +8 & \textasciicircum \\ +9 & \textbackslash \\ \bottomrule \end{tabular} """
- [x] closes #20859 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnewentry
https://api.github.com/repos/pandas-dev/pandas/pulls/20860
2018-04-29T10:39:41Z
2018-04-30T11:21:02Z
2018-04-30T11:21:02Z
2018-04-30T11:21:09Z
DOC: small whatsnew fixes [ci skip]
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index ffa4f1068f84d..c128058858c17 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -365,7 +365,7 @@ for storing ip addresses. ...: ``IPArray`` isn't a normal 1-D NumPy array, but because it's a pandas -:ref:`~pandas.api.extension.ExtensionArray, it can be stored properly inside pandas' containers. +:ref:`~pandas.api.extension.ExtensionArray`, it can be stored properly inside pandas' containers. .. code-block:: ipython @@ -402,7 +402,7 @@ Other Enhancements ^^^^^^^^^^^^^^^^^^ - Unary ``+`` now permitted for ``Series`` and ``DataFrame`` as numeric operator (:issue:`16073`) -- Better support for :func:`Dataframe.style.to_excel` output with the ``xlsxwriter`` engine. (:issue:`16149`) +- Better support for :meth:`~pandas.io.formats.style.Styler.to_excel` output with the ``xlsxwriter`` engine. (:issue:`16149`) - :func:`pandas.tseries.frequencies.to_offset` now accepts leading '+' signs e.g. '+1h'. (:issue:`18171`) - :func:`MultiIndex.unique` now supports the ``level=`` argument, to get unique values from a specific index level (:issue:`17896`) - :class:`pandas.io.formats.style.Styler` now has method ``hide_index()`` to determine whether the index will be rendered in output (:issue:`14194`) @@ -416,7 +416,7 @@ Other Enhancements - :func:`Series` / :func:`DataFrame` tab completion also returns identifiers in the first level of a :func:`MultiIndex`. (:issue:`16326`) - :func:`read_excel()` has gained the ``nrows`` parameter (:issue:`16645`) - :meth:`DataFrame.append` can now in more cases preserve the type of the calling dataframe's columns (e.g. if both are ``CategoricalIndex``) (:issue:`18359`) -- :func:``DataFrame.to_json`` and ``Series.to_json`` now accept an ``index`` argument which allows the user to exclude the index from the JSON output (:issue:`17394`) +- :meth:`DataFrame.to_json` and :meth:`Series.to_json` now accept an ``index`` argument which allows the user to exclude the index from the JSON output (:issue:`17394`) - ``IntervalIndex.to_tuples()`` has gained the ``na_tuple`` parameter to control whether NA is returned as a tuple of NA, or NA itself (:issue:`18756`) - ``Categorical.rename_categories``, ``CategoricalIndex.rename_categories`` and :attr:`Series.cat.rename_categories` can now take a callable as their argument (:issue:`18862`) @@ -433,7 +433,7 @@ Other Enhancements - ``IntervalIndex.astype`` now supports conversions between subtypes when passed an ``IntervalDtype`` (:issue:`19197`) - :class:`IntervalIndex` and its associated constructor methods (``from_arrays``, ``from_breaks``, ``from_tuples``) have gained a ``dtype`` parameter (:issue:`19262`) -- Added :func:`SeriesGroupBy.is_monotonic_increasing` and :func:`SeriesGroupBy.is_monotonic_decreasing` (:issue:`17015`) +- Added :func:`pandas.core.groupby.SeriesGroupBy.is_monotonic_increasing` and :func:`pandas.core.groupby.SeriesGroupBy.is_monotonic_decreasing` (:issue:`17015`) - For subclassed ``DataFrames``, :func:`DataFrame.apply` will now preserve the ``Series`` subclass (if defined) when passing the data to the applied function (:issue:`19822`) - :func:`DataFrame.from_dict` now accepts a ``columns`` argument that can be used to specify the column names when ``orient='index'`` is used (:issue:`18529`) - Added option ``display.html.use_mathjax`` so `MathJax <https://www.mathjax.org/>`_ can be disabled when rendering tables in ``Jupyter`` notebooks (:issue:`19856`, :issue:`19824`) @@ -443,11 +443,11 @@ Other Enhancements - :meth:`DataFrame.to_sql` now performs a multivalue insert if the underlying connection supports itk rather than inserting row by row. ``SQLAlchemy`` dialects supporting multivalue inserts include: ``mysql``, ``postgresql``, ``sqlite`` and any dialect with ``supports_multivalues_insert``. (:issue:`14315`, :issue:`8953`) - :func:`read_html` now accepts a ``displayed_only`` keyword argument to controls whether or not hidden elements are parsed (``True`` by default) (:issue:`20027`) -- :meth:`Rolling.quantile` and :meth:`Expanding.quantile` now accept the ``interpolation`` keyword, ``linear`` by default (:issue:`20497`) +- :meth:`~pandas.core.window.Rolling.quantile` and :meth:`~pandas.core.window.Expanding.quantile` now accept the ``interpolation`` keyword, ``linear`` by default (:issue:`20497`) - zip compression is supported via ``compression=zip`` in :func:`DataFrame.to_pickle`, :func:`Series.to_pickle`, :func:`DataFrame.to_csv`, :func:`Series.to_csv`, :func:`DataFrame.to_json`, :func:`Series.to_json`. (:issue:`17778`) -- :class:`WeekOfMonth` constructor now supports ``n=0`` (:issue:`20517`). +- :class:`pandas.tseries.api.offsets.WeekOfMonth` constructor now supports ``n=0`` (:issue:`20517`). - :class:`DataFrame` and :class:`Series` now support matrix multiplication (```@```) operator (:issue:`10259`) for Python>=3.5 -- Updated ``to_gbq`` and ``read_gbq`` signature and documentation to reflect changes from +- Updated :meth:`DataFrame.to_gbq` and :meth:`pandas.read_gbq` signature and documentation to reflect changes from the Pandas-GBQ library version 0.4.0. Adds intersphinx mapping to Pandas-GBQ library. (:issue:`20564`) @@ -979,7 +979,7 @@ read the `NumFOCUS blogpost`_ recapping the sprint. .. _GitHub search: https://github.com/pandas-dev/pandas/pulls?utf8=%E2%9C%93&q=is%3Apr+label%3ADocs+created%3A2018-03-10..2018-03-15+ .. _NumFOCUS blogpost: https://www.numfocus.org/blog/worldwide-pandas-sprint/ -.. _Marc Garica: https://github.com/datapythonista +.. _Marc Garcia: https://github.com/datapythonista - Changed spelling of "numpy" to "NumPy", and "python" to "Python". (:issue:`19017`) - Consistency when introducing code samples, using either colon or period. @@ -1019,8 +1019,8 @@ Categorical - Bug in :meth:`Index.astype` with a categorical dtype where the resultant index is not converted to a :class:`CategoricalIndex` for all types of index (:issue:`18630`) - Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`) - Bug in :meth:`Series.str.split` with ``expand=True`` incorrectly raising an IndexError on empty strings (:issue:`20002`). -- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`) -- Bug in :class:`Series` constructor with scalar and ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19565`) +- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (:issue:`19032`) +- Bug in :class:`Series` constructor with scalar and ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (:issue:`19565`) - Bug in ``Categorical.__iter__`` not converting to Python types (:issue:`19909`) - Bug in :func:`pandas.factorize` returning the unique codes for the ``uniques``. This now returns a ``Categorical`` with the same dtype as the input (:issue:`19721`) - Bug in :func:`pandas.factorize` including an item for missing values in the ``uniques`` return value (:issue:`19721`)
[ci skip]
https://api.github.com/repos/pandas-dev/pandas/pulls/20847
2018-04-27T15:23:08Z
2018-04-27T18:29:19Z
2018-04-27T18:29:19Z
2018-04-27T18:29:22Z
ENH: linearly spaced date_range (GH 20808)
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index d3746d9e0b61e..53fbe503ac807 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -523,6 +523,7 @@ Other Enhancements library. (:issue:`20564`) - Added new writer for exporting Stata dta files in version 117, ``StataWriter117``. This format supports exporting strings with lengths up to 2,000,000 characters (:issue:`16450`) - :func:`to_hdf` and :func:`read_hdf` now accept an ``errors`` keyword argument to control encoding error handling (:issue:`20835`) +- :func:`date_range` now returns a linearly spaced ``DatetimeIndex`` if ``start``, ``stop``, and ``periods`` are specified, but ``freq`` is not. (:issue:`20808`) .. _whatsnew_0230.api_breaking: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 720718e78d50e..e9ab443a978f8 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -358,7 +358,8 @@ def __new__(cls, data=None, msg = 'periods must be a number, got {periods}' raise TypeError(msg.format(periods=periods)) - if data is None and freq is None: + if data is None and freq is None \ + and com._any_none(periods, start, end): raise ValueError("Must provide freq argument if no data is " "supplied") @@ -466,9 +467,9 @@ def __new__(cls, data=None, @classmethod def _generate(cls, start, end, periods, name, freq, tz=None, normalize=False, ambiguous='raise', closed=None): - if com._count_not_none(start, end, periods) != 2: - raise ValueError('Of the three parameters: start, end, and ' - 'periods, exactly two must be specified') + if com._count_not_none(start, end, periods, freq) != 3: + raise ValueError('Of the four parameters: start, end, periods, ' + 'and freq, exactly three must be specified') _normalized = True @@ -566,23 +567,30 @@ def _generate(cls, start, end, periods, name, freq, if end.tz is None and start.tz is not None: start = start.replace(tzinfo=None) - if _use_cached_range(freq, _normalized, start, end): - index = cls._cached_range(start, end, periods=periods, - freq=freq, name=name) + if freq is not None: + if _use_cached_range(freq, _normalized, start, end): + index = cls._cached_range(start, end, periods=periods, + freq=freq, name=name) + else: + index = _generate_regular_range(start, end, periods, freq) + + if tz is not None and getattr(index, 'tz', None) is None: + index = conversion.tz_localize_to_utc(_ensure_int64(index), + tz, + ambiguous=ambiguous) + index = index.view(_NS_DTYPE) + + # index is localized datetime64 array -> have to convert + # start/end as well to compare + if start is not None: + start = start.tz_localize(tz).asm8 + if end is not None: + end = end.tz_localize(tz).asm8 else: - index = _generate_regular_range(start, end, periods, freq) - - if tz is not None and getattr(index, 'tz', None) is None: - index = conversion.tz_localize_to_utc(_ensure_int64(index), tz, - ambiguous=ambiguous) - index = index.view(_NS_DTYPE) - - # index is localized datetime64 array -> have to convert - # start/end as well to compare - if start is not None: - start = start.tz_localize(tz).asm8 - if end is not None: - end = end.tz_localize(tz).asm8 + index = tools.to_datetime(np.linspace(start.value, + end.value, periods)) + if tz is not None: + index = index.tz_localize('UTC').tz_convert(tz) if not left_closed and len(index) and index[0] == start: index = index[1:] @@ -2565,13 +2573,15 @@ def _generate_regular_range(start, end, periods, freq): return data -def date_range(start=None, end=None, periods=None, freq='D', tz=None, +def date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs): """ Return a fixed frequency DatetimeIndex. - Exactly two of the three parameters `start`, `end` and `periods` - must be specified. + Of the three parameters `start`, `end`, `periods`, and `freq` exactly + three must be specified. If `freq` is omitted, the resulting DatetimeIndex + will have `periods` linearly spaced elements between `start` and `end` + (closed on both sides). Parameters ---------- @@ -2613,7 +2623,7 @@ def date_range(start=None, end=None, periods=None, freq='D', tz=None, -------- **Specifying the values** - The next three examples generate the same `DatetimeIndex`, but vary + The next four examples generate the same `DatetimeIndex`, but vary the combination of `start`, `end` and `periods`. Specify `start` and `end`, with the default daily frequency. @@ -2637,6 +2647,13 @@ def date_range(start=None, end=None, periods=None, freq='D', tz=None, '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'], dtype='datetime64[ns]', freq='D') + Specify `start`, `end`, and `periods`; the frequency is generated + automatically (linearly spaced). + + >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3) + DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00', + '2018-04-27 00:00:00'], freq=None) + **Other Parameters** Changed the `freq` (frequency) to ``'M'`` (month end frequency). @@ -2687,6 +2704,10 @@ def date_range(start=None, end=None, periods=None, freq='D', tz=None, DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'], dtype='datetime64[ns]', freq='D') """ + + if freq is None and com._any_none(periods, start, end): + freq = 'D' + return DatetimeIndex(start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize, name=name, closed=closed, **kwargs) diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index e5291ed52a86c..bbe9cb65eb1a9 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -157,11 +157,28 @@ def test_date_range_ambiguous_arguments(self): start = datetime(2011, 1, 1, 5, 3, 40) end = datetime(2011, 1, 1, 8, 9, 40) - msg = ('Of the three parameters: start, end, and periods, ' - 'exactly two must be specified') + msg = ('Of the four parameters: start, end, periods, and ' + 'freq, exactly three must be specified') with tm.assert_raises_regex(ValueError, msg): date_range(start, end, periods=10, freq='s') + def test_date_range_convenience_periods(self): + # GH 20808 + rng = date_range('2018-04-24', '2018-04-27', periods=3) + exp = DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00', + '2018-04-27 00:00:00'], freq=None) + + tm.assert_index_equal(rng, exp) + + # Test if spacing remains linear if tz changes to dst in range + rng = date_range('2018-04-01 01:00:00', '2018-04-01 04:00:00', + tz='Australia/Sydney', periods=3) + exp = DatetimeIndex(['2018-04-01 01:00:00+11:00', + '2018-04-01 02:00:00+11:00', + '2018-04-01 02:00:00+10:00', + '2018-04-01 03:00:00+10:00', + '2018-04-01 04:00:00+10:00'], freq=None) + def test_date_range_businesshour(self): idx = DatetimeIndex(['2014-07-04 09:00', '2014-07-04 10:00', '2014-07-04 11:00', @@ -198,8 +215,8 @@ def test_date_range_businesshour(self): def test_range_misspecified(self): # GH #1095 - msg = ('Of the three parameters: start, end, and periods, ' - 'exactly two must be specified') + msg = ('Of the four parameters: start, end, periods, and ' + 'freq, exactly three must be specified') with tm.assert_raises_regex(ValueError, msg): date_range(start='1/1/2000')
- [X] closes #20808 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20846
2018-04-27T15:14:38Z
2018-05-03T10:42:05Z
2018-05-03T10:42:05Z
2018-05-03T10:42:12Z
ENH: Add class to write dta format 117 files
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 207589092dd00..e1f6e2c7d12b5 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -503,6 +503,7 @@ Other Enhancements - Updated :meth:`DataFrame.to_gbq` and :meth:`pandas.read_gbq` signature and documentation to reflect changes from the Pandas-GBQ library version 0.4.0. Adds intersphinx mapping to Pandas-GBQ library. (:issue:`20564`) +- Added new writer for exporting Stata dta files in version 117, ``StataWriter117``. This format supports exporting strings with lengths up to 2,000,000 characters (:issue:`16450`) - :func:`to_hdf` and :func:`read_hdf` now accept an ``errors`` keyword argument to control encoding error handling (:issue:`20835`) .. _whatsnew_0230.api_breaking: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d7efd777f4176..f6a57fc5e7ba6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1769,27 +1769,28 @@ def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='', def to_stata(self, fname, convert_dates=None, write_index=True, encoding="latin-1", byteorder=None, time_stamp=None, - data_label=None, variable_labels=None): + data_label=None, variable_labels=None, version=114, + convert_strl=None): """ - A class for writing Stata binary dta files from array-like objects + Export Stata binary dta files. Parameters ---------- fname : str or buffer - String path of file-like object + String path of file-like object. convert_dates : dict Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are 'tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name. Datetime columns that do not have a conversion type specified will be converted to 'tc'. Raises NotImplementedError if - a datetime column has timezone information + a datetime column has timezone information. write_index : bool Write the index to Stata dataset. encoding : str - Default is latin-1. Unicode is not supported + Default is latin-1. Unicode is not supported. byteorder : str - Can be ">", "<", "little", or "big". default is `sys.byteorder` + Can be ">", "<", "little", or "big". default is `sys.byteorder`. time_stamp : datetime A datetime to use as file creation date. Default is the current time. @@ -1801,6 +1802,23 @@ def to_stata(self, fname, convert_dates=None, write_index=True, .. versionadded:: 0.19.0 + version : {114, 117} + Version to use in the output dta file. Version 114 can be used + read by Stata 10 and later. Version 117 can be read by Stata 13 + or later. Version 114 limits string variables to 244 characters or + fewer while 117 allows strings with lengths up to 2,000,000 + characters. + + .. versionadded:: 0.23.0 + + convert_strl : list, optional + List of column names to convert to string columns to Stata StrL + format. Only available if version is 117. Storing strings in the + StrL format can produce smaller dta files if strings have more than + 8 characters and values are repeated. + + .. versionadded:: 0.23.0 + Raises ------ NotImplementedError @@ -1814,6 +1832,12 @@ def to_stata(self, fname, convert_dates=None, write_index=True, .. versionadded:: 0.19.0 + See Also + -------- + pandas.read_stata : Import Stata data files + pandas.io.stata.StataWriter : low-level writer for Stata data files + pandas.io.stata.StataWriter117 : low-level writer for version 117 files + Examples -------- >>> data.to_stata('./data_file.dta') @@ -1832,12 +1856,23 @@ def to_stata(self, fname, convert_dates=None, write_index=True, >>> writer = StataWriter('./date_data_file.dta', data, {2 : 'tw'}) >>> writer.write_file() """ - from pandas.io.stata import StataWriter - writer = StataWriter(fname, self, convert_dates=convert_dates, + kwargs = {} + if version not in (114, 117): + raise ValueError('Only formats 114 and 117 supported.') + if version == 114: + if convert_strl is not None: + raise ValueError('strl support is only available when using ' + 'format 117') + from pandas.io.stata import StataWriter as statawriter + else: + from pandas.io.stata import StataWriter117 as statawriter + kwargs['convert_strl'] = convert_strl + + writer = statawriter(fname, self, convert_dates=convert_dates, encoding=encoding, byteorder=byteorder, time_stamp=time_stamp, data_label=data_label, write_index=write_index, - variable_labels=variable_labels) + variable_labels=variable_labels, **kwargs) writer.write_file() def to_feather(self, fname): diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 9646831cb612c..8f91c7a497e2d 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -25,8 +25,8 @@ from pandas import compat, to_timedelta, to_datetime, isna, DatetimeIndex from pandas.compat import (lrange, lmap, lzip, text_type, string_types, range, zip, BytesIO) -from pandas.core.base import StringMixin from pandas.core.arrays import Categorical +from pandas.core.base import StringMixin from pandas.core.dtypes.common import (is_categorical_dtype, _ensure_object, is_datetime64_dtype) from pandas.core.frame import DataFrame @@ -45,9 +45,9 @@ _statafile_processing_params1 = """\ convert_dates : boolean, defaults to True - Convert date variables to DataFrame time values + Convert date variables to DataFrame time values. convert_categoricals : boolean, defaults to True - Read value labels and convert columns to Categorical/Factor variables""" + Read value labels and convert columns to Categorical/Factor variables.""" _encoding_params = """\ encoding : string, None or encoding @@ -55,7 +55,7 @@ _statafile_processing_params2 = """\ index_col : string, optional, default: None - Column to set as index + Column to set as index. convert_missing : boolean, defaults to False Flag indicating whether to convert missing values to their Stata representations. If False, missing values are replaced with nan. @@ -64,28 +64,29 @@ StataMissingValue objects. preserve_dtypes : boolean, defaults to True Preserve Stata datatypes. If False, numeric data are upcast to pandas - default types for foreign data (float64 or int64) + default types for foreign data (float64 or int64). columns : list or None Columns to retain. Columns will be returned in the given order. None - returns all columns + returns all columns. order_categoricals : boolean, defaults to True Flag indicating whether converted categorical data are ordered.""" _chunksize_params = """\ chunksize : int, default None Return StataReader object for iterations, returns chunks with - given number of lines""" + given number of lines.""" _iterator_params = """\ iterator : boolean, default False - Return StataReader object""" + Return StataReader object.""" -_read_stata_doc = """Read Stata file into DataFrame +_read_stata_doc = """ +Read Stata file into DataFrame. Parameters ---------- filepath_or_buffer : string or file-like object - Path to .dta file or object implementing a binary read() functions + Path to .dta file or object implementing a binary read() functions. %s %s %s @@ -96,17 +97,23 @@ ------- DataFrame or StataReader +See Also +-------- +pandas.io.stata.StataReader : low-level reader for Stata data files +pandas.DataFrame.to_stata: export Stata data files + Examples -------- Read a Stata dta file: ->>> df = pandas.read_stata('filename.dta') +>>> import pandas as pd +>>> df = pd.read_stata('filename.dta') Read a Stata dta file in 10,000 line chunks: ->>> itr = pandas.read_stata('filename.dta', chunksize=10000) +>>> itr = pd.read_stata('filename.dta', chunksize=10000) >>> for chunk in itr: ->>> do_something(chunk) +... do_something(chunk) """ % (_statafile_processing_params1, _encoding_params, _statafile_processing_params2, _chunksize_params, _iterator_params) @@ -127,7 +134,6 @@ DataFrame """ % (_statafile_processing_params1, _statafile_processing_params2) - _read_method_doc = """\ Reads observations from Stata file, converting them into a dataframe @@ -149,8 +155,11 @@ Parameters ---------- -path_or_buf : string or file-like object - Path to .dta file or object implementing a binary read() functions +path_or_buf : path (string), buffer or path object + string, path object (pathlib.Path or py._path.local.LocalPath) or object + implementing a binary read() functions. + + .. versionadded:: 0.23.0 support for pathlib, py.path. %s %s %s @@ -908,10 +917,10 @@ def __init__(self, encoding): } self.OLD_TYPE_MAPPING = { - 98: 251, # byte + 98: 251, # byte 105: 252, # int 108: 253, # long - 102: 254 # float + 102: 254 # float # don't know old code for double } @@ -992,7 +1001,7 @@ def __init__(self, path_or_buf, convert_dates=True, path_or_buf, encoding=self._default_encoding ) - if isinstance(path_or_buf, (str, compat.text_type, bytes)): + if isinstance(path_or_buf, (str, text_type, bytes)): self.path_or_buf = open(path_or_buf, 'rb') else: # Copy to BytesIO, and ensure no encoding @@ -1041,7 +1050,7 @@ def _read_new_header(self, first_char): if self.format_version not in [117, 118]: raise ValueError(_version_error) self.path_or_buf.read(21) # </release><byteorder> - self.byteorder = self.path_or_buf.read(3) == "MSF" and '>' or '<' + self.byteorder = self.path_or_buf.read(3) == b'MSF' and '>' or '<' self.path_or_buf.read(15) # </byteorder><K> self.nvar = struct.unpack(self.byteorder + 'H', self.path_or_buf.read(2))[0] @@ -1805,38 +1814,37 @@ def _dtype_to_stata_type(dtype, column): the dta spec. 1 - 244 are strings of this length Pandas Stata - 251 - chr(251) - for int8 byte - 252 - chr(252) - for int16 int - 253 - chr(253) - for int32 long - 254 - chr(254) - for float32 float - 255 - chr(255) - for double double + 251 - for int8 byte + 252 - for int16 int + 253 - for int32 long + 254 - for float32 float + 255 - for double double If there are dates to convert, then dtype will already have the correct type inserted. """ # TODO: expand to handle datetime to integer conversion - if dtype.type == np.string_: - return chr(dtype.itemsize) - elif dtype.type == np.object_: # try to coerce it to the biggest string - # not memory efficient, what else could we - # do? + if dtype.type == np.object_: # try to coerce it to the biggest string + # not memory efficient, what else could we + # do? itemsize = max_len_string_array(_ensure_object(column.values)) - return chr(max(itemsize, 1)) + return max(itemsize, 1) elif dtype == np.float64: - return chr(255) + return 255 elif dtype == np.float32: - return chr(254) + return 254 elif dtype == np.int32: - return chr(253) + return 253 elif dtype == np.int16: - return chr(252) + return 252 elif dtype == np.int8: - return chr(251) + return 251 else: # pragma : no cover raise NotImplementedError("Data type %s not supported." % dtype) -def _dtype_to_default_stata_fmt(dtype, column): +def _dtype_to_default_stata_fmt(dtype, column, dta_version=114, + force_strl=False): """ Maps numpy dtype to stata's default format for this type. Not terribly important since users can change this in Stata. Semantics are @@ -1849,17 +1857,27 @@ def _dtype_to_default_stata_fmt(dtype, column): int32 -> "%12.0g" int16 -> "%8.0g" int8 -> "%8.0g" + strl -> "%9s" """ # TODO: Refactor to combine type with format # TODO: expand this to handle a default datetime format? + if dta_version < 117: + max_str_len = 244 + else: + max_str_len = 2045 + if force_strl: + return '%9s' if dtype.type == np.object_: inferred_dtype = infer_dtype(column.dropna()) if not (inferred_dtype in ('string', 'unicode') or len(column) == 0): raise ValueError('Writing general object arrays is not supported') itemsize = max_len_string_array(_ensure_object(column.values)) - if itemsize > 244: - raise ValueError(excessive_string_length_error % column.name) + if itemsize > max_str_len: + if dta_version >= 117: + return '%9s' + else: + raise ValueError(excessive_string_length_error % column.name) return "%" + str(max(itemsize, 1)) + "s" elif dtype == np.float64: return "%10.0g" @@ -1879,8 +1897,12 @@ class StataWriter(StataParser): Parameters ---------- - fname : str or buffer - String path of file-like object + fname : path (string), buffer or path object + string, path object (pathlib.Path or py._path.local.LocalPath) or + object implementing a binary write() functions. + + .. versionadded:: 0.23.0 support for pathlib, py.path. + data : DataFrame Input to save convert_dates : dict @@ -1898,7 +1920,7 @@ class StataWriter(StataParser): Can be ">", "<", "little", or "big". default is `sys.byteorder` time_stamp : datetime A datetime to use as file creation date. Default is the current time - dataset_label : str + data_label : str A label for the data set. Must be 80 characters or smaller. variable_labels : dict Dictionary containing columns as keys and variable labels as values. @@ -1937,6 +1959,8 @@ class StataWriter(StataParser): >>> writer.write_file() """ + _max_string_length = 244 + def __init__(self, fname, data, convert_dates=None, write_index=True, encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, variable_labels=None): @@ -1954,6 +1978,7 @@ def __init__(self, fname, data, convert_dates=None, write_index=True, self._byteorder = _set_endianness(byteorder) self._fname = _stringify_path(fname) self.type_converters = {253: np.int32, 252: np.int16, 251: np.int8} + self._converted_names = {} def _write(self, to_write): """ @@ -2018,6 +2043,10 @@ def _replace_nans(self, data): return data + def _update_strl_names(self): + """No-op, forward compatibility""" + pass + def _check_column_names(self, data): """ Checks column names to ensure that they are valid Stata column names. @@ -2031,7 +2060,7 @@ def _check_column_names(self, data): dates are exported, the variable name is propagated to the date conversion dictionary """ - converted_names = [] + converted_names = {} columns = list(data.columns) original_columns = columns[:] @@ -2063,14 +2092,7 @@ def _check_column_names(self, data): name = '_' + str(duplicate_var_id) + name name = name[:min(len(name), 32)] duplicate_var_id += 1 - - # need to possibly encode the orig name if its unicode - try: - orig_name = orig_name.encode('utf-8') - except: - pass - converted_names.append( - '{0} -> {1}'.format(orig_name, name)) + converted_names[orig_name] = name columns[j] = name @@ -2085,12 +2107,31 @@ def _check_column_names(self, data): if converted_names: import warnings + conversion_warning = [] + for orig_name, name in converted_names.items(): + # need to possibly encode the orig name if its unicode + try: + orig_name = orig_name.encode('utf-8') + except (UnicodeDecodeError, AttributeError): + pass + msg = '{0} -> {1}'.format(orig_name, name) + conversion_warning.append(msg) - ws = invalid_name_doc.format('\n '.join(converted_names)) + ws = invalid_name_doc.format('\n '.join(conversion_warning)) warnings.warn(ws, InvalidColumnName) + self._converted_names = converted_names + self._update_strl_names() + return data + def _set_formats_and_types(self, data, dtypes): + self.typlist = [] + self.fmtlist = [] + for col, dtype in dtypes.iteritems(): + self.fmtlist.append(_dtype_to_default_stata_fmt(dtype, data[col])) + self.typlist.append(_dtype_to_stata_type(dtype, data[col])) + def _prepare_pandas(self, data): # NOTE: we might need a different API / class for pandas objects so # we can set different semantics - handle this with a PR to pandas.io @@ -2134,11 +2175,7 @@ def _prepare_pandas(self, data): ) dtypes[key] = np.dtype(new_type) - self.typlist = [] - self.fmtlist = [] - for col, dtype in dtypes.iteritems(): - self.fmtlist.append(_dtype_to_default_stata_fmt(dtype, data[col])) - self.typlist.append(_dtype_to_stata_type(dtype, data[col])) + self._set_formats_and_types(data, dtypes) # set the given format for the datetime cols if self._convert_dates is not None: @@ -2152,16 +2189,44 @@ def write_file(self): try: self._write_header(time_stamp=self._time_stamp, data_label=self._data_label) - self._write_descriptors() + self._write_map() + self._write_variable_types() + self._write_varnames() + self._write_sortlist() + self._write_formats() + self._write_value_label_names() self._write_variable_labels() - # write 5 zeros for expansion fields - self._write(_pad_bytes("", 5)) + self._write_expansion_fields() + self._write_characteristics() self._prepare_data() self._write_data() + self._write_strls() self._write_value_labels() + self._write_file_close_tag() + self._write_map() finally: self._file.close() + def _write_map(self): + """No-op, future compatibility""" + pass + + def _write_file_close_tag(self): + """No-op, future compatibility""" + pass + + def _write_characteristics(self): + """No-op, future compatibility""" + pass + + def _write_strls(self): + """No-op, future compatibility""" + pass + + def _write_expansion_fields(self): + """Write 5 zeros for expansion fields""" + self._write(_pad_bytes("", 5)) + def _write_value_labels(self): for vl in self._value_labels: self._file.write(vl.generate_value_label(self._byteorder, @@ -2204,13 +2269,11 @@ def _write_header(self, data_label=None, time_stamp=None): time_stamp.strftime(" %Y %H:%M")) self._file.write(self._null_terminate(ts)) - def _write_descriptors(self, typlist=None, varlist=None, srtlist=None, - fmtlist=None, lbllist=None): - nvar = self.nvar - # typlist, length nvar, format byte array + def _write_variable_types(self): for typ in self.typlist: - self._write(typ) + self._file.write(struct.pack('B', typ)) + def _write_varnames(self): # varlist names are checked by _check_column_names # varlist, requires null terminated for name in self.varlist: @@ -2218,16 +2281,19 @@ def _write_descriptors(self, typlist=None, varlist=None, srtlist=None, name = _pad_bytes(name[:32], 33) self._write(name) + def _write_sortlist(self): # srtlist, 2*(nvar+1), int array, encoded by byteorder - srtlist = _pad_bytes("", 2 * (nvar + 1)) + srtlist = _pad_bytes("", 2 * (self.nvar + 1)) self._write(srtlist) + def _write_formats(self): # fmtlist, 49*nvar, char array for fmt in self.fmtlist: self._write(_pad_bytes(fmt, 49)) + def _write_value_label_names(self): # lbllist, 33*nvar, char array - for i in range(nvar): + for i in range(self.nvar): # Use variable name when categorical if self._is_col_cat[i]: name = self.varlist[i] @@ -2261,6 +2327,10 @@ def _write_variable_labels(self): else: self._write(blank) + def _convert_strls(self, data): + """No-op, future compatibility""" + return data + def _prepare_data(self): data = self.data typlist = self.typlist @@ -2271,27 +2341,34 @@ def _prepare_data(self): if i in convert_dates: data[col] = _datetime_to_stata_elapsed_vec(data[col], self.fmtlist[i]) + # 2. Convert strls + data = self._convert_strls(data) - # 2. Convert bad string data to '' and pad to correct length - dtype = [] + # 3. Convert bad string data to '' and pad to correct length + dtypes = [] data_cols = [] has_strings = False + native_byteorder = self._byteorder == _set_endianness(sys.byteorder) for i, col in enumerate(data): - typ = ord(typlist[i]) - if typ <= 244: + typ = typlist[i] + if typ <= self._max_string_length: has_strings = True data[col] = data[col].fillna('').apply(_pad_bytes, args=(typ,)) stype = 'S%d' % typ - dtype.append(('c' + str(i), stype)) + dtypes.append(('c' + str(i), stype)) string = data[col].str.encode(self._encoding) data_cols.append(string.values.astype(stype)) else: - dtype.append(('c' + str(i), data[col].dtype)) - data_cols.append(data[col].values) - dtype = np.dtype(dtype) - - if has_strings: - self.data = np.fromiter(zip(*data_cols), dtype=dtype) + values = data[col].values + dtype = data[col].dtype + if not native_byteorder: + dtype = dtype.newbyteorder(self._byteorder) + dtypes.append(('c' + str(i), dtype)) + data_cols.append(values) + dtypes = np.dtype(dtypes) + + if has_strings or not native_byteorder: + self.data = np.fromiter(zip(*data_cols), dtype=dtypes) else: self.data = data.to_records(index=False) @@ -2307,3 +2384,561 @@ def _null_terminate(self, s, as_string=False): else: s += null_byte return s + + +def _dtype_to_stata_type_117(dtype, column, force_strl): + """ + Converts dtype types to stata types. Returns the byte of the given ordinal. + See TYPE_MAP and comments for an explanation. This is also explained in + the dta spec. + 1 - 2045 are strings of this length + Pandas Stata + 32768 - for object strL + 65526 - for int8 byte + 65527 - for int16 int + 65528 - for int32 long + 65529 - for float32 float + 65530 - for double double + + If there are dates to convert, then dtype will already have the correct + type inserted. + """ + # TODO: expand to handle datetime to integer conversion + if force_strl: + return 32768 + if dtype.type == np.object_: # try to coerce it to the biggest string + # not memory efficient, what else could we + # do? + itemsize = max_len_string_array(_ensure_object(column.values)) + itemsize = max(itemsize, 1) + if itemsize <= 2045: + return itemsize + return 32768 + elif dtype == np.float64: + return 65526 + elif dtype == np.float32: + return 65527 + elif dtype == np.int32: + return 65528 + elif dtype == np.int16: + return 65529 + elif dtype == np.int8: + return 65530 + else: # pragma : no cover + raise NotImplementedError("Data type %s not supported." % dtype) + + +def _bytes(s, encoding): + if compat.PY3: + return bytes(s, encoding) + else: + return bytes(s.encode(encoding)) + + +def _pad_bytes_new(name, length): + """ + Takes a bytes instance and pads it with null bytes until it's length chars. + """ + if isinstance(name, string_types): + name = _bytes(name, 'utf-8') + return name + b'\x00' * (length - len(name)) + + +class StataStrLWriter(object): + """ + Converter for Stata StrLs + + Stata StrLs map 8 byte values to strings which are stored using a + dictionary-like format where strings are keyed to two values. + + Parameters + ---------- + df : DataFrame + DataFrame to convert + columns : list + List of columns names to convert to StrL + version : int, optional + dta version. Currently supports 117, 118 and 119 + byteorder : str, optional + Can be ">", "<", "little", or "big". default is `sys.byteorder` + + Notes + ----- + Supports creation of the StrL block of a dta file for dta versions + 117, 118 and 119. These differ in how the GSO is stored. 118 and + 119 store the GSO lookup value as a uint32 and a uint64, while 117 + uses two uint32s. 118 and 119 also encode all strings as unicode + which is required by the format. 117 uses 'latin-1' a fixed width + encoding that extends the 7-bit ascii table with an additional 128 + characters. + """ + + def __init__(self, df, columns, version=117, byteorder=None): + if version not in (117, 118, 119): + raise ValueError('Only dta versions 117, 118 and 119 supported') + self._dta_ver = version + + self.df = df + self.columns = columns + self._gso_table = OrderedDict((('', (0, 0)),)) + if byteorder is None: + byteorder = sys.byteorder + self._byteorder = _set_endianness(byteorder) + + gso_v_type = 'I' # uint32 + gso_o_type = 'Q' # uint64 + self._encoding = 'utf-8' + if version == 117: + o_size = 4 + gso_o_type = 'I' # 117 used uint32 + self._encoding = 'latin-1' + elif version == 118: + o_size = 6 + else: # version == 119 + o_size = 5 + self._o_offet = 2 ** (8 * (8 - o_size)) + self._gso_o_type = gso_o_type + self._gso_v_type = gso_v_type + + def _convert_key(self, key): + v, o = key + return v + self._o_offet * o + + def generate_table(self): + """ + Generates the GSO lookup table for the DataFRame + + Returns + ------- + gso_table : OrderedDict + Ordered dictionary using the string found as keys + and their lookup position (v,o) as values + gso_df : DataFrame + DataFrame where strl columns have been converted to + (v,o) values + + Notes + ----- + Modifies the DataFrame in-place. + + The DataFrame returned encodes the (v,o) values as uint64s. The + encoding depends on teh dta version, and can be expressed as + + enc = v + o * 2 ** (o_size * 8) + + so that v is stored in the lower bits and o is in the upper + bits. o_size is + + * 117: 4 + * 118: 6 + * 119: 5 + """ + + gso_table = self._gso_table + gso_df = self.df + columns = list(gso_df.columns) + selected = gso_df[self.columns] + col_index = [(col, columns.index(col)) for col in self.columns] + keys = np.empty(selected.shape, dtype=np.uint64) + for o, (idx, row) in enumerate(selected.iterrows()): + for j, (col, v) in enumerate(col_index): + val = row[col] + key = gso_table.get(val, None) + if key is None: + # Stata prefers human numbers + key = (v + 1, o + 1) + gso_table[val] = key + keys[o, j] = self._convert_key(key) + for i, col in enumerate(self.columns): + gso_df[col] = keys[:, i] + + return gso_table, gso_df + + def _encode(self, s): + """ + Python 3 compatibility shim + """ + if compat.PY3: + return s.encode(self._encoding) + else: + if isinstance(s, text_type): + return s.encode(self._encoding) + return s + + def generate_blob(self, gso_table): + """ + Generates the binary blob of GSOs that is written to the dta file. + + Parameters + ---------- + gso_table : OrderedDict + Ordered dictionary (str, vo) + + Returns + ------- + gso : bytes + Binary content of dta file to be placed between strl tags + + Notes + ----- + Output format depends on dta version. 117 uses two uint32s to + express v and o while 118+ uses a uint32 for v and a uint64 for o. + """ + # Format information + # Length includes null term + # 117 + # GSOvvvvooootllllxxxxxxxxxxxxxxx...x + # 3 u4 u4 u1 u4 string + null term + # + # 118, 119 + # GSOvvvvooooooootllllxxxxxxxxxxxxxxx...x + # 3 u4 u8 u1 u4 string + null term + + bio = BytesIO() + gso = _bytes('GSO', 'ascii') + gso_type = struct.pack(self._byteorder + 'B', 130) + null = struct.pack(self._byteorder + 'B', 0) + v_type = self._byteorder + self._gso_v_type + o_type = self._byteorder + self._gso_o_type + len_type = self._byteorder + 'I' + for strl, vo in gso_table.items(): + if vo == (0, 0): + continue + v, o = vo + + # GSO + bio.write(gso) + + # vvvv + bio.write(struct.pack(v_type, v)) + + # oooo / oooooooo + bio.write(struct.pack(o_type, o)) + + # t + bio.write(gso_type) + + # llll + encoded = self._encode(strl) + bio.write(struct.pack(len_type, len(encoded) + 1)) + + # xxx...xxx + s = _bytes(strl, 'utf-8') + bio.write(s) + bio.write(null) + + bio.seek(0) + return bio.read() + + +class StataWriter117(StataWriter): + """ + A class for writing Stata binary dta files in Stata 13 format (117) + + .. versionadded:: 0.23.0 + + Parameters + ---------- + fname : path (string), buffer or path object + string, path object (pathlib.Path or py._path.local.LocalPath) or + object implementing a binary write() functions. + data : DataFrame + Input to save + convert_dates : dict + Dictionary mapping columns containing datetime types to stata internal + format to use when writing the dates. Options are 'tc', 'td', 'tm', + 'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name. + Datetime columns that do not have a conversion type specified will be + converted to 'tc'. Raises NotImplementedError if a datetime column has + timezone information + write_index : bool + Write the index to Stata dataset. + encoding : str + Default is latin-1. Only latin-1 and ascii are supported. + byteorder : str + Can be ">", "<", "little", or "big". default is `sys.byteorder` + time_stamp : datetime + A datetime to use as file creation date. Default is the current time + data_label : str + A label for the data set. Must be 80 characters or smaller. + variable_labels : dict + Dictionary containing columns as keys and variable labels as values. + Each label must be 80 characters or smaller. + convert_strl : list + List of columns names to convert to Stata StrL format. Columns with + more than 2045 characters are aautomatically written as StrL. + Smaller columns can be converted by including the column name. Using + StrLs can reduce output file size when strings are longer than 8 + characters, and either frequently repeated or sparse. + + Returns + ------- + writer : StataWriter117 instance + The StataWriter117 instance has a write_file method, which will + write the file to the given `fname`. + + Raises + ------ + NotImplementedError + * If datetimes contain timezone information + ValueError + * Columns listed in convert_dates are neither datetime64[ns] + or datetime.datetime + * Column dtype is not representable in Stata + * Column listed in convert_dates is not in DataFrame + * Categorical label contains more than 32,000 characters + + Examples + -------- + >>> import pandas as pd + >>> from pandas.io.stata import StataWriter117 + >>> data = pd.DataFrame([[1.0, 1, 'a']], columns=['a', 'b', 'c']) + >>> writer = StataWriter117('./data_file.dta', data) + >>> writer.write_file() + + Or with long strings stored in strl format + + >>> data = pd.DataFrame([['A relatively long string'], [''], ['']], + ... columns=['strls']) + >>> writer = StataWriter117('./data_file_with_long_strings.dta', data, + ... convert_strl=['strls']) + >>> writer.write_file() + """ + + _max_string_length = 2045 + + def __init__(self, fname, data, convert_dates=None, write_index=True, + encoding="latin-1", byteorder=None, time_stamp=None, + data_label=None, variable_labels=None, convert_strl=None): + # Shallow copy since convert_strl might be modified later + self._convert_strl = [] if convert_strl is None else convert_strl[:] + + super(StataWriter117, self).__init__(fname, data, convert_dates, + write_index, encoding, byteorder, + time_stamp, data_label, + variable_labels) + self._map = None + self._strl_blob = None + + @staticmethod + def _tag(val, tag): + """Surround val with <tag></tag>""" + if isinstance(val, str) and compat.PY3: + val = _bytes(val, 'utf-8') + return (_bytes('<' + tag + '>', 'utf-8') + val + + _bytes('</' + tag + '>', 'utf-8')) + + def _update_map(self, tag): + """Update map location for tag with file position""" + self._map[tag] = self._file.tell() + + def _write_header(self, data_label=None, time_stamp=None): + """Write the file header""" + byteorder = self._byteorder + self._file.write(_bytes('<stata_dta>', 'utf-8')) + bio = BytesIO() + # ds_format - 117 + bio.write(self._tag(_bytes('117', 'utf-8'), 'release')) + # byteorder + bio.write(self._tag(byteorder == ">" and "MSF" or "LSF", 'byteorder')) + # number of vars, 2 bytes + assert self.nvar < 2 ** 16 + bio.write(self._tag(struct.pack(byteorder + "H", self.nvar), 'K')) + # number of obs, 4 bytes + bio.write(self._tag(struct.pack(byteorder + "I", self.nobs), 'N')) + # data label 81 bytes, char, null terminated + label = data_label[:80] if data_label is not None else '' + label_len = struct.pack(byteorder + "B", len(label)) + label = label_len + _bytes(label, 'utf-8') + bio.write(self._tag(label, 'label')) + # time stamp, 18 bytes, char, null terminated + # format dd Mon yyyy hh:mm + if time_stamp is None: + time_stamp = datetime.datetime.now() + elif not isinstance(time_stamp, datetime.datetime): + raise ValueError("time_stamp should be datetime type") + # Avoid locale-specific month conversion + months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', + 'Sep', 'Oct', 'Nov', 'Dec'] + month_lookup = {i + 1: month for i, month in enumerate(months)} + ts = (time_stamp.strftime("%d ") + + month_lookup[time_stamp.month] + + time_stamp.strftime(" %Y %H:%M")) + # '\x11' added due to inspection of Stata file + ts = b'\x11' + _bytes(ts, 'utf8') + bio.write(self._tag(ts, 'timestamp')) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'header')) + + def _write_map(self): + """Called twice during file write. The first populates the values in + the map with 0s. The second call writes the final map locations when + all blocks have been written.""" + if self._map is None: + self._map = OrderedDict((('stata_data', 0), + ('map', self._file.tell()), + ('variable_types', 0), + ('varnames', 0), + ('sortlist', 0), + ('formats', 0), + ('value_label_names', 0), + ('variable_labels', 0), + ('characteristics', 0), + ('data', 0), + ('strls', 0), + ('value_labels', 0), + ('stata_data_close', 0), + ('end-of-file', 0))) + # Move to start of map + self._file.seek(self._map['map']) + bio = BytesIO() + for val in self._map.values(): + bio.write(struct.pack(self._byteorder + 'Q', val)) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'map')) + + def _write_variable_types(self): + self._update_map('variable_types') + bio = BytesIO() + for typ in self.typlist: + bio.write(struct.pack(self._byteorder + 'H', typ)) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'variable_types')) + + def _write_varnames(self): + self._update_map('varnames') + bio = BytesIO() + for name in self.varlist: + name = self._null_terminate(name, True) + name = _pad_bytes_new(name[:32], 33) + bio.write(name) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'varnames')) + + def _write_sortlist(self): + self._update_map('sortlist') + self._file.write(self._tag(b'\x00\00' * (self.nvar + 1), 'sortlist')) + + def _write_formats(self): + self._update_map('formats') + bio = BytesIO() + for fmt in self.fmtlist: + bio.write(_pad_bytes_new(fmt, 49)) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'formats')) + + def _write_value_label_names(self): + self._update_map('value_label_names') + bio = BytesIO() + for i in range(self.nvar): + # Use variable name when categorical + name = '' # default name + if self._is_col_cat[i]: + name = self.varlist[i] + name = self._null_terminate(name, True) + name = _pad_bytes_new(name[:32], 33) + bio.write(name) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'value_label_names')) + + def _write_variable_labels(self): + # Missing labels are 80 blank characters plus null termination + self._update_map('variable_labels') + bio = BytesIO() + blank = _pad_bytes_new('', 81) + + if self._variable_labels is None: + for _ in range(self.nvar): + bio.write(blank) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'variable_labels')) + return + + for col in self.data: + if col in self._variable_labels: + label = self._variable_labels[col] + if len(label) > 80: + raise ValueError('Variable labels must be 80 characters ' + 'or fewer') + is_latin1 = all(ord(c) < 256 for c in label) + if not is_latin1: + raise ValueError('Variable labels must contain only ' + 'characters that can be encoded in ' + 'Latin-1') + bio.write(_pad_bytes_new(label, 81)) + else: + bio.write(blank) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'variable_labels')) + + def _write_characteristics(self): + self._update_map('characteristics') + self._file.write(self._tag(b'', 'characteristics')) + + def _write_data(self): + self._update_map('data') + data = self.data + self._file.write(b'<data>') + data.tofile(self._file) + self._file.write(b'</data>') + + def _write_strls(self): + self._update_map('strls') + strls = b'' + if self._strl_blob is not None: + strls = self._strl_blob + self._file.write(self._tag(strls, 'strls')) + + def _write_expansion_fields(self): + """No-op in dta 117+""" + pass + + def _write_value_labels(self): + self._update_map('value_labels') + bio = BytesIO() + for vl in self._value_labels: + lab = vl.generate_value_label(self._byteorder, self._encoding) + lab = self._tag(lab, 'lbl') + bio.write(lab) + bio.seek(0) + self._file.write(self._tag(bio.read(), 'value_labels')) + + def _write_file_close_tag(self): + self._update_map('stata_data_close') + self._file.write(_bytes('</stata_dta>', 'utf-8')) + self._update_map('end-of-file') + + def _update_strl_names(self): + """Update column names for conversion to strl if they might have been + changed to comply with Stata naming rules""" + # Update convert_strl if names changed + for orig, new in self._converted_names.items(): + if orig in self._convert_strl: + idx = self._convert_strl.index(orig) + self._convert_strl[idx] = new + + def _convert_strls(self, data): + """Convert columns to StrLs if either very large or in the + convert_strl variable""" + convert_cols = [] + for i, col in enumerate(data): + if self.typlist[i] == 32768 or col in self._convert_strl: + convert_cols.append(col) + if convert_cols: + ssw = StataStrLWriter(data, convert_cols) + tab, new_data = ssw.generate_table() + data = new_data + self._strl_blob = ssw.generate_blob(tab) + return data + + def _set_formats_and_types(self, data, dtypes): + self.typlist = [] + self.fmtlist = [] + for col, dtype in dtypes.iteritems(): + force_strl = col in self._convert_strl + fmt = _dtype_to_default_stata_fmt(dtype, data[col], + dta_version=117, + force_strl=force_strl) + self.fmtlist.append(fmt) + self.typlist.append(_dtype_to_stata_type_117(dtype, data[col], + force_strl)) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 972a47ef91c05..110b790a65037 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -5,21 +5,21 @@ import os import struct import warnings -from datetime import datetime from collections import OrderedDict +from datetime import datetime import numpy as np +import pytest + import pandas as pd import pandas.util.testing as tm -import pytest from pandas import compat -from pandas._libs.tslib import NaT from pandas.compat import iterkeys from pandas.core.dtypes.common import is_categorical_dtype from pandas.core.frame import DataFrame, Series from pandas.io.parsers import read_csv -from pandas.io.stata import (read_stata, StataReader, InvalidColumnName, - PossiblePrecisionLoss, StataMissingValue) +from pandas.io.stata import (InvalidColumnName, PossiblePrecisionLoss, + StataMissingValue, StataReader, read_stata) @pytest.fixture @@ -104,11 +104,12 @@ def read_dta(self, file): def read_csv(self, file): return read_csv(file, parse_dates=True) - def test_read_empty_dta(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_read_empty_dta(self, version): empty_ds = DataFrame(columns=['unit']) # GH 7369, make sure can read a 0-obs dta file with tm.ensure_clean() as path: - empty_ds.to_stata(path, write_index=False) + empty_ds.to_stata(path, write_index=False, version=version) empty_ds2 = read_stata(path) tm.assert_frame_equal(empty_ds, empty_ds2) @@ -319,7 +320,8 @@ def test_write_dta6(self): tm.assert_frame_equal(written_and_read_again.set_index('index'), original, check_index_type=False) - def test_read_write_dta10(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_read_write_dta10(self, version): original = DataFrame(data=[["string", "object", 1, 1.1, np.datetime64('2003-12-25')]], columns=['string', 'object', 'integer', @@ -330,7 +332,7 @@ def test_read_write_dta10(self): original['integer'] = original['integer'].astype(np.int32) with tm.ensure_clean() as path: - original.to_stata(path, {'datetime': 'tc'}) + original.to_stata(path, {'datetime': 'tc'}, version=version) written_and_read_again = self.read_dta(path) # original.index is np.int32, read index is np.int64 tm.assert_frame_equal(written_and_read_again.set_index('index'), @@ -351,7 +353,8 @@ def test_write_preserves_original(self): df.to_stata(path, write_index=False) tm.assert_frame_equal(df, df_copy) - def test_encoding(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_encoding(self, version): # GH 4626, proper encoding handling raw = read_stata(self.dta_encoding) @@ -368,7 +371,8 @@ def test_encoding(self): assert isinstance(result, unicode) # noqa with tm.ensure_clean() as path: - encoded.to_stata(path, encoding='latin-1', write_index=False) + encoded.to_stata(path, encoding='latin-1', + write_index=False, version=version) reread_encoded = read_stata(path, encoding='latin-1') tm.assert_frame_equal(encoded, reread_encoded) @@ -392,7 +396,8 @@ def test_read_write_dta11(self): tm.assert_frame_equal( written_and_read_again.set_index('index'), formatted) - def test_read_write_dta12(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_read_write_dta12(self, version): original = DataFrame([(1, 2, 3, 4, 5, 6)], columns=['astringwithmorethan32characters_1', 'astringwithmorethan32characters_2', @@ -412,7 +417,8 @@ def test_read_write_dta12(self): with tm.ensure_clean() as path: with warnings.catch_warnings(record=True) as w: - original.to_stata(path, None) + warnings.simplefilter('always', InvalidColumnName) + original.to_stata(path, None, version=version) # should get a warning for that format. assert len(w) == 1 @@ -436,9 +442,10 @@ def test_read_write_dta13(self): tm.assert_frame_equal(written_and_read_again.set_index('index'), formatted) + @pytest.mark.parametrize('version', [114, 117]) @pytest.mark.parametrize( 'file', ['dta14_113', 'dta14_114', 'dta14_115', 'dta14_117']) - def test_read_write_reread_dta14(self, file, parsed_114): + def test_read_write_reread_dta14(self, file, parsed_114, version): file = getattr(self, file) parsed = self.read_dta(file) parsed.index.name = 'index' @@ -454,7 +461,7 @@ def test_read_write_reread_dta14(self, file, parsed_114): tm.assert_frame_equal(parsed_114, parsed) with tm.ensure_clean() as path: - parsed_114.to_stata(path, {'date_td': 'td'}) + parsed_114.to_stata(path, {'date_td': 'td'}, version=version) written_and_read_again = self.read_dta(path) tm.assert_frame_equal( written_and_read_again.set_index('index'), parsed_114) @@ -477,18 +484,29 @@ def test_read_write_reread_dta15(self, file): tm.assert_frame_equal(expected, parsed) - def test_timestamp_and_label(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_timestamp_and_label(self, version): original = DataFrame([(1,)], columns=['variable']) time_stamp = datetime(2000, 2, 29, 14, 21) data_label = 'This is a data file.' with tm.ensure_clean() as path: original.to_stata(path, time_stamp=time_stamp, - data_label=data_label) + data_label=data_label, + version=version) with StataReader(path) as reader: assert reader.time_stamp == '29 Feb 2000 14:21' assert reader.data_label == data_label + @pytest.mark.parametrize('version', [114, 117]) + def test_invalid_timestamp(self, version): + original = DataFrame([(1,)], columns=['variable']) + time_stamp = '01 Jan 2000, 00:00:00' + with tm.ensure_clean() as path: + with pytest.raises(ValueError): + original.to_stata(path, time_stamp=time_stamp, + version=version) + def test_numeric_column_names(self): original = DataFrame(np.reshape(np.arange(25.0), (5, 5))) original.index.name = 'index' @@ -504,7 +522,8 @@ def test_numeric_column_names(self): written_and_read_again.columns = map(convert_col_name, columns) tm.assert_frame_equal(original, written_and_read_again) - def test_nan_to_missing_value(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_nan_to_missing_value(self, version): s1 = Series(np.arange(4.0), dtype=np.float32) s2 = Series(np.arange(4.0), dtype=np.float64) s1[::2] = np.nan @@ -512,7 +531,7 @@ def test_nan_to_missing_value(self): original = DataFrame({'s1': s1, 's2': s2}) original.index.name = 'index' with tm.ensure_clean() as path: - original.to_stata(path) + original.to_stata(path, version=version) written_and_read_again = self.read_dta(path) written_and_read_again = written_and_read_again.set_index('index') tm.assert_frame_equal(written_and_read_again, original) @@ -627,7 +646,9 @@ def test_write_missing_strings(self): tm.assert_frame_equal(written_and_read_again.set_index('index'), expected) - def test_bool_uint(self): + @pytest.mark.parametrize('version', [114, 117]) + @pytest.mark.parametrize('byteorder', ['>', '<']) + def test_bool_uint(self, byteorder, version): s0 = Series([0, 1, True], dtype=np.bool) s1 = Series([0, 1, 100], dtype=np.uint8) s2 = Series([0, 1, 255], dtype=np.uint8) @@ -646,7 +667,7 @@ def test_bool_uint(self): expected[c] = expected[c].astype(t) with tm.ensure_clean() as path: - original.to_stata(path) + original.to_stata(path, byteorder=byteorder, version=version) written_and_read_again = self.read_dta(path) written_and_read_again = written_and_read_again.set_index('index') tm.assert_frame_equal(written_and_read_again, expected) @@ -757,7 +778,7 @@ def test_big_dates(self): else: row.append(datetime(yr[i], mo[i], dd[i])) expected.append(row) - expected.append([NaT] * 7) + expected.append([pd.NaT] * 7) columns = ['date_tc', 'date_td', 'date_tw', 'date_tm', 'date_tq', 'date_th', 'date_ty'] @@ -848,7 +869,8 @@ def test_drop_column(self): columns = ['byte_', 'int_', 'long_', 'not_found'] read_stata(self.dta15_117, convert_dates=True, columns=columns) - def test_categorical_writing(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_categorical_writing(self, version): original = DataFrame.from_records( [ ["one", "ten", "one", "one", "one", 1], @@ -880,7 +902,7 @@ def test_categorical_writing(self): with tm.ensure_clean() as path: with warnings.catch_warnings(record=True) as w: # noqa # Silence warnings - original.to_stata(path) + original.to_stata(path, version=version) written_and_read_again = self.read_dta(path) res = written_and_read_again.set_index('index') tm.assert_frame_equal(res, expected, check_categorical=False) @@ -915,7 +937,8 @@ def test_categorical_warnings_and_errors(self): # should get a warning for mixed content assert len(w) == 1 - def test_categorical_with_stata_missing_values(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_categorical_with_stata_missing_values(self, version): values = [['a' + str(i)] for i in range(120)] values.append([np.nan]) original = pd.DataFrame.from_records(values, columns=['many_labels']) @@ -923,7 +946,7 @@ def test_categorical_with_stata_missing_values(self): for col in original], axis=1) original.index.name = 'index' with tm.ensure_clean() as path: - original.to_stata(path) + original.to_stata(path, version=version) written_and_read_again = self.read_dta(path) res = written_and_read_again.set_index('index') tm.assert_frame_equal(res, original, check_categorical=False) @@ -1129,7 +1152,8 @@ def test_read_chunks_columns(self): tm.assert_frame_equal(from_frame, chunk, check_dtype=False) pos += chunksize - def test_write_variable_labels(self): + @pytest.mark.parametrize('version', [114, 117]) + def test_write_variable_labels(self, version): # GH 13631, add support for writing variable labels original = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1.0, 3.0, 27.0, 81.0], @@ -1138,7 +1162,9 @@ def test_write_variable_labels(self): original.index.name = 'index' variable_labels = {'a': 'City Rank', 'b': 'City Exponent', 'c': 'City'} with tm.ensure_clean() as path: - original.to_stata(path, variable_labels=variable_labels) + original.to_stata(path, + variable_labels=variable_labels, + version=version) with StataReader(path) as sr: read_labels = sr.variable_labels() expected_labels = {'index': '', @@ -1149,11 +1175,36 @@ def test_write_variable_labels(self): variable_labels['index'] = 'The Index' with tm.ensure_clean() as path: - original.to_stata(path, variable_labels=variable_labels) + original.to_stata(path, + variable_labels=variable_labels, + version=version) with StataReader(path) as sr: read_labels = sr.variable_labels() assert read_labels == variable_labels + @pytest.mark.parametrize('version', [114, 117]) + def test_invalid_variable_labels(self, version): + original = pd.DataFrame({'a': [1, 2, 3, 4], + 'b': [1.0, 3.0, 27.0, 81.0], + 'c': ['Atlanta', 'Birmingham', + 'Cincinnati', 'Detroit']}) + original.index.name = 'index' + variable_labels = {'a': 'very long' * 10, + 'b': 'City Exponent', + 'c': 'City'} + with tm.ensure_clean() as path: + with pytest.raises(ValueError): + original.to_stata(path, + variable_labels=variable_labels, + version=version) + + variable_labels['a'] = u'invalid character Œ' + with tm.ensure_clean() as path: + with pytest.raises(ValueError): + original.to_stata(path, + variable_labels=variable_labels, + version=version) + def test_write_variable_label_errors(self): original = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1.0, 3.0, 27.0, 81.0], @@ -1201,6 +1252,13 @@ def test_default_date_conversion(self): direct = read_stata(path, convert_dates=True) tm.assert_frame_equal(reread, direct) + dates_idx = original.columns.tolist().index('dates') + original.to_stata(path, + write_index=False, + convert_dates={dates_idx: 'tc'}) + direct = read_stata(path, convert_dates=True) + tm.assert_frame_equal(reread, direct) + def test_unsupported_type(self): original = pd.DataFrame({'a': [1 + 2j, 2 + 4j]}) @@ -1355,3 +1413,63 @@ def test_date_parsing_ignores_format_details(self, column): unformatted = df.loc[0, column] formatted = df.loc[0, column + "_fmt"] assert unformatted == formatted + + def test_writer_117(self): + original = DataFrame(data=[['string', 'object', 1, 1, 1, 1.1, 1.1, + np.datetime64('2003-12-25'), + 'a', 'a' * 2045, 'a' * 5000, 'a'], + ['string-1', 'object-1', 1, 1, 1, 1.1, 1.1, + np.datetime64('2003-12-26'), + 'b', 'b' * 2045, '', ''] + ], + columns=['string', 'object', 'int8', 'int16', + 'int32', 'float32', 'float64', + 'datetime', + 's1', 's2045', 'srtl', 'forced_strl']) + original['object'] = Series(original['object'], dtype=object) + original['int8'] = Series(original['int8'], dtype=np.int8) + original['int16'] = Series(original['int16'], dtype=np.int16) + original['int32'] = original['int32'].astype(np.int32) + original['float32'] = Series(original['float32'], dtype=np.float32) + original.index.name = 'index' + original.index = original.index.astype(np.int32) + copy = original.copy() + with tm.ensure_clean() as path: + original.to_stata(path, + convert_dates={'datetime': 'tc'}, + convert_strl=['forced_strl'], + version=117) + written_and_read_again = self.read_dta(path) + # original.index is np.int32, read index is np.int64 + tm.assert_frame_equal(written_and_read_again.set_index('index'), + original, check_index_type=False) + tm.assert_frame_equal(original, copy) + + def test_convert_strl_name_swap(self): + original = DataFrame([['a' * 3000, 'A', 'apple'], + ['b' * 1000, 'B', 'banana']], + columns=['long1' * 10, 'long', 1]) + original.index.name = 'index' + + with warnings.catch_warnings(record=True) as w: # noqa + with tm.ensure_clean() as path: + original.to_stata(path, convert_strl=['long', 1], version=117) + reread = self.read_dta(path) + reread = reread.set_index('index') + reread.columns = original.columns + tm.assert_frame_equal(reread, original, + check_index_type=False) + + def test_invalid_date_conversion(self): + # GH 12259 + dates = [dt.datetime(1999, 12, 31, 12, 12, 12, 12000), + dt.datetime(2012, 12, 21, 12, 21, 12, 21000), + dt.datetime(1776, 7, 4, 7, 4, 7, 4000)] + original = pd.DataFrame({'nums': [1.0, 2.0, 3.0], + 'strs': ['apple', 'banana', 'cherry'], + 'dates': dates}) + + with tm.ensure_clean() as path: + with pytest.raises(ValueError): + original.to_stata(path, + convert_dates={'wrong_name': 'tc'})
Add export for dta 117 files which add support for long strings Refactor StataWriter to simplify new writer closes #16450 - [x] closes #16450 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20844
2018-04-27T14:52:28Z
2018-05-01T18:57:28Z
2018-05-01T18:57:28Z
2018-06-02T10:33:40Z