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
Fix styling of `DataFrame` for columns with boolean label
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 7f07187e34c78..cc44f43ba8acf 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -1042,6 +1042,7 @@ Styler - Bug in :meth:`Styler.set_sticky` leading to white text on white background in dark mode (:issue:`46984`) - Bug in :meth:`Styler.to_latex` causing ``UnboundLocalError`` when ``clines="all;data"`` and the ``DataFrame`` has no rows. (:issue:`47203`) - Bug in :meth:`Styler.to_excel` when using ``vertical-align: middle;`` with ``xlsxwriter`` engine (:issue:`30107`) +- Bug when applying styles to a DataFrame with boolean column labels (:issue:`47838`) Metadata ^^^^^^^^ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index fbee64771cd9a..f19c4d04f059e 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -2977,6 +2977,12 @@ def hide( # A collection of "builtin" styles # ----------------------------------------------------------------------- + def _get_numeric_subset_default(self): + # Returns a boolean mask indicating where `self.data` has numerical columns. + # Choosing a mask as opposed to the column names also works for + # boolean column labels (GH47838). + return self.data.columns.isin(self.data.select_dtypes(include=np.number)) + @doc( name="background", alt="text", @@ -3120,7 +3126,7 @@ def background_gradient( .. figure:: ../../_static/style/{image_prefix}_axNone_gmap.png """ if subset is None and gmap is None: - subset = self.data.select_dtypes(include=np.number).columns + subset = self._get_numeric_subset_default() self.apply( _background_gradient, @@ -3155,7 +3161,7 @@ def text_gradient( gmap: Sequence | None = None, ) -> Styler: if subset is None and gmap is None: - subset = self.data.select_dtypes(include=np.number).columns + subset = self._get_numeric_subset_default() return self.apply( _background_gradient, @@ -3308,7 +3314,7 @@ def bar( raise ValueError(f"`height` must be a value in [0, 100], got {height}") if subset is None: - subset = self.data.select_dtypes(include=np.number).columns + subset = self._get_numeric_subset_default() self.apply( _bar, diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 23b05c8242274..192fec048a930 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -746,6 +746,22 @@ def color_negative_red(val): df.loc[pct_subset] df.style.applymap(color_negative_red, subset=pct_subset) + @pytest.mark.parametrize( + "stylefunc", ["background_gradient", "bar", "text_gradient"] + ) + def test_subset_for_boolean_cols(self, stylefunc): + # GH47838 + df = DataFrame( + [ + [1, 2], + [3, 4], + ], + columns=[False, True], + ) + styled = getattr(df.style, stylefunc)() + styled._compute() + assert set(styled.ctx) == {(0, 0), (0, 1), (1, 0), (1, 1)} + def test_empty(self): df = DataFrame({"A": [1, 0]}) s = df.style
- [x] closes #47838 - [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. (Not applicable since no new public functions added or signatures modified.) - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Summary of changes * Make the `subset` argument in styling by default a boolean mask indicating where the numerical columns of the data frame are. * Add new test cases for checking that the expected columns are styled in `.ctx`.
https://api.github.com/repos/pandas-dev/pandas/pulls/47848
2022-07-25T15:50:08Z
2022-08-01T18:51:06Z
2022-08-01T18:51:06Z
2022-08-01T19:18:19Z
DOC: Add spaces before `:` to cancel bold
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index d82cc37b90ad4..1892069f78edd 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -206,12 +206,11 @@ def eval( The engine used to evaluate the expression. Supported engines are - - None : tries to use ``numexpr``, falls back to ``python`` - - ``'numexpr'``: This default engine evaluates pandas objects using - numexpr for large speed ups in complex expressions - with large frames. - - ``'python'``: Performs operations as if you had ``eval``'d in top - level python. This engine is generally not that useful. + - None : tries to use ``numexpr``, falls back to ``python`` + - ``'numexpr'`` : This default engine evaluates pandas objects using + numexpr for large speed ups in complex expressions with large frames. + - ``'python'`` : Performs operations as if you had ``eval``'d in top + level python. This engine is generally not that useful. More backends may be available in the future.
- [x] closes #47735 - [ ] [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/47847
2022-07-25T12:40:47Z
2022-07-25T16:35:29Z
2022-07-25T16:35:29Z
2022-07-26T03:00:01Z
BUG: fix bug where appending unordered ``CategoricalIndex`` variables overrides index
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index a1a2149da7cf6..5a95883e12fd1 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -407,7 +407,6 @@ upon serialization. (Related issue :issue:`12997`) # Roundtripping now works pd.read_json(a.to_json(date_format='iso'), typ="series").index == a.index - .. _whatsnew_150.notable_bug_fixes.groupby_value_counts_categorical: DataFrameGroupBy.value_counts with non-grouping categorical columns and ``observed=True`` @@ -888,8 +887,9 @@ Bug fixes Categorical ^^^^^^^^^^^ -- Bug in :meth:`Categorical.view` not accepting integer dtypes (:issue:`25464`) -- Bug in :meth:`CategoricalIndex.union` when the index's categories are integer-dtype and the index contains ``NaN`` values incorrectly raising instead of casting to ``float64`` (:issue:`45362`) +- Bug in :meth:`.Categorical.view` not accepting integer dtypes (:issue:`25464`) +- Bug in :meth:`.CategoricalIndex.union` when the index's categories are integer-dtype and the index contains ``NaN`` values incorrectly raising instead of casting to ``float64`` (:issue:`45362`) +- Bug in :meth:`DataFrame.concat` when concatenating two (or more) unordered ``CategoricalIndex`` variables, whose categories are permutations, yields incorrect index values (:issue:`24845`) Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e068c1434fd4e..d1bdedee5caa0 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -573,7 +573,9 @@ def map(self, mapper): def _concat(self, to_concat: list[Index], name: Hashable) -> Index: # if calling index is category, don't check dtype of others try: - codes = np.concatenate([self._is_dtype_compat(c).codes for c in to_concat]) + cat = Categorical._concat_same_type( + [self._is_dtype_compat(c) for c in to_concat] + ) except TypeError: # not all to_concat elements are among our categories (or NA) from pandas.core.dtypes.concat import concat_compat @@ -581,5 +583,4 @@ def _concat(self, to_concat: list[Index], name: Hashable) -> Index: res = concat_compat([x._values for x in to_concat]) return Index(res, name=name) else: - cat = self._data._from_backing_data(codes) return type(self)._simple_new(cat, name=name) diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py index 5bafd2e8e8503..f00d3b369a94d 100644 --- a/pandas/tests/reshape/concat/test_categorical.py +++ b/pandas/tests/reshape/concat/test_categorical.py @@ -238,3 +238,19 @@ def test_categorical_missing_from_one_frame(self): index=[0, 1, 2, 0, 1, 2], ) tm.assert_frame_equal(result, expected) + + def test_concat_categorical_same_categories_different_order(self): + # https://github.com/pandas-dev/pandas/issues/24845 + + c1 = pd.CategoricalIndex(["a", "a"], categories=["a", "b"], ordered=False) + c2 = pd.CategoricalIndex(["b", "b"], categories=["b", "a"], ordered=False) + c3 = pd.CategoricalIndex( + ["a", "a", "b", "b"], categories=["a", "b"], ordered=False + ) + + df1 = DataFrame({"A": [1, 2]}, index=c1) + df2 = DataFrame({"A": [3, 4]}, index=c2) + + result = pd.concat((df1, df2)) + expected = DataFrame({"A": [1, 2, 3, 4]}, index=c3) + tm.assert_frame_equal(result, expected)
- [x] closes #24845 - [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/47841
2022-07-24T22:42:35Z
2022-08-16T18:38:20Z
2022-08-16T18:38:20Z
2022-08-16T18:38:55Z
BUG Fixing columns dropped from multi index in group by transform GH4…
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index d138ebb9c02a3..7fc8b16bbed9a 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -1010,6 +1010,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.resample` reduction methods when used with ``on`` would attempt to aggregate the provided column (:issue:`47079`) - Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` would not respect ``dropna=False`` when the input DataFrame/Series had a NaN values in a :class:`MultiIndex` (:issue:`46783`) - Bug in :meth:`DataFrameGroupBy.resample` raises ``KeyError`` when getting the result from a key list which misses the resample key (:issue:`47362`) +- Bug in :meth:`DataFrame.groupby` would lose index columns when the DataFrame is empty for transforms, like fillna (:issue:`47787`) - Reshaping diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 28e1b2b388035..26ae5ba91708f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1020,6 +1020,11 @@ def curried(x): return self.apply(curried) is_transform = name in base.transformation_kernels + + # Transform needs to keep the same schema, including when empty + if is_transform and self._obj_with_exclusions.empty: + return self._obj_with_exclusions + result = self._python_apply_general( curried, self._obj_with_exclusions, is_transform=is_transform ) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 920b869ef799b..df49db9ec9dad 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2348,6 +2348,42 @@ def test_groupby_duplicate_index(): tm.assert_series_equal(result, expected) +def test_group_on_empty_multiindex(transformation_func, request): + # GH 47787 + # With one row, those are transforms so the schema should be the same + if transformation_func == "tshift": + mark = pytest.mark.xfail(raises=NotImplementedError) + request.node.add_marker(mark) + df = DataFrame( + data=[[1, Timestamp("today"), 3, 4]], + columns=["col_1", "col_2", "col_3", "col_4"], + ) + df["col_3"] = df["col_3"].astype(int) + df["col_4"] = df["col_4"].astype(int) + df = df.set_index(["col_1", "col_2"]) + if transformation_func == "fillna": + args = ("ffill",) + elif transformation_func == "tshift": + args = (1, "D") + else: + args = () + result = df.iloc[:0].groupby(["col_1"]).transform(transformation_func, *args) + expected = df.groupby(["col_1"]).transform(transformation_func, *args).iloc[:0] + if transformation_func in ("diff", "shift"): + expected = expected.astype(int) + tm.assert_equal(result, expected) + + result = ( + df["col_3"].iloc[:0].groupby(["col_1"]).transform(transformation_func, *args) + ) + expected = ( + df["col_3"].groupby(["col_1"]).transform(transformation_func, *args).iloc[:0] + ) + if transformation_func in ("diff", "shift"): + expected = expected.astype(int) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( "idx", [
…7787 - [x] closes #47787 - [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/47840
2022-07-24T21:00:05Z
2022-08-17T01:38:30Z
2022-08-17T01:38:30Z
2022-08-17T20:12:21Z
DEPR: inplace keyword for Categorical.set_ordered, setting .categories directly
diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst index 0adb937de2b8b..c767fb1ebef7f 100644 --- a/doc/source/user_guide/10min.rst +++ b/doc/source/user_guide/10min.rst @@ -680,12 +680,12 @@ Converting the raw grades to a categorical data type: df["grade"] = df["raw_grade"].astype("category") df["grade"] -Rename the categories to more meaningful names (assigning to -:meth:`Series.cat.categories` is in place!): +Rename the categories to more meaningful names: .. ipython:: python - df["grade"].cat.categories = ["very good", "good", "very bad"] + new_categories = ["very good", "good", "very bad"] + df["grade"] = df["grade"].cat.rename_categories(new_categories) Reorder the categories and simultaneously add the missing categories (methods under :meth:`Series.cat` return a new :class:`Series` by default): diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst index 0105cf99193dd..b5cb1d83a9f52 100644 --- a/doc/source/user_guide/categorical.rst +++ b/doc/source/user_guide/categorical.rst @@ -334,8 +334,7 @@ It's also possible to pass in the categories in a specific order: Renaming categories ~~~~~~~~~~~~~~~~~~~ -Renaming categories is done by assigning new values to the -``Series.cat.categories`` property or by using the +Renaming categories is done by using the :meth:`~pandas.Categorical.rename_categories` method: @@ -343,9 +342,8 @@ Renaming categories is done by assigning new values to the s = pd.Series(["a", "b", "c", "a"], dtype="category") s - s.cat.categories = ["Group %s" % g for g in s.cat.categories] - s - s = s.cat.rename_categories([1, 2, 3]) + new_categories = ["Group %s" % g for g in s.cat.categories] + s = s.cat.rename_categories(new_categories) s # You can also pass a dict-like object to map the renaming s = s.cat.rename_categories({1: "x", 2: "y", 3: "z"}) @@ -365,7 +363,7 @@ Categories must be unique or a ``ValueError`` is raised: .. ipython:: python try: - s.cat.categories = [1, 1, 1] + s = s.cat.rename_categories([1, 1, 1]) except ValueError as e: print("ValueError:", str(e)) @@ -374,7 +372,7 @@ Categories must also not be ``NaN`` or a ``ValueError`` is raised: .. ipython:: python try: - s.cat.categories = [1, 2, np.nan] + s = s.cat.rename_categories([1, 2, np.nan]) except ValueError as e: print("ValueError:", str(e)) @@ -702,7 +700,7 @@ of length "1". .. ipython:: python df.iat[0, 0] - df["cats"].cat.categories = ["x", "y", "z"] + df["cats"] = df["cats"].cat.rename_categories(["x", "y", "z"]) df.at["h", "cats"] # returns a string .. note:: @@ -960,7 +958,7 @@ relevant columns back to ``category`` and assign the right categories and catego s = pd.Series(pd.Categorical(["a", "b", "b", "a", "a", "d"])) # rename the categories - s.cat.categories = ["very good", "good", "bad"] + s = s.cat.rename_categories(["very good", "good", "bad"]) # reorder the categories and add missing categories s = s.cat.set_categories(["very bad", "bad", "medium", "good", "very good"]) df = pd.DataFrame({"cats": s, "vals": [1, 2, 3, 4, 5, 6]}) @@ -1164,6 +1162,7 @@ Constructing a ``Series`` from a ``Categorical`` will not copy the input change the original ``Categorical``: .. ipython:: python + :okwarning: cat = pd.Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) s = pd.Series(cat, name="cat") diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 25625dba1080f..5bde726791fd1 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -558,7 +558,8 @@ This matches the behavior of :meth:`Categorical.set_categories`. df = pd.read_csv(StringIO(data), dtype="category") df.dtypes df["col3"] - df["col3"].cat.categories = pd.to_numeric(df["col3"].cat.categories) + new_categories = pd.to_numeric(df["col3"].cat.categories) + df["col3"] = df["col3"].cat.rename_categories(new_categories) df["col3"] diff --git a/doc/source/whatsnew/v0.19.0.rst b/doc/source/whatsnew/v0.19.0.rst index 113bbcf0a05bc..f2fdd23af1297 100644 --- a/doc/source/whatsnew/v0.19.0.rst +++ b/doc/source/whatsnew/v0.19.0.rst @@ -271,6 +271,7 @@ Individual columns can be parsed as a ``Categorical`` using a dict specification such as :func:`to_datetime`. .. ipython:: python + :okwarning: df = pd.read_csv(StringIO(data), dtype="category") df.dtypes diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 6e38024e02f36..f405e61db1879 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -775,6 +775,8 @@ Other Deprecations - Deprecated :meth:`Series.rank` returning an empty result when the dtype is non-numeric and ``numeric_only=True`` is provided; this will raise a ``TypeError`` in a future version (:issue:`47500`) - Deprecated argument ``errors`` for :meth:`Series.mask`, :meth:`Series.where`, :meth:`DataFrame.mask`, and :meth:`DataFrame.where` as ``errors`` had no effect on this methods (:issue:`47728`) - Deprecated arguments ``*args`` and ``**kwargs`` in :class:`Rolling`, :class:`Expanding`, and :class:`ExponentialMovingWindow` ops. (:issue:`47836`) +- Deprecated the ``inplace`` keyword in :meth:`Categorical.set_ordered`, :meth:`Categorical.as_ordered`, and :meth:`Categorical.as_unordered` (:issue:`37643`) +- Deprecated setting a categorical's categories with ``cat.categories = ['a', 'b', 'c']``, use :meth:`Categorical.rename_categories` instead (:issue:`37643`) - Deprecated unused arguments ``encoding`` and ``verbose`` in :meth:`Series.to_excel` and :meth:`DataFrame.to_excel` (:issue:`47912`) - Deprecated producing a single element when iterating over a :class:`DataFrameGroupBy` or a :class:`SeriesGroupBy` that has been grouped by a list of length 1; A tuple of length one will be returned instead (:issue:`42795`) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 2c3b7c2f2589d..127814dc58f4c 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -745,15 +745,14 @@ def categories(self) -> Index: @categories.setter def categories(self, categories) -> None: - new_dtype = CategoricalDtype(categories, ordered=self.ordered) - if self.dtype.categories is not None and len(self.dtype.categories) != len( - new_dtype.categories - ): - raise ValueError( - "new categories need to have the same number of " - "items as the old categories!" - ) - super().__init__(self._ndarray, new_dtype) + warn( + "Setting categories in-place is deprecated and will raise in a " + "future version. Use rename_categories instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + self._set_categories(categories) @property def ordered(self) -> Ordered: @@ -814,7 +813,7 @@ def _set_categories(self, categories, fastpath=False): ): raise ValueError( "new categories need to have the same number of " - "items than the old categories!" + "items as the old categories!" ) super().__init__(self._ndarray, new_dtype) @@ -836,7 +835,9 @@ def _set_dtype(self, dtype: CategoricalDtype) -> Categorical: return type(self)(codes, dtype=dtype, fastpath=True) @overload - def set_ordered(self, value, *, inplace: Literal[False] = ...) -> Categorical: + def set_ordered( + self, value, *, inplace: NoDefault | Literal[False] = ... + ) -> Categorical: ... @overload @@ -848,7 +849,9 @@ def set_ordered(self, value, *, inplace: bool) -> Categorical | None: ... @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "value"]) - def set_ordered(self, value, inplace: bool = False) -> Categorical | None: + def set_ordered( + self, value, inplace: bool | NoDefault = no_default + ) -> Categorical | None: """ Set the ordered attribute to the boolean value. @@ -859,7 +862,22 @@ def set_ordered(self, value, inplace: bool = False) -> Categorical | None: inplace : bool, default False Whether or not to set the ordered attribute in-place or return a copy of this categorical with ordered set to the value. + + .. deprecated:: 1.5.0 + """ + if inplace is not no_default: + warn( + "The `inplace` parameter in pandas.Categorical." + "set_ordered is deprecated and will be removed in " + "a future version. setting ordered-ness on categories will always " + "return a new Categorical object.", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + inplace = False + inplace = validate_bool_kwarg(inplace, "inplace") new_dtype = CategoricalDtype(self.categories, ordered=value) cat = self if inplace else self.copy() @@ -869,7 +887,7 @@ def set_ordered(self, value, inplace: bool = False) -> Categorical | None: return None @overload - def as_ordered(self, *, inplace: Literal[False] = ...) -> Categorical: + def as_ordered(self, *, inplace: NoDefault | Literal[False] = ...) -> Categorical: ... @overload @@ -877,7 +895,7 @@ def as_ordered(self, *, inplace: Literal[True]) -> None: ... @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def as_ordered(self, inplace: bool = False) -> Categorical | None: + def as_ordered(self, inplace: bool | NoDefault = no_default) -> Categorical | None: """ Set the Categorical to be ordered. @@ -887,16 +905,19 @@ def as_ordered(self, inplace: bool = False) -> Categorical | None: Whether or not to set the ordered attribute in-place or return a copy of this categorical with ordered set to True. + .. deprecated:: 1.5.0 + Returns ------- Categorical or None Ordered Categorical or None if ``inplace=True``. """ - inplace = validate_bool_kwarg(inplace, "inplace") + if inplace is not no_default: + inplace = validate_bool_kwarg(inplace, "inplace") return self.set_ordered(True, inplace=inplace) @overload - def as_unordered(self, *, inplace: Literal[False] = ...) -> Categorical: + def as_unordered(self, *, inplace: NoDefault | Literal[False] = ...) -> Categorical: ... @overload @@ -904,7 +925,9 @@ def as_unordered(self, *, inplace: Literal[True]) -> None: ... @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def as_unordered(self, inplace: bool = False) -> Categorical | None: + def as_unordered( + self, inplace: bool | NoDefault = no_default + ) -> Categorical | None: """ Set the Categorical to be unordered. @@ -914,12 +937,15 @@ def as_unordered(self, inplace: bool = False) -> Categorical | None: Whether or not to set the ordered attribute in-place or return a copy of this categorical with ordered set to False. + .. deprecated:: 1.5.0 + Returns ------- Categorical or None Unordered Categorical or None if ``inplace=True``. """ - inplace = validate_bool_kwarg(inplace, "inplace") + if inplace is not no_default: + inplace = validate_bool_kwarg(inplace, "inplace") return self.set_ordered(False, inplace=inplace) def set_categories( @@ -1108,11 +1134,11 @@ def rename_categories( cat = self if inplace else self.copy() if is_dict_like(new_categories): - cat.categories = [new_categories.get(item, item) for item in cat.categories] + new_categories = [new_categories.get(item, item) for item in cat.categories] elif callable(new_categories): - cat.categories = [new_categories(item) for item in cat.categories] - else: - cat.categories = new_categories + new_categories = [new_categories(item) for item in cat.categories] + + cat._set_categories(new_categories) if not inplace: return cat return None diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 3daa6d837349e..290f976e319f7 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1931,9 +1931,8 @@ def _do_convert_categoricals( categories = list(vl.values()) try: # Try to catch duplicate categories - # error: Incompatible types in assignment (expression has - # type "List[str]", variable has type "Index") - cat_data.categories = categories # type: ignore[assignment] + # TODO: if we get a non-copying rename_categories, use that + cat_data = cat_data.rename_categories(categories) except ValueError as err: vc = Series(categories).value_counts() repeated_cats = list(vc.index[vc > 1]) diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 6b16ffffe9328..1a8dbe25c0b75 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -323,13 +323,22 @@ def test_validate_inplace_raises(self, value): f"received type {type(value).__name__}" ) with pytest.raises(ValueError, match=msg): - cat.set_ordered(value=True, inplace=value) + with tm.assert_produces_warning( + FutureWarning, match="Use rename_categories" + ): + cat.set_ordered(value=True, inplace=value) with pytest.raises(ValueError, match=msg): - cat.as_ordered(inplace=value) + with tm.assert_produces_warning( + FutureWarning, match="Use rename_categories" + ): + cat.as_ordered(inplace=value) with pytest.raises(ValueError, match=msg): - cat.as_unordered(inplace=value) + with tm.assert_produces_warning( + FutureWarning, match="Use rename_categories" + ): + cat.as_unordered(inplace=value) with pytest.raises(ValueError, match=msg): with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index 87b1bb88aeac3..3d5f1d3733254 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -34,22 +34,30 @@ def test_ordered_api(self): assert cat4.ordered def test_set_ordered(self): - + msg = ( + "The `inplace` parameter in pandas.Categorical.set_ordered is " + "deprecated and will be removed in a future version. setting " + "ordered-ness on categories will always return a new Categorical object" + ) cat = Categorical(["a", "b", "c", "a"], ordered=True) cat2 = cat.as_unordered() assert not cat2.ordered cat2 = cat.as_ordered() assert cat2.ordered - cat2.as_unordered(inplace=True) + with tm.assert_produces_warning(FutureWarning, match=msg): + cat2.as_unordered(inplace=True) assert not cat2.ordered - cat2.as_ordered(inplace=True) + with tm.assert_produces_warning(FutureWarning, match=msg): + cat2.as_ordered(inplace=True) assert cat2.ordered assert cat2.set_ordered(True).ordered assert not cat2.set_ordered(False).ordered - cat2.set_ordered(True, inplace=True) + with tm.assert_produces_warning(FutureWarning, match=msg): + cat2.set_ordered(True, inplace=True) assert cat2.ordered - cat2.set_ordered(False, inplace=True) + with tm.assert_produces_warning(FutureWarning, match=msg): + cat2.set_ordered(False, inplace=True) assert not cat2.ordered # removed in 0.19.0 diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 940aa5ffff040..94e966642b925 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -194,7 +194,8 @@ def test_periodindex(self): def test_categories_assignments(self): cat = Categorical(["a", "b", "c", "a"]) exp = np.array([1, 2, 3, 1], dtype=np.int64) - cat.categories = [1, 2, 3] + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + cat.categories = [1, 2, 3] tm.assert_numpy_array_equal(cat.__array__(), exp) tm.assert_index_equal(cat.categories, Index([1, 2, 3])) @@ -216,8 +217,9 @@ def test_categories_assignments_wrong_length_raises(self, new_categories): "new categories need to have the same number of items " "as the old categories!" ) - with pytest.raises(ValueError, match=msg): - cat.categories = new_categories + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + with pytest.raises(ValueError, match=msg): + cat.categories = new_categories # Combinations of sorted/unique: @pytest.mark.parametrize( diff --git a/pandas/tests/series/accessors/test_cat_accessor.py b/pandas/tests/series/accessors/test_cat_accessor.py index 53158482fde46..750e84b8cde08 100644 --- a/pandas/tests/series/accessors/test_cat_accessor.py +++ b/pandas/tests/series/accessors/test_cat_accessor.py @@ -110,7 +110,8 @@ def test_categorical_delegations(self): ser = Series(Categorical(["a", "b", "c", "a"], ordered=True)) exp_categories = Index(["a", "b", "c"]) tm.assert_index_equal(ser.cat.categories, exp_categories) - ser.cat.categories = [1, 2, 3] + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + ser.cat.categories = [1, 2, 3] exp_categories = Index([1, 2, 3]) tm.assert_index_equal(ser.cat.categories, exp_categories) @@ -120,7 +121,8 @@ def test_categorical_delegations(self): assert ser.cat.ordered ser = ser.cat.as_unordered() assert not ser.cat.ordered - return_value = ser.cat.as_ordered(inplace=True) + with tm.assert_produces_warning(FutureWarning, match="The `inplace`"): + return_value = ser.cat.as_ordered(inplace=True) assert return_value is None assert ser.cat.ordered @@ -267,8 +269,10 @@ def test_set_categories_setitem(self): df = DataFrame({"Survived": [1, 0, 1], "Sex": [0, 1, 1]}, dtype="category") # change the dtype in-place - df["Survived"].cat.categories = ["No", "Yes"] - df["Sex"].cat.categories = ["female", "male"] + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + df["Survived"].cat.categories = ["No", "Yes"] + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + df["Sex"].cat.categories = ["female", "male"] # values should not be coerced to NaN assert list(df["Sex"]) == ["female", "male", "male"] diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index fc17f0b942d09..01fe6a529a86f 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -476,7 +476,8 @@ def test_categorical_sideeffects_free(self): cat = Categorical(["a", "b", "c", "a"]) s = Series(cat, copy=True) assert s.cat is not cat - s.cat.categories = [1, 2, 3] + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_) tm.assert_numpy_array_equal(s.__array__(), exp_s) @@ -493,7 +494,8 @@ def test_categorical_sideeffects_free(self): cat = Categorical(["a", "b", "c", "a"]) s = Series(cat) assert s.values is cat - s.cat.categories = [1, 2, 3] + with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): + s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s) tm.assert_numpy_array_equal(cat.__array__(), exp_s)
- [ ] 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 - [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. xref #37643 (not sure if this closes it since we may want to add a copy=True keyword)
https://api.github.com/repos/pandas-dev/pandas/pulls/47834
2022-07-23T23:34:41Z
2022-08-08T23:45:31Z
2022-08-08T23:45:31Z
2022-08-09T02:02:53Z
DOC: added type annotations and tests to check for multiple warning match
diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py index 1a8fe71ae3728..e9df85eae550a 100644 --- a/pandas/_testing/_warnings.py +++ b/pandas/_testing/_warnings.py @@ -17,7 +17,7 @@ @contextmanager def assert_produces_warning( - expected_warning: type[Warning] | bool | None = Warning, + expected_warning: type[Warning] | bool | tuple[type[Warning], ...] | None = Warning, filter_level: Literal[ "error", "ignore", "always", "default", "module", "once" ] = "always", @@ -26,16 +26,17 @@ def assert_produces_warning( match: str | None = None, ): """ - Context manager for running code expected to either raise a specific - warning, or not raise any warnings. Verifies that the code raises the - expected warning, and that it does not raise any other unexpected + Context manager for running code expected to either raise a specific warning, + multiple specific warnings, or not raise any warnings. Verifies that the code + raises the expected warning(s), and that it does not raise any other unexpected warnings. It is basically a wrapper around ``warnings.catch_warnings``. Parameters ---------- - expected_warning : {Warning, False, None}, default Warning + expected_warning : {Warning, False, tuple[Warning, ...], None}, default Warning The type of Exception raised. ``exception.Warning`` is the base - class for all warnings. To check that no warning is returned, + class for all warnings. To raise multiple types of exceptions, + pass them as a tuple. To check that no warning is returned, specify ``False`` or ``None``. filter_level : str or None, default "always" Specifies whether warnings are ignored, displayed, or turned @@ -157,7 +158,7 @@ def _assert_caught_expected_warning( def _assert_caught_no_extra_warnings( *, caught_warnings: Sequence[warnings.WarningMessage], - expected_warning: type[Warning] | bool | None, + expected_warning: type[Warning] | bool | tuple[type[Warning], ...] | None, ) -> None: """Assert that no extra warnings apart from the expected ones are caught.""" extra_warnings = [] @@ -195,7 +196,7 @@ def _assert_caught_no_extra_warnings( def _is_unexpected_warning( actual_warning: warnings.WarningMessage, - expected_warning: type[Warning] | bool | None, + expected_warning: type[Warning] | bool | tuple[type[Warning], ...] | None, ) -> bool: """Check if the actual warning issued is unexpected.""" if actual_warning and not expected_warning: diff --git a/pandas/tests/util/test_assert_produces_warning.py b/pandas/tests/util/test_assert_produces_warning.py index e3eb083e1a383..70a95bd7cdb48 100644 --- a/pandas/tests/util/test_assert_produces_warning.py +++ b/pandas/tests/util/test_assert_produces_warning.py @@ -179,6 +179,14 @@ def test_same_category_different_messages_last_match(): warnings.warn("Match this", category) +def test_match_multiple_warnings(): + # https://github.com/pandas-dev/pandas/issues/47829 + category = (FutureWarning, UserWarning) + with tm.assert_produces_warning(category, match=r"^Match this"): + warnings.warn("Match this", FutureWarning) + warnings.warn("Match this too", UserWarning) + + def test_right_category_wrong_match_raises(pair_different_warnings): target_category, other_category = pair_different_warnings with pytest.raises(AssertionError, match="Did not see warning.*matching"):
- [x] closes #47829 - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
https://api.github.com/repos/pandas-dev/pandas/pulls/47833
2022-07-23T21:16:32Z
2022-08-03T20:30:00Z
2022-08-03T20:30:00Z
2022-08-03T20:30:01Z
TYP: pandas/io annotations from pandas-stubs
diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 08ee5650e97a6..e3f7e9d454383 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -189,7 +189,7 @@ class AbstractMethodError(NotImplementedError): while keeping compatibility with Python 2 and Python 3. """ - def __init__(self, class_instance, methodtype="method") -> None: + def __init__(self, class_instance, methodtype: str = "method") -> None: types = {"method", "classmethod", "staticmethod", "property"} if methodtype not in types: raise ValueError( diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index a0abddc82e6c8..44152f100d390 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -359,13 +359,18 @@ def read_excel( # sheet name is str or int -> DataFrame sheet_name: str | int, header: int | Sequence[int] | None = ..., - names=..., + names: list[str] | None = ..., index_col: int | Sequence[int] | None = ..., - usecols=..., + usecols: int + | str + | Sequence[int] + | Sequence[str] + | Callable[[str], bool] + | None = ..., squeeze: bool | None = ..., dtype: DtypeArg | None = ..., engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = ..., - converters=..., + converters: dict[str, Callable] | dict[int, Callable] | None = ..., true_values: Iterable[Hashable] | None = ..., false_values: Iterable[Hashable] | None = ..., skiprows: Sequence[int] | int | Callable[[int], object] | None = ..., @@ -374,8 +379,8 @@ def read_excel( keep_default_na: bool = ..., na_filter: bool = ..., verbose: bool = ..., - parse_dates=..., - date_parser=..., + parse_dates: list | dict | bool = ..., + date_parser: Callable | None = ..., thousands: str | None = ..., decimal: str = ..., comment: str | None = ..., @@ -393,13 +398,18 @@ def read_excel( # sheet name is list or None -> dict[IntStrT, DataFrame] sheet_name: list[IntStrT] | None, header: int | Sequence[int] | None = ..., - names=..., + names: list[str] | None = ..., index_col: int | Sequence[int] | None = ..., - usecols=..., + usecols: int + | str + | Sequence[int] + | Sequence[str] + | Callable[[str], bool] + | None = ..., squeeze: bool | None = ..., dtype: DtypeArg | None = ..., engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = ..., - converters=..., + converters: dict[str, Callable] | dict[int, Callable] | None = ..., true_values: Iterable[Hashable] | None = ..., false_values: Iterable[Hashable] | None = ..., skiprows: Sequence[int] | int | Callable[[int], object] | None = ..., @@ -408,8 +418,8 @@ def read_excel( keep_default_na: bool = ..., na_filter: bool = ..., verbose: bool = ..., - parse_dates=..., - date_parser=..., + parse_dates: list | dict | bool = ..., + date_parser: Callable | None = ..., thousands: str | None = ..., decimal: str = ..., comment: str | None = ..., @@ -428,13 +438,18 @@ def read_excel( io, sheet_name: str | int | list[IntStrT] | None = 0, header: int | Sequence[int] | None = 0, - names=None, + names: list[str] | None = None, index_col: int | Sequence[int] | None = None, - usecols=None, + usecols: int + | str + | Sequence[int] + | Sequence[str] + | Callable[[str], bool] + | None = None, squeeze: bool | None = None, dtype: DtypeArg | None = None, engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = None, - converters=None, + converters: dict[str, Callable] | dict[int, Callable] | None = None, true_values: Iterable[Hashable] | None = None, false_values: Iterable[Hashable] | None = None, skiprows: Sequence[int] | int | Callable[[int], object] | None = None, @@ -443,8 +458,8 @@ def read_excel( keep_default_na: bool = True, na_filter: bool = True, verbose: bool = False, - parse_dates=False, - date_parser=None, + parse_dates: list | dict | bool = False, + date_parser: Callable | None = None, thousands: str | None = None, decimal: str = ".", comment: str | None = None, @@ -687,8 +702,8 @@ def parse( nrows: int | None = None, na_values=None, verbose: bool = False, - parse_dates=False, - date_parser=None, + parse_dates: list | dict | bool = False, + date_parser: Callable | None = None, thousands: str | None = None, decimal: str = ".", comment: str | None = None, @@ -1665,8 +1680,8 @@ def parse( skiprows: Sequence[int] | int | Callable[[int], object] | None = None, nrows: int | None = None, na_values=None, - parse_dates=False, - date_parser=None, + parse_dates: list | dict | bool = False, + date_parser: Callable | None = None, thousands: str | None = None, comment: str | None = None, skipfooter: int = 0, diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 811b079c3c693..3f9f6c7a5fee7 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -853,9 +853,9 @@ def get_formatted_cells(self) -> Iterable[ExcelCell]: def write( self, writer, - sheet_name="Sheet1", - startrow=0, - startcol=0, + sheet_name: str = "Sheet1", + startrow: int = 0, + startcol: int = 0, freeze_panes=None, engine=None, storage_options: StorageOptions = None, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6554b4c1f1afd..57bc534bd67c4 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -20,6 +20,7 @@ TYPE_CHECKING, Any, Callable, + Final, Hashable, Iterable, Iterator, @@ -117,7 +118,7 @@ ) -common_docstring = """ +common_docstring: Final = """ Parameters ---------- buf : str, Path or StringIO-like, optional, default None @@ -190,7 +191,7 @@ "unset", ) -return_docstring = """ +return_docstring: Final = """ Returns ------- str or None diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py index 163e7dc7bde5e..e161c8ad16ab1 100644 --- a/pandas/io/formats/html.py +++ b/pandas/io/formats/html.py @@ -6,6 +6,7 @@ from textwrap import dedent from typing import ( Any, + Final, Hashable, Iterable, Mapping, @@ -39,7 +40,7 @@ class HTMLFormatter: and this class responsible for only producing html markup. """ - indent_delta = 2 + indent_delta: Final = 2 def __init__( self, diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index fbee64771cd9a..a557f9b5c0a0d 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -3332,7 +3332,7 @@ def highlight_null( color: str | None = None, subset: Subset | None = None, props: str | None = None, - null_color=lib.no_default, + null_color: str | lib.NoDefault = lib.no_default, ) -> Styler: """ Highlight missing values with a style. diff --git a/pandas/io/html.py b/pandas/io/html.py index ad92bb2447329..ad92883fe8572 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -10,6 +10,7 @@ import numbers import re from typing import ( + Iterable, Pattern, Sequence, cast, @@ -971,7 +972,7 @@ def read_html( encoding: str | None = None, decimal: str = ".", converters: dict | None = None, - na_values=None, + na_values: Iterable[object] | None = None, keep_default_na: bool = True, displayed_only: bool = True, ) -> list[DataFrame]: diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index c617828c91bd4..d40b0357049a1 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -365,16 +365,16 @@ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]: def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], *, - orient=..., + orient: str | None = ..., typ: Literal["frame"] = ..., dtype: DtypeArg | None = ..., convert_axes=..., - convert_dates=..., + convert_dates: bool | list[str] = ..., keep_default_dates: bool = ..., numpy: bool = ..., precise_float: bool = ..., - date_unit=..., - encoding=..., + date_unit: str | None = ..., + encoding: str | None = ..., encoding_errors: str | None = ..., lines: bool = ..., chunksize: int, @@ -389,16 +389,16 @@ def read_json( def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], *, - orient=..., + orient: str | None = ..., typ: Literal["series"], dtype: DtypeArg | None = ..., convert_axes=..., - convert_dates=..., + convert_dates: bool | list[str] = ..., keep_default_dates: bool = ..., numpy: bool = ..., precise_float: bool = ..., - date_unit=..., - encoding=..., + date_unit: str | None = ..., + encoding: str | None = ..., encoding_errors: str | None = ..., lines: bool = ..., chunksize: int, @@ -413,16 +413,16 @@ def read_json( def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], *, - orient=..., + orient: str | None = ..., typ: Literal["series"], dtype: DtypeArg | None = ..., convert_axes=..., - convert_dates=..., + convert_dates: bool | list[str] = ..., keep_default_dates: bool = ..., numpy: bool = ..., precise_float: bool = ..., - date_unit=..., - encoding=..., + date_unit: str | None = ..., + encoding: str | None = ..., encoding_errors: str | None = ..., lines: bool = ..., chunksize: None = ..., @@ -436,16 +436,16 @@ def read_json( @overload def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], - orient=..., + orient: str | None = ..., typ: Literal["frame"] = ..., dtype: DtypeArg | None = ..., convert_axes=..., - convert_dates=..., + convert_dates: bool | list[str] = ..., keep_default_dates: bool = ..., numpy: bool = ..., precise_float: bool = ..., - date_unit=..., - encoding=..., + date_unit: str | None = ..., + encoding: str | None = ..., encoding_errors: str | None = ..., lines: bool = ..., chunksize: None = ..., @@ -464,16 +464,16 @@ def read_json( @deprecate_nonkeyword_arguments(version="2.0", allowed_args=["path_or_buf"]) def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], - orient=None, + orient: str | None = None, typ: Literal["frame", "series"] = "frame", dtype: DtypeArg | None = None, convert_axes=None, - convert_dates=True, + convert_dates: bool | list[str] = True, keep_default_dates: bool = True, numpy: bool = False, precise_float: bool = False, - date_unit=None, - encoding=None, + date_unit: str | None = None, + encoding: str | None = None, encoding_errors: str | None = "strict", lines: bool = False, chunksize: int | None = None, @@ -1009,11 +1009,11 @@ def __init__( json, orient, dtype: DtypeArg | None = None, - convert_axes=True, - convert_dates=True, - keep_default_dates=False, - numpy=False, - precise_float=False, + convert_axes: bool = True, + convert_dates: bool | list[str] = True, + keep_default_dates: bool = False, + numpy: bool = False, + precise_float: bool = False, date_unit=None, ) -> None: self.json = json @@ -1093,7 +1093,11 @@ def _try_convert_types(self): raise AbstractMethodError(self) def _try_convert_data( - self, name, data, use_dtypes: bool = True, convert_dates: bool = True + self, + name, + data, + use_dtypes: bool = True, + convert_dates: bool | list[str] = True, ): """ Try to parse a ndarray like into a column by inferring dtype. @@ -1375,10 +1379,10 @@ def _try_convert_dates(self): return # our columns to parse - convert_dates = self.convert_dates - if convert_dates is True: - convert_dates = [] - convert_dates = set(convert_dates) + convert_dates_list_bool = self.convert_dates + if isinstance(convert_dates_list_bool, bool): + convert_dates_list_bool = [] + convert_dates = set(convert_dates_list_bool) def is_ok(col) -> bool: """ diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index ed0e0a99ec43b..378b158d1b0bb 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -444,9 +444,9 @@ def to_parquet( @doc(storage_options=_shared_docs["storage_options"]) def read_parquet( - path, + path: FilePath | ReadBuffer[bytes], engine: str = "auto", - columns=None, + columns: list[str] | None = None, storage_options: StorageOptions = None, use_nullable_dtypes: bool = False, **kwargs, diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 52a2883e70f93..5c773a424a1c9 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -18,6 +18,7 @@ TYPE_CHECKING, Any, Callable, + Final, Hashable, Iterator, Literal, @@ -43,6 +44,7 @@ AnyArrayLike, ArrayLike, DtypeArg, + FilePath, Shape, npt, ) @@ -175,18 +177,18 @@ def _ensure_term(where, scope_level: int): return where if where is None or len(where) else None -incompatibility_doc = """ +incompatibility_doc: Final = """ where criteria is being ignored as this version [%s] is too old (or not-defined), read the file in and write it out to a new file to upgrade (with the copy_to method) """ -attribute_conflict_doc = """ +attribute_conflict_doc: Final = """ the [%s] attribute of the existing index is [%s] which conflicts with the new [%s], resetting the attribute to None """ -performance_doc = """ +performance_doc: Final = """ your performance may suffer as PyTables will pickle object types that it cannot map directly to c-types [inferred_type->%s,key->%s] [items->%s] """ @@ -198,11 +200,11 @@ def _ensure_term(where, scope_level: int): _AXES_MAP = {DataFrame: [0]} # register our configuration options -dropna_doc = """ +dropna_doc: Final = """ : boolean drop ALL nan rows when appending to a table """ -format_doc = """ +format_doc: Final = """ : format default format writing format, if None, then put will default to 'fixed' and append will default to 'table' @@ -245,7 +247,7 @@ def _tables(): def to_hdf( - path_or_buf, + path_or_buf: FilePath | HDFStore, key: str, value: DataFrame | Series, mode: str = "a", @@ -301,15 +303,15 @@ def to_hdf( def read_hdf( - path_or_buf, + path_or_buf: FilePath | HDFStore, key=None, mode: str = "r", errors: str = "strict", - where=None, + where: str | list | None = None, start: int | None = None, stop: int | None = None, - columns=None, - iterator=False, + columns: list[str] | None = None, + iterator: bool = False, chunksize: int | None = None, **kwargs, ): @@ -669,7 +671,7 @@ def keys(self, include: str = "pandas") -> list[str]: def __iter__(self) -> Iterator[str]: return iter(self.keys()) - def items(self): + def items(self) -> Iterator[tuple[str, list]]: """ iterate on key->group """ @@ -1415,7 +1417,7 @@ def create_table_index( raise TypeError("cannot create table index on a Fixed format store") s.create_index(columns=columns, optlevel=optlevel, kind=kind) - def groups(self): + def groups(self) -> list: """ Return a list of all the top-level nodes. @@ -1443,7 +1445,7 @@ def groups(self): ) ] - def walk(self, where="/"): + def walk(self, where: str = "/") -> Iterator[tuple[str, list[str], list[str]]]: """ Walk the pytables group hierarchy for pandas objects. @@ -1959,8 +1961,8 @@ class IndexCol: """ - is_an_indexable = True - is_data_indexable = True + is_an_indexable: bool = True + is_data_indexable: bool = True _info_fields = ["freq", "tz", "index_name"] name: str @@ -2612,7 +2614,7 @@ class Fixed: parent: HDFStore group: Node errors: str - is_table = False + is_table: bool = False def __init__( self, @@ -2863,7 +2865,8 @@ def get_attrs(self) -> None: for n in self.attributes: setattr(self, n, _ensure_decoded(getattr(self.attrs, n, None))) - def write(self, obj, **kwargs): + # error: Signature of "write" incompatible with supertype "Fixed" + def write(self, obj, **kwargs) -> None: # type: ignore[override] self.set_attrs() def read_array(self, key: str, start: int | None = None, stop: int | None = None): @@ -3148,7 +3151,8 @@ def read( values = self.read_array("values", start=start, stop=stop) return Series(values, index=index, name=self.name) - def write(self, obj, **kwargs): + # error: Signature of "write" incompatible with supertype "Fixed" + def write(self, obj, **kwargs) -> None: # type: ignore[override] super().write(obj, **kwargs) self.write_index("index", obj.index) self.write_array("values", obj) @@ -3224,7 +3228,8 @@ def read( return DataFrame(columns=axes[0], index=axes[1]) - def write(self, obj, **kwargs): + # error: Signature of "write" incompatible with supertype "Fixed" + def write(self, obj, **kwargs) -> None: # type: ignore[override] super().write(obj, **kwargs) # TODO(ArrayManager) HDFStore relies on accessing the blocks @@ -4272,7 +4277,7 @@ def read( """ raise NotImplementedError("WORMTable needs to implement read") - def write(self, **kwargs): + def write(self, **kwargs) -> None: """ write in a format that we can search later on (but cannot append to): write out the indices and the values using _write_array @@ -4286,22 +4291,23 @@ class AppendableTable(Table): table_type = "appendable" - def write( + # error: Signature of "write" incompatible with supertype "Fixed" + def write( # type: ignore[override] self, obj, axes=None, - append=False, + append: bool = False, complib=None, complevel=None, fletcher32=None, min_itemsize=None, chunksize=None, expectedrows=None, - dropna=False, + dropna: bool = False, nan_rep=None, data_columns=None, track_times=True, - ): + ) -> None: if not append and self.is_exists: self._handle.remove_node(self.group, "table") diff --git a/pandas/io/sas/sas_constants.py b/pandas/io/sas/sas_constants.py index 366e6924a1e16..69bc16e6d294f 100644 --- a/pandas/io/sas/sas_constants.py +++ b/pandas/io/sas/sas_constants.py @@ -1,112 +1,114 @@ from __future__ import annotations -magic = ( +from typing import Final + +magic: Final = ( b"\x00\x00\x00\x00\x00\x00\x00\x00" + b"\x00\x00\x00\x00\xc2\xea\x81\x60" + b"\xb3\x14\x11\xcf\xbd\x92\x08\x00" + b"\x09\xc7\x31\x8c\x18\x1f\x10\x11" ) -align_1_checker_value = b"3" -align_1_offset = 32 -align_1_length = 1 -align_1_value = 4 -u64_byte_checker_value = b"3" -align_2_offset = 35 -align_2_length = 1 -align_2_value = 4 -endianness_offset = 37 -endianness_length = 1 -platform_offset = 39 -platform_length = 1 -encoding_offset = 70 -encoding_length = 1 -dataset_offset = 92 -dataset_length = 64 -file_type_offset = 156 -file_type_length = 8 -date_created_offset = 164 -date_created_length = 8 -date_modified_offset = 172 -date_modified_length = 8 -header_size_offset = 196 -header_size_length = 4 -page_size_offset = 200 -page_size_length = 4 -page_count_offset = 204 -page_count_length = 4 -sas_release_offset = 216 -sas_release_length = 8 -sas_server_type_offset = 224 -sas_server_type_length = 16 -os_version_number_offset = 240 -os_version_number_length = 16 -os_maker_offset = 256 -os_maker_length = 16 -os_name_offset = 272 -os_name_length = 16 -page_bit_offset_x86 = 16 -page_bit_offset_x64 = 32 -subheader_pointer_length_x86 = 12 -subheader_pointer_length_x64 = 24 -page_type_offset = 0 -page_type_length = 2 -block_count_offset = 2 -block_count_length = 2 -subheader_count_offset = 4 -subheader_count_length = 2 -page_type_mask = 0x0F00 +align_1_checker_value: Final = b"3" +align_1_offset: Final = 32 +align_1_length: Final = 1 +align_1_value: Final = 4 +u64_byte_checker_value: Final = b"3" +align_2_offset: Final = 35 +align_2_length: Final = 1 +align_2_value: Final = 4 +endianness_offset: Final = 37 +endianness_length: Final = 1 +platform_offset: Final = 39 +platform_length: Final = 1 +encoding_offset: Final = 70 +encoding_length: Final = 1 +dataset_offset: Final = 92 +dataset_length: Final = 64 +file_type_offset: Final = 156 +file_type_length: Final = 8 +date_created_offset: Final = 164 +date_created_length: Final = 8 +date_modified_offset: Final = 172 +date_modified_length: Final = 8 +header_size_offset: Final = 196 +header_size_length: Final = 4 +page_size_offset: Final = 200 +page_size_length: Final = 4 +page_count_offset: Final = 204 +page_count_length: Final = 4 +sas_release_offset: Final = 216 +sas_release_length: Final = 8 +sas_server_type_offset: Final = 224 +sas_server_type_length: Final = 16 +os_version_number_offset: Final = 240 +os_version_number_length: Final = 16 +os_maker_offset: Final = 256 +os_maker_length: Final = 16 +os_name_offset: Final = 272 +os_name_length: Final = 16 +page_bit_offset_x86: Final = 16 +page_bit_offset_x64: Final = 32 +subheader_pointer_length_x86: Final = 12 +subheader_pointer_length_x64: Final = 24 +page_type_offset: Final = 0 +page_type_length: Final = 2 +block_count_offset: Final = 2 +block_count_length: Final = 2 +subheader_count_offset: Final = 4 +subheader_count_length: Final = 2 +page_type_mask: Final = 0x0F00 # Keep "page_comp_type" bits -page_type_mask2 = 0xF000 | page_type_mask -page_meta_type = 0x0000 -page_data_type = 0x0100 -page_mix_type = 0x0200 -page_amd_type = 0x0400 -page_meta2_type = 0x4000 -page_comp_type = 0x9000 -page_meta_types = [page_meta_type, page_meta2_type] -subheader_pointers_offset = 8 -truncated_subheader_id = 1 -compressed_subheader_id = 4 -compressed_subheader_type = 1 -text_block_size_length = 2 -row_length_offset_multiplier = 5 -row_count_offset_multiplier = 6 -col_count_p1_multiplier = 9 -col_count_p2_multiplier = 10 -row_count_on_mix_page_offset_multiplier = 15 -column_name_pointer_length = 8 -column_name_text_subheader_offset = 0 -column_name_text_subheader_length = 2 -column_name_offset_offset = 2 -column_name_offset_length = 2 -column_name_length_offset = 4 -column_name_length_length = 2 -column_data_offset_offset = 8 -column_data_length_offset = 8 -column_data_length_length = 4 -column_type_offset = 14 -column_type_length = 1 -column_format_text_subheader_index_offset = 22 -column_format_text_subheader_index_length = 2 -column_format_offset_offset = 24 -column_format_offset_length = 2 -column_format_length_offset = 26 -column_format_length_length = 2 -column_label_text_subheader_index_offset = 28 -column_label_text_subheader_index_length = 2 -column_label_offset_offset = 30 -column_label_offset_length = 2 -column_label_length_offset = 32 -column_label_length_length = 2 -rle_compression = b"SASYZCRL" -rdc_compression = b"SASYZCR2" +page_type_mask2: Final = 0xF000 | page_type_mask +page_meta_type: Final = 0x0000 +page_data_type: Final = 0x0100 +page_mix_type: Final = 0x0200 +page_amd_type: Final = 0x0400 +page_meta2_type: Final = 0x4000 +page_comp_type: Final = 0x9000 +page_meta_types: Final = [page_meta_type, page_meta2_type] +subheader_pointers_offset: Final = 8 +truncated_subheader_id: Final = 1 +compressed_subheader_id: Final = 4 +compressed_subheader_type: Final = 1 +text_block_size_length: Final = 2 +row_length_offset_multiplier: Final = 5 +row_count_offset_multiplier: Final = 6 +col_count_p1_multiplier: Final = 9 +col_count_p2_multiplier: Final = 10 +row_count_on_mix_page_offset_multiplier: Final = 15 +column_name_pointer_length: Final = 8 +column_name_text_subheader_offset: Final = 0 +column_name_text_subheader_length: Final = 2 +column_name_offset_offset: Final = 2 +column_name_offset_length: Final = 2 +column_name_length_offset: Final = 4 +column_name_length_length: Final = 2 +column_data_offset_offset: Final = 8 +column_data_length_offset: Final = 8 +column_data_length_length: Final = 4 +column_type_offset: Final = 14 +column_type_length: Final = 1 +column_format_text_subheader_index_offset: Final = 22 +column_format_text_subheader_index_length: Final = 2 +column_format_offset_offset: Final = 24 +column_format_offset_length: Final = 2 +column_format_length_offset: Final = 26 +column_format_length_length: Final = 2 +column_label_text_subheader_index_offset: Final = 28 +column_label_text_subheader_index_length: Final = 2 +column_label_offset_offset: Final = 30 +column_label_offset_length: Final = 2 +column_label_length_offset: Final = 32 +column_label_length_length: Final = 2 +rle_compression: Final = b"SASYZCRL" +rdc_compression: Final = b"SASYZCR2" -compression_literals = [rle_compression, rdc_compression] +compression_literals: Final = [rle_compression, rdc_compression] # Incomplete list of encodings, using SAS nomenclature: # http://support.sas.com/documentation/cdl/en/nlsref/61893/HTML/default/viewer.htm#a002607278.htm -encoding_names = { +encoding_names: Final = { 29: "latin1", 20: "utf-8", 33: "cyrillic", @@ -118,18 +120,18 @@ class SASIndex: - row_size_index = 0 - column_size_index = 1 - subheader_counts_index = 2 - column_text_index = 3 - column_name_index = 4 - column_attributes_index = 5 - format_and_label_index = 6 - column_list_index = 7 - data_subheader_index = 8 + row_size_index: Final = 0 + column_size_index: Final = 1 + subheader_counts_index: Final = 2 + column_text_index: Final = 3 + column_name_index: Final = 4 + column_attributes_index: Final = 5 + format_and_label_index: Final = 6 + column_list_index: Final = 7 + data_subheader_index: Final = 8 -subheader_signature_to_index = { +subheader_signature_to_index: Final = { b"\xF7\xF7\xF7\xF7": SASIndex.row_size_index, b"\x00\x00\x00\x00\xF7\xF7\xF7\xF7": SASIndex.row_size_index, b"\xF7\xF7\xF7\xF7\x00\x00\x00\x00": SASIndex.row_size_index, @@ -166,7 +168,7 @@ class SASIndex: # List of frequently used SAS date and datetime formats # http://support.sas.com/documentation/cdl/en/etsug/60372/HTML/default/viewer.htm#etsug_intervals_sect009.htm # https://github.com/epam/parso/blob/master/src/main/java/com/epam/parso/impl/SasFileConstants.java -sas_date_formats = ( +sas_date_formats: Final = ( "DATE", "DAY", "DDMMYY", @@ -235,7 +237,7 @@ class SASIndex: "MINGUO", ) -sas_datetime_formats = ( +sas_datetime_formats: Final = ( "DATETIME", "DTWKDATX", "B8601DN", diff --git a/pandas/io/sql.py b/pandas/io/sql.py index f591e7b8676f6..086a60774ac4e 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -17,7 +17,6 @@ TYPE_CHECKING, Any, Iterator, - Sequence, cast, overload, ) @@ -189,10 +188,10 @@ def read_sql_table( table_name, con, schema=..., - index_col=..., + index_col: str | list[str] | None = ..., coerce_float=..., - parse_dates=..., - columns=..., + parse_dates: list[str] | dict[str, str] | None = ..., + columns: list[str] | None = ..., chunksize: None = ..., ) -> DataFrame: ... @@ -203,10 +202,10 @@ def read_sql_table( table_name, con, schema=..., - index_col=..., + index_col: str | list[str] | None = ..., coerce_float=..., - parse_dates=..., - columns=..., + parse_dates: list[str] | dict[str, str] | None = ..., + columns: list[str] | None = ..., chunksize: int = ..., ) -> Iterator[DataFrame]: ... @@ -216,10 +215,10 @@ def read_sql_table( table_name: str, con, schema: str | None = None, - index_col: str | Sequence[str] | None = None, + index_col: str | list[str] | None = None, coerce_float: bool = True, - parse_dates=None, - columns=None, + parse_dates: list[str] | dict[str, str] | None = None, + columns: list[str] | None = None, chunksize: int | None = None, ) -> DataFrame | Iterator[DataFrame]: """ @@ -302,10 +301,10 @@ def read_sql_table( def read_sql_query( sql, con, - index_col=..., + index_col: str | list[str] | None = ..., coerce_float=..., - params=..., - parse_dates=..., + params: list[str] | dict[str, str] | None = ..., + parse_dates: list[str] | dict[str, str] | None = ..., chunksize: None = ..., dtype: DtypeArg | None = ..., ) -> DataFrame: @@ -316,10 +315,10 @@ def read_sql_query( def read_sql_query( sql, con, - index_col=..., + index_col: str | list[str] | None = ..., coerce_float=..., - params=..., - parse_dates=..., + params: list[str] | dict[str, str] | None = ..., + parse_dates: list[str] | dict[str, str] | None = ..., chunksize: int = ..., dtype: DtypeArg | None = ..., ) -> Iterator[DataFrame]: @@ -329,10 +328,10 @@ def read_sql_query( def read_sql_query( sql, con, - index_col=None, + index_col: str | list[str] | None = None, coerce_float: bool = True, - params=None, - parse_dates=None, + params: list[str] | dict[str, str] | None = None, + parse_dates: list[str] | dict[str, str] | None = None, chunksize: int | None = None, dtype: DtypeArg | None = None, ) -> DataFrame | Iterator[DataFrame]: @@ -409,11 +408,11 @@ def read_sql_query( def read_sql( sql, con, - index_col=..., + index_col: str | list[str] | None = ..., coerce_float=..., params=..., parse_dates=..., - columns=..., + columns: list[str] = ..., chunksize: None = ..., ) -> DataFrame: ... @@ -423,11 +422,11 @@ def read_sql( def read_sql( sql, con, - index_col=..., + index_col: str | list[str] | None = ..., coerce_float=..., params=..., parse_dates=..., - columns=..., + columns: list[str] = ..., chunksize: int = ..., ) -> Iterator[DataFrame]: ... @@ -436,11 +435,11 @@ def read_sql( def read_sql( sql, con, - index_col: str | Sequence[str] | None = None, + index_col: str | list[str] | None = None, coerce_float: bool = True, params=None, parse_dates=None, - columns=None, + columns: list[str] | None = None, chunksize: int | None = None, ) -> DataFrame | Iterator[DataFrame]: """ @@ -781,9 +780,9 @@ def __init__( name: str, pandas_sql_engine, frame=None, - index=True, - if_exists="fail", - prefix="pandas", + index: bool | str | list[str] | None = True, + if_exists: str = "fail", + prefix: str = "pandas", index_label=None, schema=None, keys=None, @@ -984,7 +983,7 @@ def _query_iterator( def read( self, - coerce_float=True, + coerce_float: bool = True, parse_dates=None, columns=None, chunksize=None, @@ -1267,8 +1266,8 @@ def to_sql( self, frame, name, - if_exists="fail", - index=True, + if_exists: str = "fail", + index: bool = True, index_label=None, schema=None, chunksize=None, @@ -1406,7 +1405,7 @@ def execute(self, *args, **kwargs): def read_table( self, table_name: str, - index_col: str | Sequence[str] | None = None, + index_col: str | list[str] | None = None, coerce_float: bool = True, parse_dates=None, columns=None, @@ -1501,7 +1500,7 @@ def _query_iterator( def read_query( self, sql: str, - index_col: str | Sequence[str] | None = None, + index_col: str | list[str] | None = None, coerce_float: bool = True, parse_dates=None, params=None, @@ -1660,8 +1659,8 @@ def to_sql( self, frame, name, - if_exists="fail", - index=True, + if_exists: str = "fail", + index: bool = True, index_label=None, schema=None, chunksize=None, @@ -2107,8 +2106,8 @@ def to_sql( self, frame, name, - if_exists="fail", - index=True, + if_exists: str = "fail", + index: bool = True, index_label=None, schema=None, chunksize=None, diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 226a19e1f7599..2662df0361b55 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -22,6 +22,7 @@ TYPE_CHECKING, Any, AnyStr, + Final, Hashable, Sequence, cast, @@ -214,7 +215,7 @@ _date_formats = ["%tc", "%tC", "%td", "%d", "%tw", "%tm", "%tq", "%th", "%ty"] -stata_epoch = datetime.datetime(1960, 1, 1) +stata_epoch: Final = datetime.datetime(1960, 1, 1) # TODO: Add typing. As of January 2020 it is not possible to type this function since @@ -485,7 +486,7 @@ def g(x: datetime.datetime) -> int: return Series(conv_dates, index=index) -excessive_string_length_error = """ +excessive_string_length_error: Final = """ Fixed width strings in Stata .dta files are limited to 244 (or fewer) characters. Column '{0}' does not satisfy this restriction. Use the 'version=117' parameter to write the newer (Stata 13 and later) format. @@ -496,7 +497,7 @@ class PossiblePrecisionLoss(Warning): pass -precision_loss_doc = """ +precision_loss_doc: Final = """ Column converted from {0} to {1}, and some data are outside of the lossless conversion range. This may result in a loss of precision in the saved data. """ @@ -506,7 +507,7 @@ class ValueLabelTypeMismatch(Warning): pass -value_label_mismatch_doc = """ +value_label_mismatch_doc: Final = """ Stata value labels (pandas categories) must be strings. Column {0} contains non-string labels which will be converted to strings. Please check that the Stata data file created has not lost information due to duplicate labels. @@ -517,7 +518,7 @@ class InvalidColumnName(Warning): pass -invalid_name_doc = """ +invalid_name_doc: Final = """ Not all pandas column names were valid Stata variable names. The following replacements have been made: @@ -851,15 +852,15 @@ class StataMissingValue: # Construct a dictionary of missing values MISSING_VALUES: dict[float, str] = {} - bases = (101, 32741, 2147483621) + bases: Final = (101, 32741, 2147483621) for b in bases: # Conversion to long to avoid hash issues on 32 bit platforms #8968 MISSING_VALUES[b] = "." for i in range(1, 27): MISSING_VALUES[i + b] = "." + chr(96 + i) - float32_base = b"\x00\x00\x00\x7f" - increment = struct.unpack("<i", b"\x00\x08\x00\x00")[0] + float32_base: bytes = b"\x00\x00\x00\x7f" + increment: int = struct.unpack("<i", b"\x00\x08\x00\x00")[0] for i in range(27): key = struct.unpack("<f", float32_base)[0] MISSING_VALUES[key] = "." @@ -868,7 +869,7 @@ class StataMissingValue: int_value = struct.unpack("<i", struct.pack("<f", key))[0] + increment float32_base = struct.pack("<i", int_value) - float64_base = b"\x00\x00\x00\x00\x00\x00\xe0\x7f" + float64_base: bytes = b"\x00\x00\x00\x00\x00\x00\xe0\x7f" increment = struct.unpack("q", b"\x00\x00\x00\x00\x00\x01\x00\x00")[0] for i in range(27): key = struct.unpack("<d", float64_base)[0] @@ -878,7 +879,7 @@ class StataMissingValue: int_value = struct.unpack("q", struct.pack("<d", key))[0] + increment float64_base = struct.pack("q", int_value) - BASE_MISSING_VALUES = { + BASE_MISSING_VALUES: Final = { "int8": 101, "int16": 32741, "int32": 2147483621, diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index fc3439a57a002..a4a9ebfbf4126 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -364,7 +364,7 @@ def validate_axis_style_args( return out -def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True): +def validate_fillna_kwargs(value, method, validate_scalar_dict_value: bool = True): """ Validate the keyword arguments to 'fillna'.
Copied annotations from pandas-stubs when pandas has no annotations
https://api.github.com/repos/pandas-dev/pandas/pulls/47831
2022-07-23T20:46:32Z
2022-07-25T16:43:49Z
2022-07-25T16:43:49Z
2022-09-10T01:38:57Z
TYP: pandas/plotting annotations from pandas-stubs
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 92f3b3ce83297..f8cb869e6ed89 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -93,7 +93,7 @@ repos: types: [python] stages: [manual] additional_dependencies: &pyright_dependencies - - pyright@1.1.258 + - pyright@1.1.262 - id: pyright_reportGeneralTypeIssues name: pyright reportGeneralTypeIssues entry: pyright --skipunannotated -p pyright_reportGeneralTypeIssues.json diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index b0e4d46564ba4..a882d3a955469 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -444,7 +444,7 @@ def dropna(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT: else: return type(self)(pc.drop_null(self._data)) - def isin(self: ArrowExtensionArrayT, values) -> npt.NDArray[np.bool_]: + def isin(self, values) -> npt.NDArray[np.bool_]: if pa_version_under2p0: fallback_performancewarning(version="2") return super().isin(values) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index bc39d1f619f49..0d69a52eb15f1 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -27,6 +27,8 @@ from pandas.core.base import PandasObject if TYPE_CHECKING: + from matplotlib.axes import Axes + from pandas import DataFrame @@ -463,16 +465,16 @@ def hist_frame( @Substitution(backend="") @Appender(_boxplot_doc) def boxplot( - data, - column=None, - by=None, - ax=None, - fontsize=None, - rot=0, - grid=True, - figsize=None, - layout=None, - return_type=None, + data: DataFrame, + column: str | list[str] | None = None, + by: str | list[str] | None = None, + ax: Axes | None = None, + fontsize: float | str | None = None, + rot: int = 0, + grid: bool = True, + figsize: tuple[float, float] | None = None, + layout: tuple[int, int] | None = None, + return_type: str | None = None, **kwargs, ): plot_backend = _get_plot_backend("matplotlib") @@ -499,8 +501,8 @@ def boxplot_frame( by=None, ax=None, fontsize=None, - rot=0, - grid=True, + rot: int = 0, + grid: bool = True, figsize=None, layout=None, return_type=None, @@ -525,16 +527,16 @@ def boxplot_frame( def boxplot_frame_groupby( grouped, - subplots=True, + subplots: bool = True, column=None, fontsize=None, - rot=0, - grid=True, + rot: int = 0, + grid: bool = True, ax=None, figsize=None, layout=None, - sharex=False, - sharey=True, + sharex: bool = False, + sharey: bool = True, backend=None, **kwargs, ): @@ -1041,7 +1043,7 @@ def __call__(self, *args, **kwargs): ) @Substitution(kind="line") @Appender(_bar_or_line_doc) - def line(self, x=None, y=None, **kwargs): + def line(self, x=None, y=None, **kwargs) -> PlotAccessor: """ Plot Series or DataFrame as lines. @@ -1128,7 +1130,7 @@ def line(self, x=None, y=None, **kwargs): ) @Substitution(kind="bar") @Appender(_bar_or_line_doc) - def bar(self, x=None, y=None, **kwargs): + def bar(self, x=None, y=None, **kwargs) -> PlotAccessor: """ Vertical bar plot. @@ -1214,7 +1216,7 @@ def bar(self, x=None, y=None, **kwargs): ) @Substitution(kind="bar") @Appender(_bar_or_line_doc) - def barh(self, x=None, y=None, **kwargs): + def barh(self, x=None, y=None, **kwargs) -> PlotAccessor: """ Make a horizontal bar plot. @@ -1226,7 +1228,7 @@ def barh(self, x=None, y=None, **kwargs): """ return self(kind="barh", x=x, y=y, **kwargs) - def box(self, by=None, **kwargs): + def box(self, by=None, **kwargs) -> PlotAccessor: r""" Make a box plot of the DataFrame columns. @@ -1293,7 +1295,7 @@ def box(self, by=None, **kwargs): """ return self(kind="box", by=by, **kwargs) - def hist(self, by=None, bins=10, **kwargs): + def hist(self, by=None, bins: int = 10, **kwargs) -> PlotAccessor: """ Draw one histogram of the DataFrame's columns. @@ -1355,7 +1357,7 @@ def hist(self, by=None, bins=10, **kwargs): """ return self(kind="hist", by=by, bins=bins, **kwargs) - def kde(self, bw_method=None, ind=None, **kwargs): + def kde(self, bw_method=None, ind=None, **kwargs) -> PlotAccessor: """ Generate Kernel Density Estimate plot using Gaussian kernels. @@ -1465,7 +1467,7 @@ def kde(self, bw_method=None, ind=None, **kwargs): density = kde - def area(self, x=None, y=None, **kwargs): + def area(self, x=None, y=None, **kwargs) -> PlotAccessor: """ Draw a stacked area plot. @@ -1538,7 +1540,7 @@ def area(self, x=None, y=None, **kwargs): """ return self(kind="area", x=x, y=y, **kwargs) - def pie(self, **kwargs): + def pie(self, **kwargs) -> PlotAccessor: """ Generate a pie plot. @@ -1593,7 +1595,7 @@ def pie(self, **kwargs): raise ValueError("pie requires either y column or 'subplots=True'") return self(kind="pie", **kwargs) - def scatter(self, x, y, s=None, c=None, **kwargs): + def scatter(self, x, y, s=None, c=None, **kwargs) -> PlotAccessor: """ Create a scatter plot with varying marker point size and color. @@ -1699,7 +1701,9 @@ def scatter(self, x, y, s=None, c=None, **kwargs): return self(kind="scatter", x=x, y=y, **kwargs) - def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwargs): + def hexbin( + self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwargs + ) -> PlotAccessor: """ Generate a hexagonal binning plot. diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index a49b035b1aaf1..045c27bb8fe56 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -48,7 +48,7 @@ class BP(NamedTuple): ax: Axes lines: dict[str, list[Line2D]] - def __init__(self, data, return_type="axes", **kwargs) -> None: + def __init__(self, data, return_type: str = "axes", **kwargs) -> None: # Do not call LinePlot.__init__ which may fill nan if return_type not in self._valid_return_types: raise ValueError("return_type must be {None, 'axes', 'dict', 'both'}") @@ -117,7 +117,7 @@ def _validate_color_args(self): def _get_colors(self, num_colors=None, color_kwds="color"): pass - def maybe_color_bp(self, bp): + def maybe_color_bp(self, bp) -> None: if isinstance(self.color, dict): boxes = self.color.get("boxes", self._boxes_c) whiskers = self.color.get("whiskers", self._whiskers_c) @@ -292,8 +292,8 @@ def boxplot( by=None, ax=None, fontsize=None, - rot=0, - grid=True, + rot: int = 0, + grid: bool = True, figsize=None, layout=None, return_type=None, @@ -443,8 +443,8 @@ def boxplot_frame( by=None, ax=None, fontsize=None, - rot=0, - grid=True, + rot: int = 0, + grid: bool = True, figsize=None, layout=None, return_type=None, @@ -471,16 +471,16 @@ def boxplot_frame( def boxplot_frame_groupby( grouped, - subplots=True, + subplots: bool = True, column=None, fontsize=None, - rot=0, - grid=True, + rot: int = 0, + grid: bool = True, ax=None, figsize=None, layout=None, - sharex=False, - sharey=True, + sharex: bool = False, + sharey: bool = True, **kwds, ): if subplots is True: diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 873084393371c..8510a7acac117 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -10,6 +10,8 @@ import functools from typing import ( Any, + Final, + Iterator, cast, ) @@ -56,14 +58,14 @@ import pandas.core.tools.datetimes as tools # constants -HOURS_PER_DAY = 24.0 -MIN_PER_HOUR = 60.0 -SEC_PER_MIN = 60.0 +HOURS_PER_DAY: Final = 24.0 +MIN_PER_HOUR: Final = 60.0 +SEC_PER_MIN: Final = 60.0 -SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR -SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY +SEC_PER_HOUR: Final = SEC_PER_MIN * MIN_PER_HOUR +SEC_PER_DAY: Final = SEC_PER_HOUR * HOURS_PER_DAY -MUSEC_PER_DAY = 10**6 * SEC_PER_DAY +MUSEC_PER_DAY: Final = 10**6 * SEC_PER_DAY _mpl_units = {} # Cache for units overwritten by us @@ -94,7 +96,7 @@ def wrapper(*args, **kwargs): @contextlib.contextmanager -def pandas_converters(): +def pandas_converters() -> Iterator[None]: """ Context manager registering pandas' converters for a plot. @@ -115,7 +117,7 @@ def pandas_converters(): deregister() -def register(): +def register() -> None: pairs = get_pairs() for type_, cls in pairs: # Cache previous converter if present @@ -126,7 +128,7 @@ def register(): units.registry[type_] = cls() -def deregister(): +def deregister() -> None: # Renamed in pandas.plotting.__init__ for type_, cls in get_pairs(): # We use type to catch our classes directly, no inheritance @@ -187,7 +189,7 @@ class TimeFormatter(Formatter): def __init__(self, locs) -> None: self.locs = locs - def __call__(self, x, pos=0) -> str: + def __call__(self, x, pos: int = 0) -> str: """ Return the time of day as a formatted string. @@ -339,7 +341,7 @@ def axisinfo(unit: tzinfo | None, axis) -> units.AxisInfo: class PandasAutoDateFormatter(dates.AutoDateFormatter): - def __init__(self, locator, tz=None, defaultfmt="%Y-%m-%d") -> None: + def __init__(self, locator, tz=None, defaultfmt: str = "%Y-%m-%d") -> None: dates.AutoDateFormatter.__init__(self, locator, tz, defaultfmt) @@ -937,12 +939,12 @@ class TimeSeries_DateLocator(Locator): def __init__( self, freq: BaseOffset, - minor_locator=False, - dynamic_mode=True, - base=1, - quarter=1, - month=1, - day=1, + minor_locator: bool = False, + dynamic_mode: bool = True, + base: int = 1, + quarter: int = 1, + month: int = 1, + day: int = 1, plot_obj=None, ) -> None: freq = to_offset(freq) @@ -1053,7 +1055,7 @@ def _set_default_format(self, vmin, vmax): self.formatdict = {x: f for (x, _, _, f) in format} return self.formatdict - def set_locs(self, locs): + def set_locs(self, locs) -> None: """Sets the locations of the ticks""" # don't actually use the locs. This is just needed to work with # matplotlib. Force to use vmin, vmax @@ -1068,7 +1070,7 @@ def set_locs(self, locs): (vmin, vmax) = (vmax, vmin) self._set_default_format(vmin, vmax) - def __call__(self, x, pos=0) -> str: + def __call__(self, x, pos: int = 0) -> str: if self.formatdict is None: return "" @@ -1103,7 +1105,7 @@ def format_timedelta_ticks(x, pos, n_decimals: int) -> str: s = f"{int(d):d} days {s}" return s - def __call__(self, x, pos=0) -> str: + def __call__(self, x, pos: int = 0) -> str: (vmin, vmax) = tuple(self.axis.get_view_interval()) n_decimals = int(np.ceil(np.log10(100 * 10**9 / abs(vmax - vmin)))) if n_decimals > 9: diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 301474edc6a8e..ee7493813f13a 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -118,11 +118,11 @@ def __init__( by: IndexLabel | None = None, subplots: bool | Sequence[Sequence[str]] = False, sharex=None, - sharey=False, - use_index=True, + sharey: bool = False, + use_index: bool = True, figsize=None, grid=None, - legend=True, + legend: bool | str = True, rot=None, ax=None, fig=None, @@ -133,13 +133,13 @@ def __init__( yticks=None, xlabel: Hashable | None = None, ylabel: Hashable | None = None, - sort_columns=False, + sort_columns: bool = False, fontsize=None, - secondary_y=False, + secondary_y: bool | tuple | list | np.ndarray = False, colormap=None, - table=False, + table: bool = False, layout=None, - include_bool=False, + include_bool: bool = False, column: IndexLabel | None = None, **kwds, ) -> None: @@ -437,10 +437,10 @@ def nseries(self) -> int: else: return self.data.shape[1] - def draw(self): + def draw(self) -> None: self.plt.draw_if_interactive() - def generate(self): + def generate(self) -> None: self._args_adjust() self._compute_plot_data() self._setup_subplots() @@ -547,8 +547,11 @@ def result(self): return self.axes else: sec_true = isinstance(self.secondary_y, bool) and self.secondary_y + # error: Argument 1 to "len" has incompatible type "Union[bool, + # Tuple[Any, ...], List[Any], ndarray[Any, Any]]"; expected "Sized" all_sec = ( - is_list_like(self.secondary_y) and len(self.secondary_y) == self.nseries + is_list_like(self.secondary_y) + and len(self.secondary_y) == self.nseries # type: ignore[arg-type] ) if sec_true or all_sec: # if all data is plotted on secondary, return right axes @@ -937,7 +940,7 @@ def _get_ax(self, i: int): return ax @classmethod - def get_default_ax(cls, ax): + def get_default_ax(cls, ax) -> None: import matplotlib.pyplot as plt if ax is None and len(plt.get_fignums()) > 0: diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index 77496cf049f3d..3b151d67c70be 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -49,7 +49,13 @@ class HistPlot(LinePlot): def _kind(self) -> Literal["hist", "kde"]: return "hist" - def __init__(self, data, bins=10, bottom=0, **kwargs) -> None: + def __init__( + self, + data, + bins: int | np.ndarray | list[np.ndarray] = 10, + bottom: int | np.ndarray = 0, + **kwargs, + ) -> None: self.bins = bins # use mpl default self.bottom = bottom # Do not call LinePlot.__init__ which may fill nan @@ -369,13 +375,13 @@ def hist_series( self, by=None, ax=None, - grid=True, + grid: bool = True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, - bins=10, + bins: int = 10, legend: bool = False, **kwds, ): @@ -441,17 +447,17 @@ def hist_frame( data, column=None, by=None, - grid=True, + grid: bool = True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, - sharex=False, - sharey=False, + sharex: bool = False, + sharey: bool = False, figsize=None, layout=None, - bins=10, + bins: int = 10, legend: bool = False, **kwds, ): diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 083d85ef0876d..e2a0d50544f22 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -34,15 +34,15 @@ def scatter_matrix( frame: DataFrame, - alpha=0.5, + alpha: float = 0.5, figsize=None, ax=None, - grid=False, - diagonal="hist", - marker=".", + grid: bool = False, + diagonal: str = "hist", + marker: str = ".", density_kwds=None, hist_kwds=None, - range_padding=0.05, + range_padding: float = 0.05, **kwds, ): df = frame._get_numeric_data() @@ -352,7 +352,7 @@ def parallel_coordinates( cols=None, ax: Axes | None = None, color=None, - use_columns=False, + use_columns: bool = False, xticks=None, colormap=None, axvlines: bool = True, diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index ca6cccb0f98eb..06aac478bfb11 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -291,7 +291,7 @@ def _format_coord(freq, t, y) -> str: return f"t = {time_period} y = {y:8f}" -def format_dateaxis(subplot, freq, index): +def format_dateaxis(subplot, freq, index) -> None: """ Pretty-formats the date axis (x-axis). diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 94357e5002ffd..a8b1e4c572c43 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -50,7 +50,7 @@ def maybe_adjust_figure(fig: Figure, *args, **kwargs): fig.subplots_adjust(*args, **kwargs) -def format_date_labels(ax: Axes, rot): +def format_date_labels(ax: Axes, rot) -> None: # mini version of autofmt_xdate for label in ax.get_xticklabels(): label.set_ha("right") diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 0e82a0fc924fb..17763b25329ab 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -13,6 +13,11 @@ from matplotlib.figure import Figure import numpy as np + from pandas import ( + DataFrame, + Series, + ) + def table(ax, data, rowLabels=None, colLabels=None, **kwargs): """ @@ -81,16 +86,16 @@ def deregister() -> None: def scatter_matrix( - frame, - alpha=0.5, - figsize=None, - ax=None, - grid=False, - diagonal="hist", - marker=".", + frame: DataFrame, + alpha: float = 0.5, + figsize: tuple[float, float] | None = None, + ax: Axes | None = None, + grid: bool = False, + diagonal: str = "hist", + marker: str = ".", density_kwds=None, hist_kwds=None, - range_padding=0.05, + range_padding: float = 0.05, **kwargs, ) -> np.ndarray: """ @@ -167,7 +172,14 @@ def scatter_matrix( ) -def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds) -> Axes: +def radviz( + frame: DataFrame, + class_column: str, + ax: Axes | None = None, + color: list[str] | tuple[str, ...] | None = None, + colormap=None, + **kwds, +) -> Axes: """ Plot a multidimensional dataset in 2D. @@ -249,7 +261,13 @@ def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds) -> A def andrews_curves( - frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs + frame: DataFrame, + class_column: str, + ax: Axes | None = None, + samples: int = 200, + color: list[str] | tuple[str, ...] | None = None, + colormap=None, + **kwargs, ) -> Axes: """ Generate a matplotlib plot of Andrews curves, for visualising clusters of @@ -308,7 +326,13 @@ def andrews_curves( ) -def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds) -> Figure: +def bootstrap_plot( + series: Series, + fig: Figure | None = None, + size: int = 50, + samples: int = 500, + **kwds, +) -> Figure: """ Bootstrap plot on mean, median and mid-range statistics. @@ -363,17 +387,17 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds) -> Figure: def parallel_coordinates( - frame, - class_column, - cols=None, - ax=None, - color=None, - use_columns=False, - xticks=None, + frame: DataFrame, + class_column: str, + cols: list[str] | None = None, + ax: Axes | None = None, + color: list[str] | tuple[str, ...] | None = None, + use_columns: bool = False, + xticks: list | tuple | None = None, colormap=None, - axvlines=True, + axvlines: bool = True, axvlines_kwds=None, - sort_labels=False, + sort_labels: bool = False, **kwargs, ) -> Axes: """ @@ -441,7 +465,7 @@ def parallel_coordinates( ) -def lag_plot(series, lag=1, ax=None, **kwds) -> Axes: +def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Axes: """ Lag plot for time series. @@ -485,7 +509,7 @@ def lag_plot(series, lag=1, ax=None, **kwds) -> Axes: return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds) -def autocorrelation_plot(series, ax=None, **kwargs) -> Axes: +def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Axes: """ Autocorrelation plot for time series. @@ -532,7 +556,7 @@ class _Options(dict): _ALIASES = {"x_compat": "xaxis.compat"} _DEFAULT_KEYS = ["xaxis.compat"] - def __init__(self, deprecated=False) -> None: + def __init__(self, deprecated: bool = False) -> None: self._deprecated = deprecated super().__setitem__("xaxis.compat", False)
Copied annotations from pandas-stubs when pandas has no annotations
https://api.github.com/repos/pandas-dev/pandas/pulls/47827
2022-07-23T01:16:08Z
2022-07-25T16:45:09Z
2022-07-25T16:45:09Z
2022-09-10T01:38:55Z
REF: de-duplicate PeriodArray arithmetic code
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 2d676f94c6a64..12352c4490f29 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -14,7 +14,10 @@ import numpy as np -from pandas._libs import algos as libalgos +from pandas._libs import ( + algos as libalgos, + lib, +) from pandas._libs.arrays import NDArrayBacked from pandas._libs.tslibs import ( BaseOffset, @@ -22,7 +25,6 @@ NaTType, Timedelta, astype_overflowsafe, - delta_to_nanoseconds, dt64arr_to_periodarr as c_dt64arr_to_periodarr, get_unit_from_dtype, iNaT, @@ -55,7 +57,6 @@ ) from pandas.core.dtypes.common import ( - TD64NS_DTYPE, ensure_object, is_datetime64_any_dtype, is_datetime64_dtype, @@ -72,7 +73,7 @@ ABCSeries, ABCTimedeltaArray, ) -from pandas.core.dtypes.missing import notna +from pandas.core.dtypes.missing import isna import pandas.core.algorithms as algos from pandas.core.arrays import datetimelike as dtl @@ -764,22 +765,16 @@ def _add_timedeltalike_scalar(self, other): # We cannot add timedelta-like to non-tick PeriodArray raise raise_on_incompatible(self, other) - if notna(other): - # Convert to an integer increment of our own freq, disallowing - # e.g. 30seconds if our freq is minutes. - try: - inc = delta_to_nanoseconds(other, reso=self.freq._reso, round_ok=False) - except ValueError as err: - # "Cannot losslessly convert units" - raise raise_on_incompatible(self, other) from err - - return self._addsub_int_array_or_scalar(inc, operator.add) + if isna(other): + # i.e. np.timedelta64("NaT") + return super()._add_timedeltalike_scalar(other) - return super()._add_timedeltalike_scalar(other) + td = np.asarray(Timedelta(other).asm8) + return self._add_timedelta_arraylike(td) def _add_timedelta_arraylike( self, other: TimedeltaArray | npt.NDArray[np.timedelta64] - ): + ) -> PeriodArray: """ Parameters ---------- @@ -787,7 +782,7 @@ def _add_timedelta_arraylike( Returns ------- - result : ndarray[int64] + PeriodArray """ freq = self.freq if not isinstance(freq, Tick): @@ -803,8 +798,12 @@ def _add_timedelta_arraylike( np.asarray(other), dtype=dtype, copy=False, round_ok=False ) except ValueError as err: - # TODO: not actually a great exception message in this case - raise raise_on_incompatible(self, other) from err + # e.g. if we have minutes freq and try to add 30s + # "Cannot losslessly convert units" + raise IncompatibleFrequency( + "Cannot add/subtract timedelta-like from PeriodArray that is " + "not an integer multiple of the PeriodArray's freq." + ) from err b_mask = np.isnat(delta) @@ -835,31 +834,21 @@ def _check_timedeltalike_freq_compat(self, other): IncompatibleFrequency """ assert isinstance(self.freq, Tick) # checked by calling function - base_nanos = self.freq.base.nanos + + dtype = np.dtype(f"m8[{self.freq._td64_unit}]") if isinstance(other, (timedelta, np.timedelta64, Tick)): - nanos = delta_to_nanoseconds(other) - - elif isinstance(other, np.ndarray): - # numpy timedelta64 array; all entries must be compatible - assert other.dtype.kind == "m" - other = astype_overflowsafe(other, TD64NS_DTYPE, copy=False) - # error: Incompatible types in assignment (expression has type - # "ndarray[Any, dtype[Any]]", variable has type "int") - nanos = other.view("i8") # type: ignore[assignment] + td = np.asarray(Timedelta(other).asm8) else: - # TimedeltaArray/Index - nanos = other.asi8 - - if np.all(nanos % base_nanos == 0): - # nanos being added is an integer multiple of the - # base-frequency to self.freq - delta = nanos // base_nanos - # delta is the integer (or integer-array) number of periods - # by which will be added to self. - return delta - - raise raise_on_incompatible(self, other) + td = np.asarray(other) + + try: + delta = astype_overflowsafe(td, dtype=dtype, copy=False, round_ok=False) + except ValueError as err: + raise raise_on_incompatible(self, other) from err + + delta = delta.view("i8") + return lib.item_from_zerodim(delta) def raise_on_incompatible(left, right): diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 50f5ab8aee9dd..b03ac26a4b74d 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -807,9 +807,13 @@ def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq): elif pi_freq == "D": # Tick, but non-compatible - msg = "Input has different freq=None from PeriodArray" + msg = ( + "Cannot add/subtract timedelta-like from PeriodArray that is " + "not an integer multiple of the PeriodArray's freq." + ) with pytest.raises(IncompatibleFrequency, match=msg): pi - td64obj + with pytest.raises(IncompatibleFrequency, match=msg): pi[0] - td64obj @@ -1107,7 +1111,15 @@ def test_parr_add_sub_timedeltalike_freq_mismatch_daily( rng = period_range("2014-05-01", "2014-05-15", freq="D") rng = tm.box_expected(rng, box_with_array) - msg = "Input has different freq(=.+)? from Period.*?\\(freq=D\\)" + msg = "|".join( + [ + # non-timedelta-like DateOffset + "Input has different freq(=.+)? from Period.*?\\(freq=D\\)", + # timedelta/td64/Timedelta but not a multiple of 24H + "Cannot add/subtract timedelta-like from PeriodArray that is " + "not an integer multiple of the PeriodArray's freq.", + ] + ) with pytest.raises(IncompatibleFrequency, match=msg): rng + other with pytest.raises(IncompatibleFrequency, match=msg): @@ -1134,7 +1146,15 @@ def test_parr_add_timedeltalike_mismatched_freq_hourly( other = not_hourly rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="H") rng = tm.box_expected(rng, box_with_array) - msg = "Input has different freq(=.+)? from Period.*?\\(freq=H\\)" + msg = "|".join( + [ + # non-timedelta-like DateOffset + "Input has different freq(=.+)? from Period.*?\\(freq=H\\)", + # timedelta/td64/Timedelta but not a multiple of 24H + "Cannot add/subtract timedelta-like from PeriodArray that is " + "not an integer multiple of the PeriodArray's freq.", + ] + ) with pytest.raises(IncompatibleFrequency, match=msg): rng + other @@ -1508,17 +1528,17 @@ def test_pi_offset_errors(self): ) ser = Series(idx) - # Series op is applied per Period instance, thus error is raised - # from Period + msg = ( + "Cannot add/subtract timedelta-like from PeriodArray that is not " + "an integer multiple of the PeriodArray's freq" + ) for obj in [idx, ser]: - msg = r"Input has different freq=2H from Period.*?\(freq=D\)" with pytest.raises(IncompatibleFrequency, match=msg): obj + pd.offsets.Hour(2) with pytest.raises(IncompatibleFrequency, match=msg): pd.offsets.Hour(2) + obj - msg = r"Input has different freq=-2H from Period.*?\(freq=D\)" with pytest.raises(IncompatibleFrequency, match=msg): obj - pd.offsets.Hour(2)
and improved exception message - [ ] 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/47826
2022-07-22T23:31:55Z
2022-07-25T16:49:16Z
2022-07-25T16:49:16Z
2022-07-25T17:34:42Z
Specify that both ``by`` and ``level`` should not be specified in ``groupby`` - GH40378
diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst index 34244a8edcbfa..5d8ef7ce02097 100644 --- a/doc/source/user_guide/groupby.rst +++ b/doc/source/user_guide/groupby.rst @@ -345,17 +345,6 @@ Index level names may be supplied as keys. More on the ``sum`` function and aggregation later. -When using ``.groupby()`` on a DatFrame with a MultiIndex, do not specify both ``by`` and ``level``. -The argument validation should be done in ``.groupby()``, using the name of the specific index. - -.. ipython:: python - - df = pd.DataFrame({"col1": ["a", "b", "c"]}) - df.index = pd.MultiIndex.from_arrays([["a", "a", "b"], - [1, 2, 1]], - names=["x", "y"]) - df.groupby(["col1", "x"]) - Grouping DataFrame with Index levels and columns ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A DataFrame may be grouped by a combination of columns and index levels by diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index b7b75d6464da3..09c8cf39f5839 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -110,7 +110,7 @@ is unused and defaults to 0. level : int, level name, or sequence of such, default None If the axis is a MultiIndex (hierarchical), group by a particular - level or levels. + level or levels. Do not specify both ``by`` and ``level``. as_index : bool, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is
- [x] closes #40378 - [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. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Ref: https://github.com/pandas-dev/pandas/pull/47778#discussion_r923860446
https://api.github.com/repos/pandas-dev/pandas/pulls/47825
2022-07-22T19:53:23Z
2022-08-08T18:52:13Z
2022-08-08T18:52:13Z
2022-08-08T18:52:19Z
Manual Backport PR #47803 on branch 1.4.x (TST/CI: xfail test_round_sanity for 32 bit)
diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 7a32c932aee77..bedc09959520a 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -13,6 +13,7 @@ NaT, iNaT, ) +from pandas.compat import IS64 import pandas as pd from pandas import ( @@ -413,6 +414,7 @@ def test_round_implementation_bounds(self): with pytest.raises(OverflowError, match=msg): Timedelta.max.ceil("s") + @pytest.mark.xfail(not IS64, reason="Failing on 32 bit build", strict=False) @given(val=st.integers(min_value=iNaT + 1, max_value=lib.i8max)) @pytest.mark.parametrize( "method", [Timedelta.round, Timedelta.floor, Timedelta.ceil] diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index 5f07cabd51ca1..5dc558b6739b8 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -20,6 +20,7 @@ to_offset, ) from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG +from pandas.compat import IS64 import pandas.util._test_decorators as td import pandas._testing as tm @@ -280,6 +281,7 @@ def test_round_implementation_bounds(self): with pytest.raises(OverflowError, match=msg): Timestamp.max.ceil("s") + @pytest.mark.xfail(not IS64, reason="Failing on 32 bit build", strict=False) @given(val=st.integers(iNaT + 1, lib.i8max)) @pytest.mark.parametrize( "method", [Timestamp.round, Timestamp.floor, Timestamp.ceil]
Manual Backport PR #47803 - [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).
https://api.github.com/repos/pandas-dev/pandas/pulls/47824
2022-07-22T19:43:21Z
2022-07-23T11:07:06Z
2022-07-23T11:07:06Z
2022-07-23T18:13:06Z
Fixed metadata propagation in Dataframe.idxmax and Dataframe.idxmin #…
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e62f9fa8076d8..47203fbf315e5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11010,7 +11010,8 @@ def idxmin( index = data._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] - return data._constructor_sliced(result, index=data._get_agg_axis(axis)) + final_result = data._constructor_sliced(result, index=data._get_agg_axis(axis)) + return final_result.__finalize__(self, method="idxmin") @doc(_shared_docs["idxmax"], numeric_only_default="False") def idxmax( @@ -11035,7 +11036,8 @@ def idxmax( index = data._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] - return data._constructor_sliced(result, index=data._get_agg_axis(axis)) + final_result = data._constructor_sliced(result, index=data._get_agg_axis(axis)) + return final_result.__finalize__(self, method="idxmax") def _get_agg_axis(self, axis_num: int) -> Index: """ diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 6901d415a5ae7..dddab05af7341 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -226,17 +226,9 @@ pytest.param( (pd.DataFrame, frame_data, operator.methodcaller("nunique")), ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("idxmin")), - marks=not_implemented_mark, - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("idxmax")), - marks=not_implemented_mark, - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("mode")), - ), + (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,
…28283 - [x] contributes to #28283 calling .__finalize__ on Dataframe.idxmax, idxmin
https://api.github.com/repos/pandas-dev/pandas/pulls/47821
2022-07-22T15:56:37Z
2022-07-25T16:50:52Z
2022-07-25T16:50:52Z
2022-07-25T16:50:59Z
ENH: Add ArrowDype and .array.ArrowExtensionArray to top level
diff --git a/pandas/__init__.py b/pandas/__init__.py index eb5ce71141f46..5016bde000c3b 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -47,6 +47,7 @@ from pandas.core.api import ( # dtype + ArrowDtype, Int8Dtype, Int16Dtype, Int32Dtype, @@ -308,6 +309,7 @@ def __getattr__(name): # Pandas is not (yet) a py.typed library: the public API is determined # based on the documentation. __all__ = [ + "ArrowDtype", "BooleanDtype", "Categorical", "CategoricalDtype", diff --git a/pandas/core/api.py b/pandas/core/api.py index c2bedb032d479..3d2547fcea230 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -25,6 +25,7 @@ value_counts, ) from pandas.core.arrays import Categorical +from pandas.core.arrays.arrow import ArrowDtype from pandas.core.arrays.boolean import BooleanDtype from pandas.core.arrays.floating import ( Float32Dtype, @@ -85,6 +86,7 @@ __all__ = [ "array", + "ArrowDtype", "bdate_range", "BooleanDtype", "Categorical", diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index e301e82a0ee75..79be8760db931 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -1,3 +1,4 @@ +from pandas.core.arrays.arrow import ArrowExtensionArray from pandas.core.arrays.base import ( ExtensionArray, ExtensionOpsMixin, @@ -21,6 +22,7 @@ from pandas.core.arrays.timedeltas import TimedeltaArray __all__ = [ + "ArrowExtensionArray", "ExtensionArray", "ExtensionOpsMixin", "ExtensionScalarOpsMixin", diff --git a/pandas/core/arrays/arrow/__init__.py b/pandas/core/arrays/arrow/__init__.py index 58b268cbdd221..e7fa6fae0a5a1 100644 --- a/pandas/core/arrays/arrow/__init__.py +++ b/pandas/core/arrays/arrow/__init__.py @@ -1,3 +1,4 @@ from pandas.core.arrays.arrow.array import ArrowExtensionArray +from pandas.core.arrays.arrow.dtype import ArrowDtype -__all__ = ["ArrowExtensionArray"] +__all__ = ["ArrowDtype", "ArrowExtensionArray"] diff --git a/pandas/core/arrays/arrow/_arrow_utils.py b/pandas/core/arrays/arrow/_arrow_utils.py index 81ba04a4e1426..e4b934023d701 100644 --- a/pandas/core/arrays/arrow/_arrow_utils.py +++ b/pandas/core/arrays/arrow/_arrow_utils.py @@ -1,19 +1,14 @@ from __future__ import annotations import inspect -import json import warnings import numpy as np import pyarrow -from pandas._typing import IntervalInclusiveType from pandas.errors import PerformanceWarning -from pandas.util._decorators import deprecate_kwarg from pandas.util._exceptions import find_stack_level -from pandas.core.arrays.interval import VALID_INCLUSIVE - def fallback_performancewarning(version: str | None = None) -> None: """ @@ -67,109 +62,3 @@ def pyarrow_array_to_numpy_and_mask( else: mask = np.ones(len(arr), dtype=bool) return data, mask - - -class ArrowPeriodType(pyarrow.ExtensionType): - def __init__(self, freq) -> None: - # attributes need to be set first before calling - # super init (as that calls serialize) - self._freq = freq - pyarrow.ExtensionType.__init__(self, pyarrow.int64(), "pandas.period") - - @property - def freq(self): - return self._freq - - def __arrow_ext_serialize__(self) -> bytes: - metadata = {"freq": self.freq} - return json.dumps(metadata).encode() - - @classmethod - def __arrow_ext_deserialize__(cls, storage_type, serialized) -> ArrowPeriodType: - metadata = json.loads(serialized.decode()) - return ArrowPeriodType(metadata["freq"]) - - def __eq__(self, other): - if isinstance(other, pyarrow.BaseExtensionType): - return type(self) == type(other) and self.freq == other.freq - else: - return NotImplemented - - def __hash__(self) -> int: - return hash((str(self), self.freq)) - - def to_pandas_dtype(self): - import pandas as pd - - return pd.PeriodDtype(freq=self.freq) - - -# register the type with a dummy instance -_period_type = ArrowPeriodType("D") -pyarrow.register_extension_type(_period_type) - - -class ArrowIntervalType(pyarrow.ExtensionType): - @deprecate_kwarg(old_arg_name="closed", new_arg_name="inclusive") - def __init__(self, subtype, inclusive: IntervalInclusiveType) -> None: - # attributes need to be set first before calling - # super init (as that calls serialize) - assert inclusive in VALID_INCLUSIVE - self._inclusive: IntervalInclusiveType = inclusive - if not isinstance(subtype, pyarrow.DataType): - subtype = pyarrow.type_for_alias(str(subtype)) - self._subtype = subtype - - storage_type = pyarrow.struct([("left", subtype), ("right", subtype)]) - pyarrow.ExtensionType.__init__(self, storage_type, "pandas.interval") - - @property - def subtype(self): - return self._subtype - - @property - def inclusive(self) -> IntervalInclusiveType: - return self._inclusive - - @property - def closed(self) -> IntervalInclusiveType: - warnings.warn( - "Attribute `closed` is deprecated in favor of `inclusive`.", - FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), - ) - return self._inclusive - - def __arrow_ext_serialize__(self) -> bytes: - metadata = {"subtype": str(self.subtype), "inclusive": self.inclusive} - return json.dumps(metadata).encode() - - @classmethod - def __arrow_ext_deserialize__(cls, storage_type, serialized) -> ArrowIntervalType: - metadata = json.loads(serialized.decode()) - subtype = pyarrow.type_for_alias(metadata["subtype"]) - inclusive = metadata["inclusive"] - return ArrowIntervalType(subtype, inclusive) - - def __eq__(self, other): - if isinstance(other, pyarrow.BaseExtensionType): - return ( - type(self) == type(other) - and self.subtype == other.subtype - and self.inclusive == other.inclusive - ) - else: - return NotImplemented - - def __hash__(self) -> int: - return hash((str(self), str(self.subtype), self.inclusive)) - - def to_pandas_dtype(self): - import pandas as pd - - return pd.IntervalDtype(self.subtype.to_pandas_dtype(), self.inclusive) - - -# register the type with a dummy instance -_interval_type = ArrowIntervalType(pyarrow.int64(), "left") -pyarrow.register_extension_type(_interval_type) diff --git a/pandas/core/arrays/arrow/dtype.py b/pandas/core/arrays/arrow/dtype.py index 4a32663a68ed2..523e031c220e4 100644 --- a/pandas/core/arrays/arrow/dtype.py +++ b/pandas/core/arrays/arrow/dtype.py @@ -3,9 +3,9 @@ import re import numpy as np -import pyarrow as pa from pandas._typing import DtypeObj +from pandas.compat import pa_version_under1p01 from pandas.util._decorators import cache_readonly from pandas.core.dtypes.base import ( @@ -13,6 +13,9 @@ register_extension_dtype, ) +if not pa_version_under1p01: + import pyarrow as pa + @register_extension_dtype class ArrowDtype(StorageExtensionDtype): @@ -25,6 +28,8 @@ class ArrowDtype(StorageExtensionDtype): def __init__(self, pyarrow_dtype: pa.DataType) -> None: super().__init__("pyarrow") + if pa_version_under1p01: + raise ImportError("pyarrow>=1.0.1 is required for ArrowDtype") if not isinstance(pyarrow_dtype, pa.DataType): raise ValueError( f"pyarrow_dtype ({pyarrow_dtype}) must be an instance " @@ -93,6 +98,9 @@ def construct_from_string(cls, string: str) -> ArrowDtype: ) if not string.endswith("[pyarrow]"): raise TypeError(f"'{string}' must end with '[pyarrow]'") + if string == "string[pyarrow]": + # Ensure Registry.find skips ArrowDtype to use StringDtype instead + raise TypeError("string[pyarrow] should be constructed by StringDtype") base_type = string.split("[pyarrow]")[0] try: pa_dtype = pa.type_for_alias(base_type) diff --git a/pandas/core/arrays/arrow/extension_types.py b/pandas/core/arrays/arrow/extension_types.py new file mode 100644 index 0000000000000..a2b3c6d4da080 --- /dev/null +++ b/pandas/core/arrays/arrow/extension_types.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import json +import warnings + +import pyarrow + +from pandas._typing import IntervalInclusiveType +from pandas.util._decorators import deprecate_kwarg +from pandas.util._exceptions import find_stack_level + +from pandas.core.arrays.interval import VALID_INCLUSIVE + + +class ArrowPeriodType(pyarrow.ExtensionType): + def __init__(self, freq) -> None: + # attributes need to be set first before calling + # super init (as that calls serialize) + self._freq = freq + pyarrow.ExtensionType.__init__(self, pyarrow.int64(), "pandas.period") + + @property + def freq(self): + return self._freq + + def __arrow_ext_serialize__(self) -> bytes: + metadata = {"freq": self.freq} + return json.dumps(metadata).encode() + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized) -> ArrowPeriodType: + metadata = json.loads(serialized.decode()) + return ArrowPeriodType(metadata["freq"]) + + def __eq__(self, other): + if isinstance(other, pyarrow.BaseExtensionType): + return type(self) == type(other) and self.freq == other.freq + else: + return NotImplemented + + def __hash__(self) -> int: + return hash((str(self), self.freq)) + + def to_pandas_dtype(self): + import pandas as pd + + return pd.PeriodDtype(freq=self.freq) + + +# register the type with a dummy instance +_period_type = ArrowPeriodType("D") +pyarrow.register_extension_type(_period_type) + + +class ArrowIntervalType(pyarrow.ExtensionType): + @deprecate_kwarg(old_arg_name="closed", new_arg_name="inclusive") + def __init__(self, subtype, inclusive: IntervalInclusiveType) -> None: + # attributes need to be set first before calling + # super init (as that calls serialize) + assert inclusive in VALID_INCLUSIVE + self._inclusive: IntervalInclusiveType = inclusive + if not isinstance(subtype, pyarrow.DataType): + subtype = pyarrow.type_for_alias(str(subtype)) + self._subtype = subtype + + storage_type = pyarrow.struct([("left", subtype), ("right", subtype)]) + pyarrow.ExtensionType.__init__(self, storage_type, "pandas.interval") + + @property + def subtype(self): + return self._subtype + + @property + def inclusive(self) -> IntervalInclusiveType: + return self._inclusive + + @property + def closed(self) -> IntervalInclusiveType: + warnings.warn( + "Attribute `closed` is deprecated in favor of `inclusive`.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self._inclusive + + def __arrow_ext_serialize__(self) -> bytes: + metadata = {"subtype": str(self.subtype), "inclusive": self.inclusive} + return json.dumps(metadata).encode() + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized) -> ArrowIntervalType: + metadata = json.loads(serialized.decode()) + subtype = pyarrow.type_for_alias(metadata["subtype"]) + inclusive = metadata["inclusive"] + return ArrowIntervalType(subtype, inclusive) + + def __eq__(self, other): + if isinstance(other, pyarrow.BaseExtensionType): + return ( + type(self) == type(other) + and self.subtype == other.subtype + and self.inclusive == other.inclusive + ) + else: + return NotImplemented + + def __hash__(self) -> int: + return hash((str(self), str(self.subtype), self.inclusive)) + + def to_pandas_dtype(self): + import pandas as pd + + return pd.IntervalDtype(self.subtype.to_pandas_dtype(), self.inclusive) + + +# register the type with a dummy instance +_interval_type = ArrowIntervalType(pyarrow.int64(), "left") +pyarrow.register_extension_type(_interval_type) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index bd765b4601b01..6b670028f2d1d 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -1554,7 +1554,7 @@ def __arrow_array__(self, type=None): """ import pyarrow - from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType + from pandas.core.arrays.arrow.extension_types import ArrowIntervalType try: subtype = pyarrow.from_numpy_dtype(self.dtype.subtype) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index cd88eb1e49be8..e6ea7b0879100 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -377,7 +377,7 @@ def __arrow_array__(self, type=None): """ import pyarrow - from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType if type is not None: if pyarrow.types.is_integer(type): diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index caddd12a2c2b4..01f29efbfba11 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -114,7 +114,6 @@ class ArrowStringArray(ArrowExtensionArray, BaseStringArray, ObjectStringArrayMi def __init__(self, values) -> None: super().__init__(values) - # TODO: Migrate to ArrowDtype instead self._dtype = StringDtype(storage="pyarrow") if not pa.types.is_string(self._data.type): diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 378b158d1b0bb..d0ec419c3b392 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -151,7 +151,7 @@ def __init__(self) -> None: import pyarrow.parquet # import utils to register the pyarrow extension types - import pandas.core.arrays.arrow._arrow_utils # pyright: ignore # noqa:F401 + import pandas.core.arrays.arrow.extension_types # pyright: ignore # noqa:F401 self.api = pyarrow diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index c62a86e1983f5..c2db9698d0537 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -53,6 +53,7 @@ class TestPDApi(Base): # top-level classes classes = [ + "ArrowDtype", "Categorical", "CategoricalIndex", "DataFrame", diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py index 073e6b6119b14..48f5c676b66e6 100644 --- a/pandas/tests/arrays/interval/test_interval.py +++ b/pandas/tests/arrays/interval/test_interval.py @@ -248,7 +248,7 @@ def test_min_max(self, left_right_dtypes, index_or_series_or_array): def test_arrow_extension_type(): import pyarrow as pa - from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType + from pandas.core.arrays.arrow.extension_types import ArrowIntervalType p1 = ArrowIntervalType(pa.int64(), "left") p2 = ArrowIntervalType(pa.int64(), "left") @@ -265,7 +265,7 @@ def test_arrow_extension_type(): def test_arrow_array(): import pyarrow as pa - from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType + from pandas.core.arrays.arrow.extension_types import ArrowIntervalType intervals = pd.interval_range(1, 5, freq=1).array @@ -295,7 +295,7 @@ def test_arrow_array(): def test_arrow_array_missing(): import pyarrow as pa - from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType + from pandas.core.arrays.arrow.extension_types import ArrowIntervalType arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0]) arr[1] = None @@ -330,7 +330,7 @@ def test_arrow_array_missing(): def test_arrow_table_roundtrip(breaks): import pyarrow as pa - from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType + from pandas.core.arrays.arrow.extension_types import ArrowIntervalType arr = IntervalArray.from_breaks(breaks) arr[1] = None @@ -431,7 +431,7 @@ def test_arrow_interval_type_error_and_warning(): # GH 40245 import pyarrow as pa - from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType + from pandas.core.arrays.arrow.extension_types import ArrowIntervalType msg = "Can only specify 'closed' or 'inclusive', not both." with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/arrays/period/test_arrow_compat.py b/pandas/tests/arrays/period/test_arrow_compat.py index 7d2d2daed3497..03fd146572405 100644 --- a/pandas/tests/arrays/period/test_arrow_compat.py +++ b/pandas/tests/arrays/period/test_arrow_compat.py @@ -13,7 +13,7 @@ def test_arrow_extension_type(): - from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType p1 = ArrowPeriodType("D") p2 = ArrowPeriodType("D") @@ -34,7 +34,7 @@ def test_arrow_extension_type(): ], ) def test_arrow_array(data, freq): - from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType periods = period_array(data, freq=freq) result = pa.array(periods) @@ -57,7 +57,7 @@ def test_arrow_array(data, freq): def test_arrow_array_missing(): - from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType arr = PeriodArray([1, 2, 3], freq="D") arr[1] = pd.NaT @@ -70,7 +70,7 @@ def test_arrow_array_missing(): def test_arrow_table_roundtrip(): - from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType arr = PeriodArray([1, 2, 3], freq="D") arr[1] = pd.NaT @@ -91,7 +91,7 @@ def test_arrow_table_roundtrip(): def test_arrow_load_from_zero_chunks(): # GH-41040 - from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType + from pandas.core.arrays.arrow.extension_types import ArrowPeriodType arr = PeriodArray([], freq="D") df = pd.DataFrame({"a": arr})
- [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). Moved `ArrowIntervalType` and `ArrowPeriodType` to a separate file `arrow/extension_types.py` to avoid a circular import. Will add documentation in a separate PR https://github.com/pandas-dev/pandas/pull/47854
https://api.github.com/repos/pandas-dev/pandas/pulls/47818
2022-07-22T03:57:29Z
2022-08-16T18:28:04Z
2022-08-16T18:28:04Z
2022-08-16T18:28:08Z
CI/TYP: run stubtest
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f65c42dab1852..e4ab74091d6b6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -85,9 +85,9 @@ repos: - repo: local hooks: - id: pyright + # note: assumes python env is setup and activated name: pyright entry: pyright - # note: assumes python env is setup and activated language: node pass_filenames: false types: [python] @@ -95,22 +95,32 @@ repos: additional_dependencies: &pyright_dependencies - pyright@1.1.262 - id: pyright_reportGeneralTypeIssues + # note: assumes python env is setup and activated name: pyright reportGeneralTypeIssues entry: pyright --skipunannotated -p pyright_reportGeneralTypeIssues.json - # note: assumes python env is setup and activated language: node pass_filenames: false types: [python] stages: [manual] additional_dependencies: *pyright_dependencies - id: mypy + # note: assumes python env is setup and activated name: mypy entry: mypy - # note: assumes python env is setup and activated language: system pass_filenames: false types: [python] stages: [manual] + - id: stubtest + # note: assumes python env is setup and activated + # note: requires pandas dev to be installed + name: mypy (stubtest) + entry: python + language: system + pass_filenames: false + types: [pyi] + args: [scripts/run_stubtest.py] + stages: [manual] - id: flake8-rst name: flake8-rst description: Run flake8 on code snippets in docstrings or RST files diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi index a6d593076777d..8500fdf2f602e 100644 --- a/pandas/_libs/hashtable.pyi +++ b/pandas/_libs/hashtable.pyi @@ -39,72 +39,72 @@ class Int64Factorizer(Factorizer): ) -> npt.NDArray[np.intp]: ... class Int64Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int64]: ... class Int32Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int32]: ... class Int16Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int16]: ... class Int8Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int8]: ... class UInt64Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint64]: ... class UInt32Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint32]: ... class UInt16Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint16]: ... class UInt8Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint8]: ... class Float64Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.float64]: ... class Float32Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.float32]: ... class Complex128Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.complex128]: ... class Complex64Vector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.complex64]: ... class StringVector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.object_]: ... class ObjectVector: - def __init__(self): ... + def __init__(self, *args): ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.object_]: ... diff --git a/pandas/_libs/tslibs/timedeltas.pyi b/pandas/_libs/tslibs/timedeltas.pyi index 7969c0901e08f..d100108e7dd2b 100644 --- a/pandas/_libs/tslibs/timedeltas.pyi +++ b/pandas/_libs/tslibs/timedeltas.pyi @@ -85,7 +85,7 @@ class Timedelta(timedelta): def __new__( cls: type[_S], value=..., - unit: str = ..., + unit: str | None = ..., **kwargs: float | np.integer | np.floating, ) -> _S: ... # GH 46171 diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index f35d744763478..a3b2003b0caf3 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -163,6 +163,7 @@ class ArrowExtensionArray(OpsMixin, ExtensionArray): """ _data: pa.ChunkedArray + _dtype: ArrowDtype def __init__(self, values: pa.Array | pa.ChunkedArray) -> None: if pa_version_under1p01: diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index bb2fefabd6ae5..caddd12a2c2b4 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -108,6 +108,10 @@ class ArrowStringArray(ArrowExtensionArray, BaseStringArray, ObjectStringArrayMi Length: 4, dtype: string """ + # error: Incompatible types in assignment (expression has type "StringDtype", + # base class "ArrowExtensionArray" defined the type as "ArrowDtype") + _dtype: StringDtype # type: ignore[assignment] + def __init__(self, values) -> None: super().__init__(values) # TODO: Migrate to ArrowDtype instead diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 84915e2f52f17..c92c448304de2 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -144,7 +144,7 @@ def __init__( self._win_type = win_type self.axis = obj._get_axis_number(axis) if axis is not None else None self.method = method - self._win_freq_i8 = None + self._win_freq_i8: int | None = None if self.on is None: if self.axis == 0: self._on = self.obj.index @@ -1838,15 +1838,13 @@ def _validate(self): "compatible with a datetimelike index" ) from err if isinstance(self._on, PeriodIndex): - # error: Incompatible types in assignment (expression has type "float", - # variable has type "None") + # error: Incompatible types in assignment (expression has type + # "float", variable has type "Optional[int]") self._win_freq_i8 = freq.nanos / ( # type: ignore[assignment] self._on.freq.nanos / self._on.freq.n ) else: - # error: Incompatible types in assignment (expression has type "int", - # variable has type "None") - self._win_freq_i8 = freq.nanos # type: ignore[assignment] + self._win_freq_i8 = freq.nanos # min_periods must be an integer if self.min_periods is None: @@ -2867,7 +2865,9 @@ def _get_window_indexer(self) -> GroupbyIndexer: window = self.window elif self._win_freq_i8 is not None: rolling_indexer = VariableWindowIndexer - window = self._win_freq_i8 + # error: Incompatible types in assignment (expression has type + # "int", variable has type "BaseIndexer") + window = self._win_freq_i8 # type: ignore[assignment] else: rolling_indexer = FixedWindowIndexer window = self.window diff --git a/scripts/run_stubtest.py b/scripts/run_stubtest.py new file mode 100644 index 0000000000000..cea9665e649d6 --- /dev/null +++ b/scripts/run_stubtest.py @@ -0,0 +1,85 @@ +import os +from pathlib import Path +import sys +import tempfile +import warnings + +from mypy import stubtest + +import pandas as pd + +# fail early if pandas is not installed +if "dev" not in getattr(pd, "__version__", ""): + # fail on the CI, soft fail during local development + warnings.warn("You need to install the development version of pandas") + if pd.compat.is_ci_environment(): + sys.exit(1) + else: + sys.exit(0) + + +_ALLOWLIST = [ # should be empty + # TODO (child classes implement these methods) + "pandas._libs.hashtable.HashTable.__contains__", + "pandas._libs.hashtable.HashTable.__len__", + "pandas._libs.hashtable.HashTable.factorize", + "pandas._libs.hashtable.HashTable.get_item", + "pandas._libs.hashtable.HashTable.get_labels", + "pandas._libs.hashtable.HashTable.get_state", + "pandas._libs.hashtable.HashTable.lookup", + "pandas._libs.hashtable.HashTable.map_locations", + "pandas._libs.hashtable.HashTable.set_item", + "pandas._libs.hashtable.HashTable.sizeof", + "pandas._libs.hashtable.HashTable.unique", + # stubtest might be too sensitive + "pandas._libs.lib.NoDefault", + "pandas._libs.lib._NoDefault.no_default", + # internal type alias (should probably be private) + "pandas._libs.lib.ndarray_obj_2d", + # workaround for mypy (cache_readonly = property) + "pandas._libs.properties.cache_readonly.__get__", + "pandas._libs.properties.cache_readonly.deleter", + "pandas._libs.properties.cache_readonly.getter", + "pandas._libs.properties.cache_readonly.setter", + # TODO (child classes implement these methods) + "pandas._libs.sparse.SparseIndex.__init__", + "pandas._libs.sparse.SparseIndex.equals", + "pandas._libs.sparse.SparseIndex.indices", + "pandas._libs.sparse.SparseIndex.intersect", + "pandas._libs.sparse.SparseIndex.lookup", + "pandas._libs.sparse.SparseIndex.lookup_array", + "pandas._libs.sparse.SparseIndex.make_union", + "pandas._libs.sparse.SparseIndex.nbytes", + "pandas._libs.sparse.SparseIndex.ngaps", + "pandas._libs.sparse.SparseIndex.to_block_index", + "pandas._libs.sparse.SparseIndex.to_int_index", + # TODO (decorator changes argument names) + "pandas._libs.tslibs.offsets.BaseOffset._apply_array", + "pandas._libs.tslibs.offsets.BusinessHour.rollback", + "pandas._libs.tslibs.offsets.BusinessHour.rollforward ", + # type alias + "pandas._libs.tslibs.timedeltas.UnitChoices", +] + +if __name__ == "__main__": + # find pyi files + root = Path.cwd() + pyi_modules = [ + str(pyi.relative_to(root).with_suffix("")).replace(os.sep, ".") + for pyi in root.glob("pandas/**/*.pyi") + ] + + # create allowlist + with tempfile.NamedTemporaryFile(mode="w+t") as allow: + allow.write("\n".join(_ALLOWLIST)) + allow.flush() + + args = pyi_modules + [ + "--ignore-missing-stub", + "--concise", + "--mypy-config-file", + "pyproject.toml", + "--allowlist", + allow.name, + ] + sys.exit(stubtest.test_stubs(stubtest.parse_options(args)))
Stubtest enforces that pyi files do not get out of sync with the implementation. stubtest and mypy seems to have a slight discrepancy (had to change annotations so that they both error in the same cases). stubtest needs pandas dev to be installed. This might not be something people want to do locally: if pandas dev is not installed: `scripts/run_stubtest.py` will 'succeed' but print a warning (the CI has pandas dev installed). Might want to wait for the CI using mypy 0.971 (#47806 waiting for conda). @hauntsaninja: The allow list acts more or less like ignore comments, is there an option to error on unused allow list entries? Closes #47760
https://api.github.com/repos/pandas-dev/pandas/pulls/47817
2022-07-21T14:49:37Z
2022-08-01T17:11:29Z
2022-08-01T17:11:29Z
2022-09-10T01:38:53Z
TST: Addition test for get_indexer for interval index
diff --git a/pandas/tests/indexes/interval/test_indexing.py b/pandas/tests/indexes/interval/test_indexing.py index e05cb73cfe446..74d17b31aff27 100644 --- a/pandas/tests/indexes/interval/test_indexing.py +++ b/pandas/tests/indexes/interval/test_indexing.py @@ -15,7 +15,11 @@ NaT, Series, Timedelta, + Timestamp, + array, date_range, + interval_range, + period_range, timedelta_range, ) import pandas._testing as tm @@ -415,6 +419,16 @@ def test_get_indexer_multiindex_with_intervals(self): expected = np.array([1, 4, 7], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) + @pytest.mark.parametrize("box", [IntervalIndex, array, list]) + def test_get_indexer_interval_index(self, box): + # GH#30178 + rng = period_range("2022-07-01", freq="D", periods=3) + idx = box(interval_range(Timestamp("2022-07-01"), freq="3D", periods=3)) + + actual = rng.get_indexer(idx) + expected = np.array([-1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(actual, expected) + class TestSliceLocs: def test_slice_locs_with_interval(self):
- [x] closes #30178 - [x] [Tests added and passed] - [x] All [code checks passed]
https://api.github.com/repos/pandas-dev/pandas/pulls/47816
2022-07-21T14:14:21Z
2022-07-26T16:38:56Z
2022-07-26T16:38:56Z
2022-07-26T16:39:11Z
ENH/TST: Add argsort/min/max for ArrowExtensionArray
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index a882d3a955469..841275e54e3d6 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -22,8 +22,12 @@ pa_version_under4p0, pa_version_under5p0, pa_version_under6p0, + pa_version_under7p0, +) +from pandas.util._decorators import ( + deprecate_nonkeyword_arguments, + doc, ) -from pandas.util._decorators import doc from pandas.core.dtypes.common import ( is_array_like, @@ -418,6 +422,58 @@ def isna(self) -> npt.NDArray[np.bool_]: else: return self._data.is_null().to_numpy() + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) + def argsort( + self, + ascending: bool = True, + kind: str = "quicksort", + na_position: str = "last", + *args, + **kwargs, + ) -> np.ndarray: + order = "ascending" if ascending else "descending" + null_placement = {"last": "at_end", "first": "at_start"}.get(na_position, None) + if null_placement is None or pa_version_under7p0: + # Although pc.array_sort_indices exists in version 6 + # there's a bug that affects the pa.ChunkedArray backing + # https://issues.apache.org/jira/browse/ARROW-12042 + fallback_performancewarning("7") + return super().argsort( + ascending=ascending, kind=kind, na_position=na_position + ) + + result = pc.array_sort_indices( + self._data, order=order, null_placement=null_placement + ) + if pa_version_under2p0: + np_result = result.to_pandas().values + else: + np_result = result.to_numpy() + return np_result.astype(np.intp, copy=False) + + def _argmin_max(self, skipna: bool, method: str) -> int: + if self._data.length() in (0, self._data.null_count) or ( + self._hasna and not skipna + ): + # For empty or all null, pyarrow returns -1 but pandas expects TypeError + # For skipna=False and data w/ null, pandas expects NotImplementedError + # let ExtensionArray.arg{max|min} raise + return getattr(super(), f"arg{method}")(skipna=skipna) + + if pa_version_under6p0: + raise NotImplementedError( + f"arg{method} only implemented for pyarrow version >= 6.0" + ) + + value = getattr(pc, method)(self._data, skip_nulls=skipna) + return pc.index(self._data, value).as_py() + + def argmin(self, skipna: bool = True) -> int: + return self._argmin_max(skipna, "min") + + def argmax(self, skipna: bool = True) -> int: + return self._argmin_max(skipna, "max") + def copy(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT: """ Return a shallow copy of the array. diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index a2a96da02b2a6..2f3482ddc4811 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -1385,6 +1385,11 @@ def test_value_counts_with_normalize(self, data, request): ) super().test_value_counts_with_normalize(data) + @pytest.mark.xfail( + pa_version_under6p0, + raises=NotImplementedError, + reason="argmin/max only implemented for pyarrow version >= 6.0", + ) def test_argmin_argmax( self, data_for_sorting, data_missing_for_sorting, na_value, request ): @@ -1395,8 +1400,50 @@ def test_argmin_argmax( reason=f"{pa_dtype} only has 2 unique possible values", ) ) + elif pa.types.is_duration(pa_dtype): + request.node.add_marker( + pytest.mark.xfail( + raises=pa.ArrowNotImplementedError, + reason=f"min_max not supported in pyarrow for {pa_dtype}", + ) + ) super().test_argmin_argmax(data_for_sorting, data_missing_for_sorting, na_value) + @pytest.mark.parametrize( + "op_name, skipna, expected", + [ + ("idxmax", True, 0), + ("idxmin", True, 2), + ("argmax", True, 0), + ("argmin", True, 2), + ("idxmax", False, np.nan), + ("idxmin", False, np.nan), + ("argmax", False, -1), + ("argmin", False, -1), + ], + ) + def test_argreduce_series( + self, data_missing_for_sorting, op_name, skipna, expected, request + ): + pa_dtype = data_missing_for_sorting.dtype.pyarrow_dtype + if pa_version_under6p0 and skipna: + request.node.add_marker( + pytest.mark.xfail( + raises=NotImplementedError, + reason="min_max not supported in pyarrow", + ) + ) + elif not pa_version_under6p0 and pa.types.is_duration(pa_dtype) and skipna: + request.node.add_marker( + pytest.mark.xfail( + raises=pa.ArrowNotImplementedError, + reason=f"min_max not supported in pyarrow for {pa_dtype}", + ) + ) + super().test_argreduce_series( + data_missing_for_sorting, op_name, skipna, expected + ) + @pytest.mark.parametrize("ascending", [True, False]) def test_sort_values(self, data_for_sorting, ascending, sort_by_key, request): pa_dtype = data_for_sorting.dtype.pyarrow_dtype diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index 6cea21b6672d8..e4293d6d70e38 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -167,7 +167,48 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna): class TestMethods(base.BaseMethodsTests): - pass + def test_argmin_argmax( + self, data_for_sorting, data_missing_for_sorting, na_value, request + ): + if pa_version_under6p0 and data_missing_for_sorting.dtype.storage == "pyarrow": + request.node.add_marker( + pytest.mark.xfail( + raises=NotImplementedError, + reason="min_max not supported in pyarrow", + ) + ) + super().test_argmin_argmax(data_for_sorting, data_missing_for_sorting, na_value) + + @pytest.mark.parametrize( + "op_name, skipna, expected", + [ + ("idxmax", True, 0), + ("idxmin", True, 2), + ("argmax", True, 0), + ("argmin", True, 2), + ("idxmax", False, np.nan), + ("idxmin", False, np.nan), + ("argmax", False, -1), + ("argmin", False, -1), + ], + ) + def test_argreduce_series( + self, data_missing_for_sorting, op_name, skipna, expected, request + ): + if ( + pa_version_under6p0 + and data_missing_for_sorting.dtype.storage == "pyarrow" + and skipna + ): + request.node.add_marker( + pytest.mark.xfail( + raises=NotImplementedError, + reason="min_max not supported in pyarrow", + ) + ) + super().test_argreduce_series( + data_missing_for_sorting, op_name, skipna, expected + ) class TestCasting(base.BaseCastingTests): diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index d582a469eaf0e..e7e971f957e48 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -10,7 +10,7 @@ from pandas.compat import ( IS64, - pa_version_under2p0, + pa_version_under7p0, ) from pandas.core.dtypes.common import is_integer_dtype @@ -396,11 +396,16 @@ def test_astype_preserves_name(self, index, dtype): # imaginary components discarded warn = np.ComplexWarning + is_pyarrow_str = ( + str(index.dtype) == "string[pyarrow]" + and pa_version_under7p0 + and dtype == "category" + ) try: # Some of these conversions cannot succeed so we use a try / except with tm.assert_produces_warning( warn, - raise_on_extra_warnings=not pa_version_under2p0, + raise_on_extra_warnings=is_pyarrow_str, ): result = index.astype(dtype) except (ValueError, TypeError, NotImplementedError, SystemError): diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index f38a6c89e1bcb..45ecd09e550d0 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -8,6 +8,8 @@ import numpy as np import pytest +from pandas.compat import pa_version_under7p0 + from pandas.core.dtypes.cast import find_common_type from pandas import ( @@ -177,7 +179,8 @@ def test_dunder_inplace_setops_deprecated(index): with tm.assert_produces_warning(FutureWarning): index &= index - with tm.assert_produces_warning(FutureWarning): + is_pyarrow = str(index.dtype) == "string[pyarrow]" and pa_version_under7p0 + with tm.assert_produces_warning(FutureWarning, raise_on_extra_warnings=is_pyarrow): index ^= index
- [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).
https://api.github.com/repos/pandas-dev/pandas/pulls/47811
2022-07-21T01:08:35Z
2022-07-28T17:37:37Z
2022-07-28T17:37:37Z
2022-07-28T17:57:45Z
BUG: fix SparseArray.unique IndexError and _first_fill_value_loc algo
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 090fea57872c5..acd7cec480c39 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -1026,6 +1026,7 @@ Reshaping Sparse ^^^^^^ - Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``SparseDtype`` failing to retain the array's ``fill_value`` (:issue:`45691`) +- Bug in :meth:`SparseArray.unique` fails to keep original elements order (:issue:`47809`) - ExtensionArray diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 5653d87a4570b..b547446603853 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -821,7 +821,7 @@ def shift(self: SparseArrayT, periods: int = 1, fill_value=None) -> SparseArrayT def _first_fill_value_loc(self): """ - Get the location of the first missing value. + Get the location of the first fill value. Returns ------- @@ -834,14 +834,24 @@ def _first_fill_value_loc(self): if not len(indices) or indices[0] > 0: return 0 - diff = indices[1:] - indices[:-1] - return np.searchsorted(diff, 2) + 1 + # a number larger than 1 should be appended to + # the last in case of fill value only appears + # in the tail of array + diff = np.r_[np.diff(indices), 2] + return indices[(diff > 1).argmax()] + 1 def unique(self: SparseArrayT) -> SparseArrayT: uniques = algos.unique(self.sp_values) - fill_loc = self._first_fill_value_loc() - if fill_loc >= 0: - uniques = np.insert(uniques, fill_loc, self.fill_value) + if len(self.sp_values) != len(self): + fill_loc = self._first_fill_value_loc() + # Inorder to align the behavior of pd.unique or + # pd.Series.unique, we should keep the original + # order, here we use unique again to find the + # insertion place. Since the length of sp_values + # is not large, maybe minor performance hurt + # is worthwhile to the correctness. + insert_loc = len(algos.unique(self.sp_values[:fill_loc])) + uniques = np.insert(uniques, insert_loc, self.fill_value) return type(self)._from_sequence(uniques, dtype=self.dtype) def _values_for_factorize(self): diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 492427b2be213..9b78eb345e188 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -391,23 +391,36 @@ def test_setting_fill_value_updates(): @pytest.mark.parametrize( - "arr, loc", + "arr,fill_value,loc", [ - ([None, 1, 2], 0), - ([0, None, 2], 1), - ([0, 1, None], 2), - ([0, 1, 1, None, None], 3), - ([1, 1, 1, 2], -1), - ([], -1), + ([None, 1, 2], None, 0), + ([0, None, 2], None, 1), + ([0, 1, None], None, 2), + ([0, 1, 1, None, None], None, 3), + ([1, 1, 1, 2], None, -1), + ([], None, -1), + ([None, 1, 0, 0, None, 2], None, 0), + ([None, 1, 0, 0, None, 2], 1, 1), + ([None, 1, 0, 0, None, 2], 2, 5), + ([None, 1, 0, 0, None, 2], 3, -1), + ([None, 0, 0, 1, 2, 1], 0, 1), + ([None, 0, 0, 1, 2, 1], 1, 3), ], ) -def test_first_fill_value_loc(arr, loc): - result = SparseArray(arr)._first_fill_value_loc() +def test_first_fill_value_loc(arr, fill_value, loc): + result = SparseArray(arr, fill_value=fill_value)._first_fill_value_loc() assert result == loc @pytest.mark.parametrize( - "arr", [[1, 2, np.nan, np.nan], [1, np.nan, 2, np.nan], [1, 2, np.nan]] + "arr", + [ + [1, 2, np.nan, np.nan], + [1, np.nan, 2, np.nan], + [1, 2, np.nan], + [np.nan, 1, 0, 0, np.nan, 2], + [np.nan, 0, 0, 1, 2, 1], + ], ) @pytest.mark.parametrize("fill_value", [np.nan, 0, 1]) def test_unique_na_fill(arr, fill_value):
- [x] closes #47809 - [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). - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Only on master, whatsnew omitted. Please review #47779 after this merged. Remind that `pd.unique`/`SparseArray` and `np.unique` is not the same. The former one will keep the original order (which is from pd.core.algorithms.unique) and numpy unique will sort the result. cc @mzeitlin11
https://api.github.com/repos/pandas-dev/pandas/pulls/47810
2022-07-21T00:50:35Z
2022-07-22T17:32:20Z
2022-07-22T17:32:20Z
2022-07-25T04:06:55Z
DOC: add pivot_table note to dropna doc
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ead4ea744c647..39bbfc75b0376 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8564,7 +8564,9 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame: margins : bool, default False Add all row / columns (e.g. for subtotal / grand totals). dropna : bool, default True - Do not include columns whose entries are all NaN. + Do not include columns whose entries are all NaN. If True, + rows with a NaN value in any column will be omitted before + computing margins. margins_name : str, default 'All' Name of the row / column that will contain the totals when margins is True.
- [ ] closes #47447 - [ ] [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/47808
2022-07-21T00:04:01Z
2022-08-01T19:24:30Z
2022-08-01T19:24:30Z
2022-08-01T19:24:37Z
REF: re-use convert_reso
diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index bfccedba9431e..c1936e34cf8d0 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -109,3 +109,10 @@ cdef bint cmp_dtstructs(npy_datetimestruct* left, npy_datetimestruct* right, int cdef get_implementation_bounds( NPY_DATETIMEUNIT reso, npy_datetimestruct *lower, npy_datetimestruct *upper ) + +cdef int64_t convert_reso( + int64_t value, + NPY_DATETIMEUNIT from_reso, + NPY_DATETIMEUNIT to_reso, + bint round_ok, +) except? -1 diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index 5f8bad8398076..d8c176e6d8ac1 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -541,5 +541,59 @@ cdef int64_t get_conversion_factor(NPY_DATETIMEUNIT from_unit, NPY_DATETIMEUNIT return 1000 * get_conversion_factor(NPY_DATETIMEUNIT.NPY_FR_fs, to_unit) elif from_unit == NPY_DATETIMEUNIT.NPY_FR_fs: return 1000 * get_conversion_factor(NPY_DATETIMEUNIT.NPY_FR_as, to_unit) + + +cdef int64_t convert_reso( + int64_t value, + NPY_DATETIMEUNIT from_reso, + NPY_DATETIMEUNIT to_reso, + bint round_ok, +) except? -1: + cdef: + int64_t res_value, mult, div, mod + + if from_reso == to_reso: + return value + + elif to_reso < from_reso: + # e.g. ns -> us, no risk of overflow, but can be lossy rounding + mult = get_conversion_factor(to_reso, from_reso) + div, mod = divmod(value, mult) + if mod > 0 and not round_ok: + raise ValueError("Cannot losslessly convert units") + + # Note that when mod > 0, we follow np.timedelta64 in always + # rounding down. + res_value = div + + elif ( + from_reso == NPY_FR_Y + or from_reso == NPY_FR_M + or to_reso == NPY_FR_Y + or to_reso == NPY_FR_M + ): + # Converting by multiplying isn't _quite_ right bc the number of + # seconds in a month/year isn't fixed. + res_value = _convert_reso_with_dtstruct(value, from_reso, to_reso) + else: - raise ValueError(from_unit, to_unit) + # e.g. ns -> us, risk of overflow, but no risk of lossy rounding + mult = get_conversion_factor(from_reso, to_reso) + with cython.overflowcheck(True): + # Note: caller is responsible for re-raising as OutOfBoundsTimedelta + res_value = value * mult + + return res_value + + +cdef int64_t _convert_reso_with_dtstruct( + int64_t value, + NPY_DATETIMEUNIT from_unit, + NPY_DATETIMEUNIT to_unit, +) except? -1: + cdef: + npy_datetimestruct dts + + pandas_datetime_to_datetimestruct(value, from_unit, &dts) + check_dts_bounds(&dts, to_unit) + return npy_datetimestruct_to_datetime(to_unit, &dts) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index c64a9fb4d9c36..39458c10ad35b 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -47,6 +47,7 @@ from pandas._libs.tslibs.np_datetime cimport ( NPY_FR_ns, cmp_dtstructs, cmp_scalar, + convert_reso, get_conversion_factor, get_datetime64_unit, get_timedelta64_value, @@ -57,7 +58,10 @@ from pandas._libs.tslibs.np_datetime cimport ( pandas_timedeltastruct, ) -from pandas._libs.tslibs.np_datetime import OutOfBoundsTimedelta +from pandas._libs.tslibs.np_datetime import ( + OutOfBoundsDatetime, + OutOfBoundsTimedelta, +) from pandas._libs.tslibs.offsets cimport is_tick_object from pandas._libs.tslibs.util cimport ( @@ -240,6 +244,11 @@ cpdef int64_t delta_to_nanoseconds( elif is_timedelta64_object(delta): in_reso = get_datetime64_unit(delta) + if in_reso == NPY_DATETIMEUNIT.NPY_FR_Y or in_reso == NPY_DATETIMEUNIT.NPY_FR_M: + raise ValueError( + "delta_to_nanoseconds does not support Y or M units, " + "as their duration in nanoseconds is ambiguous." + ) n = get_timedelta64_value(delta) elif PyDelta_Check(delta): @@ -256,26 +265,15 @@ cpdef int64_t delta_to_nanoseconds( else: raise TypeError(type(delta)) - if reso < in_reso: - # e.g. ns -> us - factor = get_conversion_factor(reso, in_reso) - div, mod = divmod(n, factor) - if mod > 0 and not round_ok: - raise ValueError("Cannot losslessly convert units") - - # Note that when mod > 0, we follow np.timedelta64 in always - # rounding down. - value = div - else: - factor = get_conversion_factor(in_reso, reso) - try: - with cython.overflowcheck(True): - value = n * factor - except OverflowError as err: - unit_str = npy_unit_to_abbrev(reso) - raise OutOfBoundsTimedelta( - f"Cannot cast {str(delta)} to unit={unit_str} without overflow." - ) from err + try: + return convert_reso(n, in_reso, reso, round_ok=round_ok) + except (OutOfBoundsDatetime, OverflowError) as err: + # Catch OutOfBoundsDatetime bc convert_reso can call check_dts_bounds + # for Y/M-resolution cases + unit_str = npy_unit_to_abbrev(reso) + raise OutOfBoundsTimedelta( + f"Cannot cast {str(delta)} to unit={unit_str} without overflow." + ) from err return value @@ -1538,21 +1536,7 @@ cdef class _Timedelta(timedelta): if reso == self._reso: return self - if reso < self._reso: - # e.g. ns -> us - mult = get_conversion_factor(reso, self._reso) - div, mod = divmod(self.value, mult) - if mod > 0 and not round_ok: - raise ValueError("Cannot losslessly convert units") - - # Note that when mod > 0, we follow np.timedelta64 in always - # rounding down. - value = div - else: - mult = get_conversion_factor(self._reso, reso) - with cython.overflowcheck(True): - # Note: caller is responsible for re-raising as OutOfBoundsTimedelta - value = self.value * mult + value = convert_reso(self.value, self._reso, reso, round_ok=round_ok) return type(self)._from_value_and_reso(value, reso=reso) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 3cf9c9bcda538..840b7a86389c1 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -82,6 +82,7 @@ from pandas._libs.tslibs.np_datetime cimport ( NPY_FR_ns, cmp_dtstructs, cmp_scalar, + convert_reso, get_conversion_factor, get_datetime64_unit, get_datetime64_value, @@ -1043,7 +1044,6 @@ cdef class _Timestamp(ABCTimestamp): # ----------------------------------------------------------------- # Conversion Methods - # TODO: share with _Timedelta? @cython.cdivision(False) cdef _Timestamp _as_reso(self, NPY_DATETIMEUNIT reso, bint round_ok=True): cdef: @@ -1052,21 +1052,7 @@ cdef class _Timestamp(ABCTimestamp): if reso == self._reso: return self - if reso < self._reso: - # e.g. ns -> us - mult = get_conversion_factor(reso, self._reso) - div, mod = divmod(self.value, mult) - if mod > 0 and not round_ok: - raise ValueError("Cannot losslessly convert units") - - # Note that when mod > 0, we follow np.datetime64 in always - # rounding down. - value = div - else: - mult = get_conversion_factor(self._reso, reso) - with cython.overflowcheck(True): - # Note: caller is responsible for re-raising as OutOfBoundsDatetime - value = self.value * mult + value = convert_reso(self.value, self._reso, reso, round_ok=round_ok) return type(self)._from_value_and_reso(value, reso=reso, tz=self.tzinfo) def _as_unit(self, str unit, bint round_ok=True): diff --git a/pandas/tests/tslibs/test_timedeltas.py b/pandas/tests/tslibs/test_timedeltas.py index bb1efe38ea7c4..36ca02d32dbbd 100644 --- a/pandas/tests/tslibs/test_timedeltas.py +++ b/pandas/tests/tslibs/test_timedeltas.py @@ -56,14 +56,19 @@ def test_delta_to_nanoseconds_error(): def test_delta_to_nanoseconds_td64_MY_raises(): + msg = ( + "delta_to_nanoseconds does not support Y or M units, " + "as their duration in nanoseconds is ambiguous" + ) + td = np.timedelta64(1234, "Y") - with pytest.raises(ValueError, match="0, 10"): + with pytest.raises(ValueError, match=msg): delta_to_nanoseconds(td) td = np.timedelta64(1234, "M") - with pytest.raises(ValueError, match="1, 10"): + with pytest.raises(ValueError, match=msg): delta_to_nanoseconds(td)
- [ ] 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/47807
2022-07-20T21:58:23Z
2022-07-21T17:05:38Z
2022-07-21T17:05:38Z
2022-07-21T17:21:15Z
CI/TYP: bump mypy and pyright
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e4ab74091d6b6..dbddba57ef21c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -93,7 +93,7 @@ repos: types: [python] stages: [manual] additional_dependencies: &pyright_dependencies - - pyright@1.1.262 + - pyright@1.1.264 - id: pyright_reportGeneralTypeIssues # note: assumes python env is setup and activated name: pyright reportGeneralTypeIssues diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index d138ebb9c02a3..3d608f9e42cdf 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -418,7 +418,7 @@ If installed, we now require: +=================+=================+==========+=========+ | numpy | 1.19.5 | X | X | +-----------------+-----------------+----------+---------+ -| mypy (dev) | 0.960 | | X | +| mypy (dev) | 0.971 | | X | +-----------------+-----------------+----------+---------+ | beautifulsoup4 | 4.9.3 | | X | +-----------------+-----------------+----------+---------+ diff --git a/environment.yml b/environment.yml index fd0822b13984e..ec2e0a3860432 100644 --- a/environment.yml +++ b/environment.yml @@ -88,7 +88,7 @@ dependencies: - flake8-bugbear=21.3.2 # used by flake8, find likely bugs - flake8-comprehensions=3.7.0 # used by flake8, linting of unnecessary comprehensions - isort>=5.2.1 # check that imports are in the right order - - mypy=0.960 + - mypy=0.971 - pre-commit>=2.15.0 - pycodestyle # used by flake8 - pyupgrade diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 90824ce8d856f..ff3f259f49955 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -774,7 +774,9 @@ def __init__( @disallow(_unsupported_nodes | _python_not_supported | frozenset(["Not"])) class PythonExprVisitor(BaseExprVisitor): - def __init__(self, env, engine, parser, preparser=lambda x: x) -> None: + def __init__( + self, env, engine, parser, preparser=lambda source, f=None: source + ) -> None: super().__init__(env, engine, parser, preparser=preparser) diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index db5f28e2ae6c1..e331fc89f69b7 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -10,6 +10,7 @@ from typing import ( Callable, Iterable, + Literal, ) import numpy as np @@ -552,7 +553,7 @@ class UnaryOp(Op): * If no function associated with the passed operator token is found. """ - def __init__(self, op: str, operand) -> None: + def __init__(self, op: Literal["+", "-", "~", "not"], operand) -> None: super().__init__(op, (operand,)) self.operand = operand diff --git a/requirements-dev.txt b/requirements-dev.txt index e1e98ef8ffe23..5a9647456cb0b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -67,7 +67,7 @@ flake8==4.0.1 flake8-bugbear==21.3.2 flake8-comprehensions==3.7.0 isort>=5.2.1 -mypy==0.960 +mypy==0.971 pre-commit>=2.15.0 pycodestyle pyupgrade
No type changes this time (but there will be a few when numba allows us to use numpy 1.23).
https://api.github.com/repos/pandas-dev/pandas/pulls/47806
2022-07-20T21:33:36Z
2022-08-01T19:27:16Z
2022-08-01T19:27:16Z
2022-09-10T01:38:50Z
ENH/TST: Add isin, _hasna for ArrowExtensionArray
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 8957ea493e9ad..ee8192cfca1ec 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -18,6 +18,7 @@ from pandas.compat import ( pa_version_under1p01, pa_version_under2p0, + pa_version_under3p0, pa_version_under4p0, pa_version_under5p0, pa_version_under6p0, @@ -388,6 +389,10 @@ def __len__(self) -> int: """ return len(self._data) + @property + def _hasna(self) -> bool: + return self._data.null_count > 0 + def isna(self) -> npt.NDArray[np.bool_]: """ Boolean NumPy array indicating if each value is missing. @@ -425,6 +430,49 @@ def dropna(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT: else: return type(self)(pc.drop_null(self._data)) + def isin(self: ArrowExtensionArrayT, values) -> npt.NDArray[np.bool_]: + if pa_version_under2p0: + fallback_performancewarning(version="2") + return super().isin(values) + + # for an empty value_set pyarrow 3.0.0 segfaults and pyarrow 2.0.0 returns True + # for null values, so we short-circuit to return all False array. + if not len(values): + return np.zeros(len(self), dtype=bool) + + kwargs = {} + if pa_version_under3p0: + # in pyarrow 2.0.0 skip_null is ignored but is a required keyword and raises + # with unexpected keyword argument in pyarrow 3.0.0+ + kwargs["skip_null"] = True + + result = pc.is_in( + self._data, value_set=pa.array(values, from_pandas=True), **kwargs + ) + # pyarrow 2.0.0 returned nulls, so we explicitly specify dtype to convert nulls + # to False + return np.array(result, dtype=np.bool_) + + def _values_for_factorize(self) -> tuple[np.ndarray, Any]: + """ + Return an array and missing value suitable for factorization. + + Returns + ------- + values : ndarray + na_value : pd.NA + + Notes + ----- + The values returned by this method are also used in + :func:`pandas.util.hash_pandas_object`. + """ + if pa_version_under2p0: + values = self._data.to_pandas().values + else: + values = self._data.to_numpy() + return values, self.dtype.na_value + @doc(ExtensionArray.factorize) def factorize( self, @@ -622,8 +670,6 @@ def _concat_same_type( ------- ArrowExtensionArray """ - import pyarrow as pa - chunks = [array for ea in to_concat for array in ea._data.iterchunks()] arr = pa.chunked_array(chunks) return cls(arr)
- [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).
https://api.github.com/repos/pandas-dev/pandas/pulls/47805
2022-07-20T20:33:48Z
2022-07-22T01:26:18Z
2022-07-22T01:26:18Z
2022-07-22T01:40:20Z
TYP: Column.null_count is a Python int
diff --git a/pandas/core/exchange/column.py b/pandas/core/exchange/column.py index 538c1d061ef22..c2a1cfe766b22 100644 --- a/pandas/core/exchange/column.py +++ b/pandas/core/exchange/column.py @@ -96,7 +96,7 @@ def offset(self) -> int: return 0 @cache_readonly - def dtype(self): + def dtype(self) -> tuple[DtypeKind, int, str, str]: dtype = self._col.dtype if is_categorical_dtype(dtype): @@ -138,7 +138,7 @@ def _dtype_from_pandasdtype(self, dtype) -> tuple[DtypeKind, int, str, str]: # Not a NumPy dtype. Check if it's a categorical maybe raise ValueError(f"Data type {dtype} not supported by exchange protocol") - return (kind, dtype.itemsize * 8, dtype_to_arrow_c_fmt(dtype), dtype.byteorder) + return kind, dtype.itemsize * 8, dtype_to_arrow_c_fmt(dtype), dtype.byteorder @property def describe_categorical(self): @@ -181,10 +181,10 @@ def null_count(self) -> int: """ Number of null elements. Should always be known. """ - return self._col.isna().sum() + return self._col.isna().sum().item() @property - def metadata(self): + def metadata(self) -> dict[str, pd.Index]: """ Store specific metadata of the column. """ @@ -196,7 +196,7 @@ def num_chunks(self) -> int: """ return 1 - def get_chunks(self, n_chunks=None): + def get_chunks(self, n_chunks: int | None = None): """ Return an iterator yielding the chunks. See `DataFrame.get_chunks` for details on ``n_chunks``. diff --git a/pandas/tests/exchange/test_spec_conformance.py b/pandas/tests/exchange/test_spec_conformance.py index f5b8bb569f35e..392402871a5fd 100644 --- a/pandas/tests/exchange/test_spec_conformance.py +++ b/pandas/tests/exchange/test_spec_conformance.py @@ -24,7 +24,9 @@ def test_only_one_dtype(test_data, df_from_dict): column_size = len(test_data[columns[0]]) for column in columns: - assert dfX.get_column_by_name(column).null_count == 0 + null_count = dfX.get_column_by_name(column).null_count + assert null_count == 0 + assert isinstance(null_count, int) assert dfX.get_column_by_name(column).size == column_size assert dfX.get_column_by_name(column).offset == 0 @@ -49,6 +51,7 @@ def test_mixed_dtypes(df_from_dict): for column, kind in columns.items(): colX = dfX.get_column_by_name(column) assert colX.null_count == 0 + assert isinstance(colX.null_count, int) assert colX.size == 3 assert colX.offset == 0 @@ -62,6 +65,7 @@ def test_na_float(df_from_dict): dfX = df.__dataframe__() colX = dfX.get_column_by_name("a") assert colX.null_count == 1 + assert isinstance(colX.null_count, int) def test_noncategorical(df_from_dict):
- [x] closes #47789 (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). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. No whatsnew needed since the exchange protocol will be new in 1.5
https://api.github.com/repos/pandas-dev/pandas/pulls/47804
2022-07-20T17:12:56Z
2022-07-21T17:07:43Z
2022-07-21T17:07:43Z
2022-07-21T17:07:46Z
CLN: remove LegacyFoo from io.pytables
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..61e92f12e19af 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -321,6 +321,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - :meth:`pandas.Series.str.cat` now defaults to aligning ``others``, using ``join='left'`` (:issue:`27611`) - :meth:`pandas.Series.str.cat` does not accept list-likes *within* list-likes anymore (:issue:`27611`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) +- Removed support for legacy HDF5 formats (:issue:`29787`) - :func:`read_excel` removed support for "skip_footer" argument, use "skipfooter" instead (:issue:`18836`) - :meth:`DataFrame.to_records` no longer supports the argument "convert_datetime64" (:issue:`18902`) - Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index ba53d8cfd0de5..c38bc1e48b029 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -179,9 +179,6 @@ class DuplicateWarning(Warning): # storer class map _STORER_MAP = { - "Series": "LegacySeriesFixed", - "DataFrame": "LegacyFrameFixed", - "DataMatrix": "LegacyFrameFixed", "series": "SeriesFixed", "frame": "FrameFixed", } @@ -3083,35 +3080,6 @@ def write_array(self, key: str, value, items=None): getattr(self.group, key)._v_attrs.transposed = transposed -class LegacyFixed(GenericFixed): - def read_index_legacy( - self, key: str, start: Optional[int] = None, stop: Optional[int] = None - ): - node = getattr(self.group, key) - data = node[start:stop] - kind = node._v_attrs.kind - return _unconvert_index_legacy( - data, kind, encoding=self.encoding, errors=self.errors - ) - - -class LegacySeriesFixed(LegacyFixed): - def read(self, **kwargs): - kwargs = self.validate_read(kwargs) - index = self.read_index_legacy("index") - values = self.read_array("values") - return Series(values, index=index) - - -class LegacyFrameFixed(LegacyFixed): - def read(self, **kwargs): - kwargs = self.validate_read(kwargs) - index = self.read_index_legacy("index") - columns = self.read_index_legacy("columns") - values = self.read_array("values") - return DataFrame(values, index=index, columns=columns) - - class SeriesFixed(GenericFixed): pandas_kind = "series" attributes = ["name"] @@ -4139,35 +4107,7 @@ def write(self, **kwargs): raise NotImplementedError("WORKTable needs to implement write") -class LegacyTable(Table): - """ an appendable table: allow append/query/delete operations to a - (possibly) already existing appendable table this table ALLOWS - append (but doesn't require them), and stores the data in a format - that can be easily searched - - """ - - _indexables: Optional[List[IndexCol]] = [ - IndexCol(name="index", axis=1, pos=0), - IndexCol(name="column", axis=2, pos=1, index_kind="columns_kind"), - DataCol(name="fields", cname="values", kind_attr="fields", pos=2), - ] - table_type = "legacy" - ndim = 3 - - def write(self, **kwargs): - raise TypeError("write operations are not allowed on legacy tables!") - - def read(self, where=None, columns=None, **kwargs): - """we have n indexable columns, with an arbitrary number of data - axes - """ - - if not self.read_axes(where=where, **kwargs): - return None - - -class AppendableTable(LegacyTable): +class AppendableTable(Table): """ support the new appendable table formats """ _indexables = None @@ -4866,21 +4806,6 @@ def _unconvert_index(data, kind, encoding=None, errors="strict"): return index -def _unconvert_index_legacy(data, kind, legacy=False, encoding=None, errors="strict"): - kind = _ensure_decoded(kind) - if kind == "datetime": - index = to_datetime(data) - elif kind in ("integer"): - index = np.asarray(data, dtype=object) - elif kind in ("string"): - index = _unconvert_string_array( - data, nan_rep=None, encoding=encoding, errors=errors - ) - else: # pragma: no cover - raise ValueError("unrecognized index type {kind}".format(kind=kind)) - return index - - def _convert_string_array(data, encoding, errors, itemsize=None): """ we take a string-like that is object dtype and coerce to a fixed size
https://api.github.com/repos/pandas-dev/pandas/pulls/29787
2019-11-22T01:41:46Z
2019-11-22T15:27:33Z
2019-11-22T15:27:33Z
2019-11-22T16:36:30Z
DEPR: change pd.concat sort=None to sort=False
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..ec8c6ab1451a5 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -341,6 +341,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed previously deprecated "order" argument from :func:`factorize` (:issue:`19751`) - Removed previously deprecated "v" argument from :meth:`FrozenNDarray.searchsorted`, use "value" instead (:issue:`22672`) - :func:`read_stata` and :meth:`DataFrame.to_stata` no longer supports the "encoding" argument (:issue:`21400`) +- In :func:`concat` the default value for ``sort`` has been changed from ``None`` to ``False`` (:issue:`20613`) - Removed previously deprecated "raise_conflict" argument from :meth:`DataFrame.update`, use "errors" instead (:issue:`23585`) - Removed previously deprecated keyword "n" from :meth:`DatetimeIndex.shift`, :meth:`TimedeltaIndex.shift`, :meth:`PeriodIndex.shift`, use "periods" instead (:issue:`22458`) - diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index f650a62bc5b74..c3de1321404b4 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -1,6 +1,5 @@ import textwrap from typing import List, Set -import warnings from pandas._libs import NaT, lib @@ -211,12 +210,6 @@ def conv(i): index = indexes[0] for other in indexes[1:]: if not index.equals(other): - - if sort is None: - # TODO: remove once pd.concat sort default changes - warnings.warn(_sort_msg, FutureWarning, stacklevel=8) - sort = True - return _unique_indices(indexes) name = get_consensus_names(indexes)[0] diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index c2322ae626cfd..853a638bdb277 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -37,7 +37,7 @@ def concat( levels=None, names=None, verify_integrity: bool = False, - sort=None, + sort: bool = False, copy: bool = True, ): """ @@ -82,18 +82,16 @@ def concat( verify_integrity : bool, default False Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation. - sort : bool, default None + sort : bool, default False Sort non-concatenation axis if it is not already aligned when `join` - is 'outer'. The current default of sorting is deprecated and will - change to not-sorting in a future version of pandas. - - Explicitly pass ``sort=True`` to silence the warning and sort. - Explicitly pass ``sort=False`` to silence the warning and not sort. - + is 'outer'. This has no effect when ``join='inner'``, which already preserves the order of the non-concatenation axis. .. versionadded:: 0.23.0 + .. versionchanged:: 1.0.0 + + Changed to not sort by default. copy : bool, default True If False, do not copy data unnecessarily. diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index 220968d4b3d29..a0cbc1456afa4 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -195,7 +195,7 @@ def test_join_left_sequence_non_unique_index(): tm.assert_frame_equal(joined, expected) -@pytest.mark.parametrize("sort_kw", [True, False, None]) +@pytest.mark.parametrize("sort_kw", [True, False]) def test_suppress_future_warning_with_sort_kw(sort_kw): a = DataFrame({"col1": [1, 2]}, index=["c", "a"]) @@ -213,12 +213,6 @@ def test_suppress_future_warning_with_sort_kw(sort_kw): if sort_kw is False: expected = expected.reindex(index=["c", "a", "b"]) - if sort_kw is None: - # only warn if not explicitly specified - ctx = tm.assert_produces_warning(FutureWarning, check_stacklevel=False) - else: - ctx = tm.assert_produces_warning(None, check_stacklevel=False) - - with ctx: + with tm.assert_produces_warning(None, check_stacklevel=False): result = a.join([b, c], how="outer", sort=sort_kw) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 323b3126c2461..8be05e9f154de 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -37,16 +37,6 @@ def sort(request): return request.param -@pytest.fixture(params=[True, False, None]) -def sort_with_none(request): - """Boolean sort keyword for concat and DataFrame.append. - - Includes the default of None - """ - # TODO: Replace with sort once keyword changes. - return request.param - - class TestConcatAppendCommon: """ Test common dtype coercion rules between concat and append. @@ -775,15 +765,13 @@ def test_concat_join_axes_deprecated(self, axis): ) expected = pd.concat([one, two], axis=1, sort=False).reindex(index=two.index) - with tm.assert_produces_warning(expected_warning=FutureWarning): - result = pd.concat([one, two], axis=1, sort=False, join_axes=[two.index]) + result = pd.concat([one, two], axis=1, sort=False, join_axes=[two.index]) tm.assert_frame_equal(result, expected) expected = pd.concat([one, two], axis=0, sort=False).reindex( columns=two.columns ) - with tm.assert_produces_warning(expected_warning=FutureWarning): - result = pd.concat([one, two], axis=0, sort=False, join_axes=[two.columns]) + result = pd.concat([one, two], axis=0, sort=False, join_axes=[two.columns]) tm.assert_frame_equal(result, expected) @@ -875,27 +863,19 @@ def test_append_records(self): tm.assert_frame_equal(result, expected) # rewrite sort fixture, since we also want to test default of None - def test_append_sorts(self, sort_with_none): + def test_append_sorts(self, sort): df1 = pd.DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) df2 = pd.DataFrame({"a": [1, 2], "c": [3, 4]}, index=[2, 3]) - if sort_with_none is None: - # only warn if not explicitly specified - # don't check stacklevel since its set for concat, and append - # has an extra stack. - ctx = tm.assert_produces_warning(FutureWarning, check_stacklevel=False) - else: - ctx = tm.assert_produces_warning(None) - - with ctx: - result = df1.append(df2, sort=sort_with_none) + with tm.assert_produces_warning(None): + result = df1.append(df2, sort=sort) # for None / True expected = pd.DataFrame( {"b": [1, 2, None, None], "a": [1, 2, 1, 2], "c": [None, None, 3, 4]}, columns=["a", "b", "c"], ) - if sort_with_none is False: + if sort is False: expected = expected[["b", "a", "c"]] tm.assert_frame_equal(result, expected) @@ -2629,7 +2609,7 @@ def test_concat_empty_and_non_empty_series_regression(): tm.assert_series_equal(result, expected) -def test_concat_sorts_columns(sort_with_none): +def test_concat_sorts_columns(sort): # GH-4588 df1 = pd.DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) df2 = pd.DataFrame({"a": [3, 4], "c": [5, 6]}) @@ -2640,22 +2620,16 @@ def test_concat_sorts_columns(sort_with_none): columns=["a", "b", "c"], ) - if sort_with_none is False: + if sort is False: expected = expected[["b", "a", "c"]] - if sort_with_none is None: - # only warn if not explicitly specified - ctx = tm.assert_produces_warning(FutureWarning) - else: - ctx = tm.assert_produces_warning(None) - # default - with ctx: - result = pd.concat([df1, df2], ignore_index=True, sort=sort_with_none) + with tm.assert_produces_warning(None): + result = pd.concat([df1, df2], ignore_index=True, sort=sort) tm.assert_frame_equal(result, expected) -def test_concat_sorts_index(sort_with_none): +def test_concat_sorts_index(sort): df1 = pd.DataFrame({"a": [1, 2, 3]}, index=["c", "a", "b"]) df2 = pd.DataFrame({"b": [1, 2]}, index=["a", "b"]) @@ -2663,22 +2637,16 @@ def test_concat_sorts_index(sort_with_none): expected = pd.DataFrame( {"a": [2, 3, 1], "b": [1, 2, None]}, index=["a", "b", "c"], columns=["a", "b"] ) - if sort_with_none is False: + if sort is False: expected = expected.loc[["c", "a", "b"]] - if sort_with_none is None: - # only warn if not explicitly specified - ctx = tm.assert_produces_warning(FutureWarning) - else: - ctx = tm.assert_produces_warning(None) - # Warn and sort by default - with ctx: - result = pd.concat([df1, df2], axis=1, sort=sort_with_none) + with tm.assert_produces_warning(None): + result = pd.concat([df1, df2], axis=1, sort=sort) tm.assert_frame_equal(result, expected) -def test_concat_inner_sort(sort_with_none): +def test_concat_inner_sort(sort): # https://github.com/pandas-dev/pandas/pull/20613 df1 = pd.DataFrame({"a": [1, 2], "b": [1, 2], "c": [1, 2]}, columns=["b", "a", "c"]) df2 = pd.DataFrame({"a": [1, 2], "b": [3, 4]}, index=[3, 4]) @@ -2686,12 +2654,10 @@ def test_concat_inner_sort(sort_with_none): with tm.assert_produces_warning(None): # unset sort should *not* warn for inner join # since that never sorted - result = pd.concat( - [df1, df2], sort=sort_with_none, join="inner", ignore_index=True - ) + result = pd.concat([df1, df2], sort=sort, join="inner", ignore_index=True) expected = pd.DataFrame({"b": [1, 2, 3, 4], "a": [1, 2, 1, 2]}, columns=["b", "a"]) - if sort_with_none is True: + if sort is True: expected = expected[["a", "b"]] tm.assert_frame_equal(result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/29786
2019-11-22T00:59:02Z
2019-11-25T23:38:55Z
2019-11-25T23:38:55Z
2019-11-25T23:40:33Z
CLN: catch ValueError instead of Exception in io.html
diff --git a/pandas/io/html.py b/pandas/io/html.py index ed2b21994fdca..5f38f866e1643 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -896,7 +896,7 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs): try: tables = p.parse_tables() - except Exception as caught: + except ValueError as caught: # if `io` is an io-like object, check if it's seekable # and try to rewind it before trying the next parser if hasattr(io, "seekable") and io.seekable():
Broken off from #28862.
https://api.github.com/repos/pandas-dev/pandas/pulls/29785
2019-11-21T23:07:29Z
2019-11-22T15:31:18Z
2019-11-22T15:31:18Z
2019-11-22T16:33:34Z
DEPS: Removing unused pytest-mock
diff --git a/ci/deps/azure-36-32bit.yaml b/ci/deps/azure-36-32bit.yaml index f3e3d577a7a33..cf3fca307481f 100644 --- a/ci/deps/azure-36-32bit.yaml +++ b/ci/deps/azure-36-32bit.yaml @@ -8,7 +8,6 @@ dependencies: # tools ### Cython 0.29.13 and pytest 5.0.1 for 32 bits are not available with conda, installing below with pip instead - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml index 3baf975afc096..c3c94e365c259 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-36-locale.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml index 01741e9b65a7a..46ddd44931848 100644 --- a/ci/deps/azure-36-locale_slow.yaml +++ b/ci/deps/azure-36-locale_slow.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-36-minimum_versions.yaml b/ci/deps/azure-36-minimum_versions.yaml index 1e32ef7482be3..ff1095005fa85 100644 --- a/ci/deps/azure-36-minimum_versions.yaml +++ b/ci/deps/azure-36-minimum_versions.yaml @@ -9,7 +9,6 @@ dependencies: - cython=0.29.13 - pytest=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 26446ab5365b1..3319afed173b5 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 3264df5944e35..a04bdc2448bce 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -8,7 +8,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-36.yaml index 48ba87d26f53d..831b68d0bb4d3 100644 --- a/ci/deps/azure-macos-36.yaml +++ b/ci/deps/azure-macos-36.yaml @@ -8,7 +8,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml index e3ad1d8371623..3aa261a57f2d4 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-36.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 07e134b054c10..928896efd5fc4 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-azurepipelines diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml index 9148e0d4b29d9..170edd90ea3d7 100644 --- a/ci/deps/travis-36-cov.yaml +++ b/ci/deps/travis-36-cov.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 - pytest-cov # this is only needed in the coverage build diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index 3199ee037bc0a..5dc1e4524ec86 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 # pandas dependencies diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml index eab374c96772c..1dfd90d0904ac 100644 --- a/ci/deps/travis-36-slow.yaml +++ b/ci/deps/travis-36-slow.yaml @@ -9,7 +9,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 # pandas dependencies diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index 7b75a427a4954..6826a9d072ff3 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -10,7 +10,6 @@ dependencies: - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - - pytest-mock - hypothesis>=3.58.0 # pandas dependencies
May be I'm missing something, but I don't think we use `pytest-mock` (a grep didn't find anything by `mocker`), but we have it in almost all builds. The CI should tell if I'm wrong.
https://api.github.com/repos/pandas-dev/pandas/pulls/29784
2019-11-21T22:06:08Z
2019-11-22T01:14:47Z
2019-11-22T01:14:47Z
2019-11-22T01:14:47Z
DEPS: Unifying version of pytest-xdist across builds
diff --git a/ci/deps/travis-38.yaml b/ci/deps/travis-38.yaml index 88da1331b463a..828f02596a70e 100644 --- a/ci/deps/travis-38.yaml +++ b/ci/deps/travis-38.yaml @@ -8,7 +8,7 @@ dependencies: # tools - cython>=0.29.13 - pytest>=5.0.1 - - pytest-xdist>=1.29.0 # The rest of the builds use >=1.21, and use pytest-mock + - pytest-xdist>=1.21 - hypothesis>=3.58.0 # pandas dependencies
We use `pytest-xdist>=1.21` in all builds except this one. Using the same for the 3.8 build, which was introduced in parallel as the standardization of dependencies. xref: https://github.com/pandas-dev/pandas/pull/29678#discussion_r348873095
https://api.github.com/repos/pandas-dev/pandas/pulls/29783
2019-11-21T22:04:20Z
2019-11-22T15:25:53Z
2019-11-22T15:25:53Z
2019-11-22T15:25:56Z
DOC: Updating documentation of new required pytest version
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 042d6926d84f5..d7b3e159f8ce7 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -946,7 +946,7 @@ extensions in `numpy.testing .. note:: - The earliest supported pytest version is 4.0.2. + The earliest supported pytest version is 5.0.1. Writing tests ~~~~~~~~~~~~~ diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 663948fd46cf6..3ba3a2fd4be1b 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -177,7 +177,7 @@ pandas is equipped with an exhaustive set of unit tests, covering about 97% of the code base as of this writing. To run it on your machine to verify that everything is working (and that you have all of the dependencies, soft and hard, installed), make sure you have `pytest -<http://docs.pytest.org/en/latest/>`__ >= 4.0.2 and `Hypothesis +<http://docs.pytest.org/en/latest/>`__ >= 5.0.1 and `Hypothesis <https://hypothesis.readthedocs.io/>`__ >= 3.58, then run: :: diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..6cbf655db4a44 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -253,6 +253,7 @@ Other API changes See :ref:`units registration <whatsnew_1000.matplotlib_units>` for more. - :meth:`Series.dropna` has dropped its ``**kwargs`` argument in favor of a single ``how`` parameter. Supplying anything else than ``how`` to ``**kwargs`` raised a ``TypeError`` previously (:issue:`29388`) +- When testing pandas, the new minimum required version of pytest is 5.0.1 (:issue:`29664`) - diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index fc66502710b0c..ce9079ce8864d 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -18,6 +18,7 @@ "pandas_gbq": "0.8.0", "pyarrow": "0.9.0", "pytables": "3.4.2", + "pytest": "5.0.1", "s3fs": "0.3.0", "scipy": "0.19.0", "sqlalchemy": "1.1.4", diff --git a/pandas/util/_tester.py b/pandas/util/_tester.py index 0f5324c8d02ba..7822ecdeeb4d8 100644 --- a/pandas/util/_tester.py +++ b/pandas/util/_tester.py @@ -11,7 +11,7 @@ def test(extra_args=None): try: import pytest except ImportError: - raise ImportError("Need pytest>=4.0.2 to run tests") + raise ImportError("Need pytest>=5.0.1 to run tests") try: import hypothesis # noqa except ImportError:
Follow up of #29678 @jreback I think `show_versions` gets the version by importing the module. Correct me if I'm wrong, but I didn't see anything to update there.
https://api.github.com/repos/pandas-dev/pandas/pulls/29782
2019-11-21T22:02:34Z
2019-11-22T15:26:49Z
2019-11-22T15:26:49Z
2019-11-22T15:26:53Z
CLN - Change string formatting in plotting
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index da1e06dccc65d..beb276478070e 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -736,26 +736,23 @@ def _get_call_args(backend_name, data, args, kwargs): ] else: raise TypeError( - ( - "Called plot accessor for type {}, expected Series or DataFrame" - ).format(type(data).__name__) + f"Called plot accessor for type {type(data).__name__}, " + "expected Series or DataFrame" ) if args and isinstance(data, ABCSeries): + positional_args = str(args)[1:-1] + keyword_args = ", ".join( + f"{name}={value!r}" for (name, default), value in zip(arg_def, args) + ) msg = ( "`Series.plot()` should not be called with positional " "arguments, only keyword arguments. The order of " "positional arguments will change in the future. " - "Use `Series.plot({})` instead of `Series.plot({})`." - ) - positional_args = str(args)[1:-1] - keyword_args = ", ".join( - "{}={!r}".format(name, value) - for (name, default), value in zip(arg_def, args) - ) - warnings.warn( - msg.format(keyword_args, positional_args), FutureWarning, stacklevel=3 + f"Use `Series.plot({keyword_args})` instead of " + f"`Series.plot({positional_args})`." ) + warnings.warn(msg, FutureWarning, stacklevel=3) pos_args = {name: value for value, (name, _) in zip(args, arg_def)} if backend_name == "pandas.plotting._matplotlib": @@ -782,7 +779,7 @@ def __call__(self, *args, **kwargs): return plot_backend.plot(self._parent, x=x, y=y, kind=kind, **kwargs) if kind not in self._all_kinds: - raise ValueError("{} is not a valid plot kind".format(kind)) + raise ValueError(f"{kind} is not a valid plot kind") # The original data structured can be transformed before passed to the # backend. For example, for DataFrame is common to set the index as the @@ -796,14 +793,13 @@ def __call__(self, *args, **kwargs): if isinstance(data, ABCDataFrame): return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs) else: - raise ValueError( - ("plot kind {} can only be used for data frames").format(kind) - ) + raise ValueError(f"plot kind {kind} can only be used for data frames") elif kind in self._series_kinds: if isinstance(data, ABCDataFrame): if y is None and kwargs.get("subplots") is False: - msg = "{} requires either y column or 'subplots=True'" - raise ValueError(msg.format(kind)) + raise ValueError( + f"{kind} requires either y column or 'subplots=True'" + ) elif y is not None: if is_integer(y) and not data.columns.holds_integer(): y = data.columns[y] @@ -1639,12 +1635,11 @@ def _find_backend(backend: str): _backends[backend] = module return module - msg = ( - "Could not find plotting backend '{name}'. Ensure that you've installed the " - "package providing the '{name}' entrypoint, or that the package has a" + raise ValueError( + f"Could not find plotting backend '{backend}'. Ensure that you've installed " + f"the package providing the '{backend}' entrypoint, or that the package has a " "top-level `.plot` method." ) - raise ValueError(msg.format(name=backend)) def _get_plot_backend(backend=None): diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 274f06cd3ec1d..7bcca659ee3f6 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -74,9 +74,8 @@ def _validate_color_args(self): for key, values in self.color.items(): if key not in valid_keys: raise ValueError( - "color dict contains invalid " - "key '{0}' " - "The key must be either {1}".format(key, valid_keys) + f"color dict contains invalid key '{key}'. " + f"The key must be either {valid_keys}" ) else: self.color = None @@ -217,7 +216,7 @@ def _grouped_plot_by_column( result = axes byline = by[0] if len(by) == 1 else by - fig.suptitle("Boxplot grouped by {byline}".format(byline=byline)) + fig.suptitle(f"Boxplot grouped by {byline}") fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) return result @@ -268,9 +267,8 @@ def _get_colors(): result[key_to_index[key]] = value else: raise ValueError( - "color dict contains invalid " - "key '{0}' " - "The key must be either {1}".format(key, valid_keys) + f"color dict contains invalid key '{key}'. " + f"The key must be either {valid_keys}" ) else: result.fill(colors) diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 4b0ba2bd423df..feb895a099da5 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -125,7 +125,7 @@ def time2num(d): if isinstance(d, str): parsed = tools.to_datetime(d) if not isinstance(parsed, datetime): - raise ValueError("Could not parse time {d}".format(d=d)) + raise ValueError(f"Could not parse time {d}") return _to_ordinalf(parsed.time()) if isinstance(d, pydt.time): return _to_ordinalf(d) @@ -244,7 +244,7 @@ def get_datevalue(date, freq): return date elif date is None: return None - raise ValueError("Unrecognizable date '{date}'".format(date=date)) + raise ValueError(f"Unrecognizable date '{date}'") def _dt_to_float_ordinal(dt): @@ -421,12 +421,10 @@ def __call__(self): if estimate > self.MAXTICKS * 2: raise RuntimeError( - ( - "MillisecondLocator estimated to generate " - "{estimate:d} ticks from {dmin} to {dmax}: " - "exceeds Locator.MAXTICKS" - "* 2 ({arg:d}) " - ).format(estimate=estimate, dmin=dmin, dmax=dmax, arg=self.MAXTICKS * 2) + "MillisecondLocator estimated to generate " + f"{estimate:d} ticks from {dmin} to {dmax}: " + "exceeds Locator.MAXTICKS" + f"* 2 ({self.MAXTICKS * 2:d}) " ) interval = self._get_interval() @@ -582,7 +580,7 @@ def _daily_finder(vmin, vmax, freq): elif freq == FreqGroup.FR_HR: periodsperday = 24 else: # pragma: no cover - raise ValueError("unexpected frequency: {freq}".format(freq=freq)) + raise ValueError(f"unexpected frequency: {freq}") periodsperyear = 365 * periodsperday periodspermonth = 28 * periodsperday @@ -941,8 +939,7 @@ def get_finder(freq): elif (freq >= FreqGroup.FR_BUS) or fgroup == FreqGroup.FR_WK: return _daily_finder else: # pragma: no cover - errmsg = "Unsupported frequency: {freq}".format(freq=freq) - raise NotImplementedError(errmsg) + raise NotImplementedError(f"Unsupported frequency: {freq}") class TimeSeries_DateLocator(Locator): @@ -1119,11 +1116,11 @@ def format_timedelta_ticks(x, pos, n_decimals): h, m = divmod(m, 60) d, h = divmod(h, 24) decimals = int(ns * 10 ** (n_decimals - 9)) - s = r"{:02d}:{:02d}:{:02d}".format(int(h), int(m), int(s)) + s = f"{int(h):02d}:{int(m):02d}:{int(s):02d}" if n_decimals > 0: - s += ".{{:0{:0d}d}}".format(n_decimals).format(decimals) + s += f".{decimals:0{n_decimals}d}" if d != 0: - s = "{:d} days ".format(int(d)) + s + s = f"{int(d):d} days {s}" return s def __call__(self, x, pos=0): diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 5341dc3a6338a..20af25af7bc88 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -349,8 +349,7 @@ def _setup_subplots(self): if input_log - valid_log: invalid_log = next(iter((input_log - valid_log))) raise ValueError( - "Boolean, None and 'sym' are valid options," - " '{}' is given.".format(invalid_log) + f"Boolean, None and 'sym' are valid options, '{invalid_log}' is given." ) if self.logx is True or self.loglog is True: @@ -501,14 +500,13 @@ def _adorn_subplots(self): if self.subplots: if is_list_like(self.title): if len(self.title) != self.nseries: - msg = ( + raise ValueError( "The length of `title` must equal the number " "of columns if using `title` of type `list` " "and `subplots=True`.\n" - "length of title = {}\n" - "number of columns = {}" - ).format(len(self.title), self.nseries) - raise ValueError(msg) + f"length of title = {len(self.title)}\n" + f"number of columns = {self.nseries}" + ) for (ax, title) in zip(self.axes, self.title): ax.set_title(title) @@ -813,11 +811,10 @@ def match_labels(data, e): or (err_shape[1] != 2) or (err_shape[2] != len(self.data)) ): - msg = ( + raise ValueError( "Asymmetrical error bars should be provided " - + "with the shape (%u, 2, %u)" % (self.nseries, len(self.data)) + f"with the shape ({self.nseries}, 2, {len(self.data)})" ) - raise ValueError(msg) # broadcast errors to each data series if len(err) == 1: @@ -827,7 +824,7 @@ def match_labels(data, e): err = np.tile([err], (self.nseries, len(self.data))) else: - msg = "No valid {label} detected".format(label=label) + msg = f"No valid {label} detected" raise ValueError(msg) return err @@ -1178,7 +1175,7 @@ def _get_stacked_values(cls, ax, stacking_id, values, label): raise ValueError( "When stacked is True, each column must be either " "all positive or negative." - "{0} contains both positive and negative values".format(label) + f"{label} contains both positive and negative values" ) @classmethod @@ -1473,7 +1470,7 @@ class PiePlot(MPLPlot): def __init__(self, data, kind=None, **kwargs): data = data.fillna(value=0) if (data < 0).any().any(): - raise ValueError("{0} doesn't allow negative values".format(kind)) + raise ValueError(f"{kind} doesn't allow negative values") MPLPlot.__init__(self, data, kind=kind, **kwargs) def _args_adjust(self): diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 6d2363668e650..0720f544203f7 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -395,7 +395,7 @@ def lag_plot(series, lag=1, ax=None, **kwds): if ax is None: ax = plt.gca() ax.set_xlabel("y(t)") - ax.set_ylabel("y(t + {lag})".format(lag=lag)) + ax.set_ylabel(f"y(t + {lag})") ax.scatter(y1, y2, **kwds) return ax diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 927b9cf4e392a..fd69265b18a5b 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -20,7 +20,7 @@ def _get_standard_colors( cmap = colormap colormap = cm.get_cmap(colormap) if colormap is None: - raise ValueError("Colormap {0} is not recognized".format(cmap)) + raise ValueError(f"Colormap {cmap} is not recognized") colors = [colormap(num) for num in np.linspace(0, 1, num=num_colors)] elif color is not None: if colormap is not None: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 931c699d9b9fd..fa9585e1fc229 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -307,7 +307,8 @@ def _maybe_convert_index(ax, data): def _format_coord(freq, t, y): - return "t = {0} y = {1:8f}".format(Period(ordinal=int(t), freq=freq), y) + time_period = Period(ordinal=int(t), freq=freq) + return f"t = {time_period} y = {y:8f}" def format_dateaxis(subplot, freq, index): diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index bcbe5eea8b5ab..dd4034a97f58e 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -60,10 +60,7 @@ def _get_layout(nplots, layout=None, layout_type="box"): if nrows * ncols < nplots: raise ValueError( - "Layout of {nrows}x{ncols} must be larger " - "than required size {nplots}".format( - nrows=nrows, ncols=ncols, nplots=nplots - ) + f"Layout of {nrows}x{ncols} must be larger than required size {nplots}" ) return layout @@ -203,8 +200,8 @@ def _subplots( return fig, ax else: raise ValueError( - "The number of passed axes must be {0}, the " - "same as the output plot".format(naxes) + f"The number of passed axes must be {naxes}, the " + "same as the output plot" ) fig = ax.get_figure() diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 6c8bcdada5957..965da21488c8d 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -474,9 +474,7 @@ def __init__(self, deprecated=False): def __getitem__(self, key): key = self._get_canonical_key(key) if key not in self: - raise ValueError( - "{key} is not a valid pandas plotting option".format(key=key) - ) + raise ValueError(f"{key} is not a valid pandas plotting option") return super().__getitem__(key) def __setitem__(self, key, value): @@ -486,7 +484,7 @@ def __setitem__(self, key, value): def __delitem__(self, key): key = self._get_canonical_key(key) if key in self._DEFAULT_KEYS: - raise ValueError("Cannot remove default parameter {key}".format(key=key)) + raise ValueError(f"Cannot remove default parameter {key}") return super().__delitem__(key) def __contains__(self, key):
Changed the string formatting in pandas/plotting/*.py to f-strings. - [x] tests passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` ref #29547
https://api.github.com/repos/pandas-dev/pandas/pulls/29781
2019-11-21T20:37:55Z
2019-11-21T22:46:04Z
2019-11-21T22:46:03Z
2019-11-21T23:31:34Z
CLN: typing and renaming in computation.pytables
diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 8dee273517f88..58bbfd0a1bdee 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -21,7 +21,7 @@ from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded -class Scope(_scope.Scope): +class PyTablesScope(_scope.Scope): __slots__ = ("queryables",) queryables: Dict[str, Any] @@ -38,13 +38,13 @@ def __init__( class Term(ops.Term): - env: Scope + env: PyTablesScope def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls return object.__new__(klass) - def __init__(self, name, env: Scope, side=None, encoding=None): + def __init__(self, name, env: PyTablesScope, side=None, encoding=None): super().__init__(name, env, side=side, encoding=encoding) def _resolve_name(self): @@ -68,7 +68,8 @@ def value(self): class Constant(Term): - def __init__(self, value, env, side=None, encoding=None): + def __init__(self, value, env: PyTablesScope, side=None, encoding=None): + assert isinstance(env, PyTablesScope), type(env) super().__init__(value, env, side=side, encoding=encoding) def _resolve_name(self): @@ -270,7 +271,7 @@ def evaluate(self): raise ValueError("query term is not valid [{slf}]".format(slf=self)) rhs = self.conform(self.rhs) - values = [TermValue(v, v, self.kind).value for v in rhs] + values = list(rhs) if self.is_in_table: @@ -386,7 +387,7 @@ def prune(self, klass): return None -class ExprVisitor(BaseExprVisitor): +class PyTablesExprVisitor(BaseExprVisitor): const_type = Constant term_type = Term @@ -486,25 +487,29 @@ def _validate_where(w): TypeError : An invalid data type was passed in for w (e.g. dict). """ - if not (isinstance(w, (Expr, str)) or is_list_like(w)): - raise TypeError("where must be passed as a string, Expr, or list-like of Exprs") + if not (isinstance(w, (PyTablesExpr, str)) or is_list_like(w)): + raise TypeError( + "where must be passed as a string, PyTablesExpr, " + "or list-like of PyTablesExpr" + ) return w -class Expr(expr.Expr): - """ hold a pytables like expression, comprised of possibly multiple 'terms' +class PyTablesExpr(expr.Expr): + """ + Hold a pytables-like expression, comprised of possibly multiple 'terms'. Parameters ---------- - where : string term expression, Expr, or list-like of Exprs + where : string term expression, PyTablesExpr, or list-like of PyTablesExprs queryables : a "kinds" map (dict of column name -> kind), or None if column is non-indexable encoding : an encoding that will encode the query terms Returns ------- - an Expr object + a PyTablesExpr object Examples -------- @@ -520,8 +525,8 @@ class Expr(expr.Expr): "major_axis>=20130101" """ - _visitor: Optional[ExprVisitor] - env: Scope + _visitor: Optional[PyTablesExprVisitor] + env: PyTablesScope def __init__( self, @@ -542,14 +547,14 @@ def __init__( # capture the environment if needed local_dict = DeepChainMap() - if isinstance(where, Expr): + if isinstance(where, PyTablesExpr): local_dict = where.env.scope _where = where.expr elif isinstance(where, (list, tuple)): where = list(where) for idx, w in enumerate(where): - if isinstance(w, Expr): + if isinstance(w, PyTablesExpr): local_dict = w.env.scope else: w = _validate_where(w) @@ -559,11 +564,11 @@ def __init__( _where = where self.expr = _where - self.env = Scope(scope_level + 1, local_dict=local_dict) + self.env = PyTablesScope(scope_level + 1, local_dict=local_dict) if queryables is not None and isinstance(self.expr, str): self.env.queryables.update(queryables) - self._visitor = ExprVisitor( + self._visitor = PyTablesExprVisitor( self.env, queryables=queryables, parser="pytables", @@ -601,30 +606,31 @@ def evaluate(self): class TermValue: """ hold a term value the we use to construct a condition/filter """ - def __init__(self, value, converted, kind: Optional[str]): + def __init__(self, value, converted, kind: str): + assert isinstance(kind, str), kind self.value = value self.converted = converted self.kind = kind - def tostring(self, encoding): + def tostring(self, encoding) -> str: """ quote the string if not encoded else encode and return """ if self.kind == "string": if encoding is not None: - return self.converted + return str(self.converted) return '"{converted}"'.format(converted=self.converted) elif self.kind == "float": # python 2 str(float) is not always # round-trippable so use repr() return repr(self.converted) - return self.converted + return str(self.converted) def maybe_expression(s) -> bool: """ loose checking if s is a pytables-acceptable expression """ if not isinstance(s, str): return False - ops = ExprVisitor.binary_ops + ExprVisitor.unary_ops + ("=",) + ops = PyTablesExprVisitor.binary_ops + PyTablesExprVisitor.unary_ops + ("=",) # make sure we have an op at least return any(op in s for op in ops) diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 71aa885816670..78a47afcc0830 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -162,7 +162,7 @@ def has_resolvers(self) -> bool: """ return bool(len(self.resolvers)) - def resolve(self, key, is_local): + def resolve(self, key: str, is_local: bool): """ Resolve a variable name in a possibly local context. diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index ba53d8cfd0de5..eb294f0d225e1 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -48,7 +48,7 @@ from pandas.core.arrays.categorical import Categorical from pandas.core.arrays.sparse import BlockIndex, IntIndex import pandas.core.common as com -from pandas.core.computation.pytables import Expr, maybe_expression +from pandas.core.computation.pytables import PyTablesExpr, maybe_expression from pandas.core.index import ensure_index from pandas.core.internals import BlockManager, _block_shape, make_block @@ -93,7 +93,7 @@ def _ensure_str(name): return name -Term = Expr +Term = PyTablesExpr def _ensure_term(where, scope_level: int): @@ -5047,7 +5047,7 @@ def generate(self, where): q = self.table.queryables() try: - return Expr(where, queryables=q, encoding=self.table.encoding) + return PyTablesExpr(where, queryables=q, encoding=self.table.encoding) except NameError: # raise a nice message, suggesting that the user should use # data_columns diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index c6ce08080314a..66e8e1bebfe98 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -1891,7 +1891,7 @@ def test_invalid_parser(): _parsers: Dict[str, Type[BaseExprVisitor]] = { "python": PythonExprVisitor, - "pytables": pytables.ExprVisitor, + "pytables": pytables.PyTablesExprVisitor, "pandas": PandasExprVisitor, }
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29778
2019-11-21T19:16:24Z
2019-11-22T15:30:17Z
2019-11-22T15:30:17Z
2019-11-22T16:34:19Z
TYP: io.pytables types
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index ba53d8cfd0de5..941f070cc0955 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1404,7 +1404,7 @@ def _check_if_open(self): if not self.is_open: raise ClosedFileError("{0} file is not open!".format(self._path)) - def _validate_format(self, format, kwargs): + def _validate_format(self, format: str, kwargs: Dict[str, Any]) -> Dict[str, Any]: """ validate / deprecate formats; return the new kwargs """ kwargs = kwargs.copy() @@ -1597,10 +1597,9 @@ class TableIterator: stop : the passed stop value (default is None) iterator : bool, default False Whether to use the default iterator. - chunksize : the passed chunking value (default is 50000) + chunksize : the passed chunking value (default is 100000) auto_close : boolean, automatically close the store at the end of iteration, default is False - kwargs : the passed kwargs """ chunksize: Optional[int] @@ -1616,7 +1615,7 @@ def __init__( start=None, stop=None, iterator: bool = False, - chunksize=None, + chunksize: Optional[int] = None, auto_close: bool = False, ): self.store = store @@ -3448,15 +3447,14 @@ def _get_metadata_path(self, key) -> str: """ return the metadata pathname for this key """ return "{group}/meta/{key}/meta".format(group=self.group._v_pathname, key=key) - def write_metadata(self, key, values): + def write_metadata(self, key: str, values): """ write out a meta data array to the key as a fixed-format Series Parameters ---------- - key : string + key : str values : ndarray - """ values = Series(values) self.parent.put( @@ -3468,7 +3466,7 @@ def write_metadata(self, key, values): nan_rep=self.nan_rep, ) - def read_metadata(self, key): + def read_metadata(self, key: str): """ return the meta data array for this key """ if getattr(getattr(self.group, "meta", None), key, None) is not None: return self.parent.select(self._get_metadata_path(key)) @@ -4010,7 +4008,11 @@ def process_filter(field, filt): return obj def create_description( - self, complib=None, complevel=None, fletcher32: bool = False, expectedrows=None + self, + complib=None, + complevel=None, + fletcher32: bool = False, + expectedrows: Optional[int] = None, ): """ create the description of the table from the axes & values """ @@ -4228,7 +4230,7 @@ def write( # add the rows self.write_data(chunksize, dropna=dropna) - def write_data(self, chunksize, dropna=False): + def write_data(self, chunksize: Optional[int], dropna: bool = False): """ we form the data into a 2-d including indexes,values,mask write chunk-by-chunk """ @@ -4556,7 +4558,7 @@ class GenericTable(AppendableFrameTable): obj_type = DataFrame @property - def pandas_type(self): + def pandas_type(self) -> str: return self.pandas_kind @property @@ -4608,7 +4610,7 @@ class AppendableMultiFrameTable(AppendableFrameTable): _re_levels = re.compile(r"^level_\d+$") @property - def table_type_short(self): + def table_type_short(self) -> str: return "appendable_multi" def write(self, obj, data_columns=None, **kwargs):
https://api.github.com/repos/pandas-dev/pandas/pulls/29777
2019-11-21T18:33:36Z
2019-11-22T15:30:57Z
2019-11-22T15:30:57Z
2019-11-22T16:32:31Z
REF: avoid returning self in io.pytables
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index ba53d8cfd0de5..8926da3f17783 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1760,18 +1760,11 @@ def __init__( assert isinstance(self.cname, str) assert isinstance(self.kind_attr, str) - def set_axis(self, axis: int): - """ set the axis over which I index """ - self.axis = axis - - return self - def set_pos(self, pos: int): """ set the position of this column in the Table """ self.pos = pos if pos is not None and self.typ is not None: self.typ._v_pos = pos - return self def __repr__(self) -> str: temp = tuple( @@ -1846,8 +1839,6 @@ def convert( self.values = _set_tz(self.values, self.tz) - return self - def take_data(self): """ return the values & release the memory """ self.values, values = None, self.values @@ -1968,8 +1959,6 @@ def update_info(self, info): if value is not None or existing_value is not None: idx[key] = value - return self - def set_info(self, info): """ set my state from the passed info """ idx = info.get(self.name) @@ -2042,14 +2031,10 @@ def convert( """ assert self.table is not None # for mypy - assert self.table is not None - _start = start if start is not None else 0 _stop = min(stop, self.table.nrows) if stop is not None else self.table.nrows self.values = Int64Index(np.arange(_stop - _start)) - return self - def get_attr(self): pass @@ -2489,8 +2474,6 @@ def convert(self, values, nan_rep, encoding, errors, start=None, stop=None): self.data, nan_rep=nan_rep, encoding=encoding, errors=errors ) - return self - def get_attr(self): """ get the data for this column """ self.values = getattr(self.attrs, self.kind_attr, None) @@ -3800,9 +3783,12 @@ def create_axes( if i in axes: name = obj._AXIS_NAMES[i] - index_axes_map[i] = _convert_index( + new_index = _convert_index( name, a, self.encoding, self.errors, self.format_type - ).set_axis(i) + ) + new_index.axis = i + index_axes_map[i] = new_index + else: # we might be able to change the axes on the appending data if @@ -3829,10 +3815,12 @@ def create_axes( self.non_index_axes.append((i, append_axis)) # set axis positions (based on the axes) - self.index_axes = [ - index_axes_map[a].set_pos(j).update_info(self.info) - for j, a in enumerate(axes) - ] + new_index_axes = [index_axes_map[a] for a in axes] + for j, iax in enumerate(new_index_axes): + iax.set_pos(j) + iax.update_info(self.info) + self.index_axes = new_index_axes + j = len(self.index_axes) # check for column conflicts @@ -4101,19 +4089,13 @@ def read_column( # column must be an indexable or a data column c = getattr(self.table.cols, column) a.set_info(self.info) - return Series( - _set_tz( - a.convert( - c[start:stop], - nan_rep=self.nan_rep, - encoding=self.encoding, - errors=self.errors, - ).take_data(), - a.tz, - True, - ), - name=column, + a.convert( + c[start:stop], + nan_rep=self.nan_rep, + encoding=self.encoding, + errors=self.errors, ) + return Series(_set_tz(a.take_data(), a.tz, True), name=column) raise KeyError("column [{column}] not found in the table".format(column=column))
Another small step towards making these less stateful
https://api.github.com/repos/pandas-dev/pandas/pulls/29776
2019-11-21T18:18:39Z
2019-11-22T15:29:00Z
2019-11-22T15:29:00Z
2019-11-22T16:38:49Z
CLN:F-string in pandas/_libs/tslibs/*.pyx
diff --git a/pandas/_libs/tslibs/c_timestamp.pyx b/pandas/_libs/tslibs/c_timestamp.pyx index 8512b34b9e78c..c6c98e996b745 100644 --- a/pandas/_libs/tslibs/c_timestamp.pyx +++ b/pandas/_libs/tslibs/c_timestamp.pyx @@ -55,11 +55,11 @@ def maybe_integer_op_deprecated(obj): # GH#22535 add/sub of integers and int-arrays is deprecated if obj.freq is not None: warnings.warn("Addition/subtraction of integers and integer-arrays " - "to {cls} is deprecated, will be removed in a future " + f"to {type(obj).__name__} is deprecated, " + "will be removed in a future " "version. Instead of adding/subtracting `n`, use " "`n * self.freq`" - .format(cls=type(obj).__name__), - FutureWarning) + , FutureWarning) cdef class _Timestamp(datetime): @@ -144,11 +144,10 @@ cdef class _Timestamp(datetime): # e.g. tzlocal has no `strftime` pass - tz = ", tz='{0}'".format(zone) if zone is not None else "" - freq = "" if self.freq is None else ", freq='{0}'".format(self.freqstr) + tz = f", tz='{zone}'" if zone is not None else "" + freq = "" if self.freq is None else f", freq='{self.freqstr}'" - return "Timestamp('{stamp}'{tz}{freq})".format(stamp=stamp, - tz=tz, freq=freq) + return f"Timestamp('{stamp}'{tz}{freq})" cdef bint _compare_outside_nanorange(_Timestamp self, datetime other, int op) except -1: @@ -370,23 +369,22 @@ cdef class _Timestamp(datetime): @property def _repr_base(self) -> str: - return '{date} {time}'.format(date=self._date_repr, - time=self._time_repr) + return f"{self._date_repr} {self._time_repr}" @property def _date_repr(self) -> str: # Ideal here would be self.strftime("%Y-%m-%d"), but # the datetime strftime() methods require year >= 1900 - return '%d-%.2d-%.2d' % (self.year, self.month, self.day) + return f'{self.year}-{self.month:02d}-{self.day:02d}' @property def _time_repr(self) -> str: - result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) + result = f'{self.hour:02d}:{self.minute:02d}:{self.second:02d}' if self.nanosecond != 0: - result += '.%.9d' % (self.nanosecond + 1000 * self.microsecond) + result += f'.{self.nanosecond + 1000 * self.microsecond:09d}' elif self.microsecond != 0: - result += '.%.6d' % self.microsecond + result += f'.{self.microsecond:06d}' return result diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index bd74180403ad9..c5315219b8422 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -197,7 +197,7 @@ def datetime_to_datetime64(object[:] values): iresult[i] = pydatetime_to_dt64(val, &dts) check_dts_bounds(&dts) else: - raise TypeError('Unrecognized value type: %s' % type(val)) + raise TypeError(f'Unrecognized value type: {type(val)}') return result, inferred_tz @@ -326,8 +326,8 @@ cdef convert_to_tsobject(object ts, object tz, object unit, raise ValueError("Cannot convert Period to Timestamp " "unambiguously. Use to_timestamp") else: - raise TypeError('Cannot convert input [{}] of type {} to ' - 'Timestamp'.format(ts, type(ts))) + raise TypeError(f'Cannot convert input [{ts}] of type {type(ts)} to ' + f'Timestamp') if tz is not None: localize_tso(obj, tz) @@ -686,7 +686,7 @@ def normalize_date(dt: object) -> datetime: elif PyDate_Check(dt): return datetime(dt.year, dt.month, dt.day) else: - raise TypeError('Unrecognized type: %s' % type(dt)) + raise TypeError(f'Unrecognized type: {type(dt)}') @cython.wraparound(False) diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 8f5c8d10776df..dfed8d06530aa 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -130,7 +130,7 @@ def get_date_name_field(const int64_t[:] dtindex, object field, object locale=No out[i] = names[dts.month].capitalize() else: - raise ValueError("Field {field} not supported".format(field=field)) + raise ValueError(f"Field {field} not supported") return out @@ -165,8 +165,7 @@ def get_start_end_field(const int64_t[:] dtindex, object field, if freqstr: if freqstr == 'C': - raise ValueError("Custom business days is not supported by {field}" - .format(field=field)) + raise ValueError(f"Custom business days is not supported by {field}") is_business = freqstr[0] == 'B' # YearBegin(), BYearBegin() use month = starting month of year. @@ -373,7 +372,7 @@ def get_start_end_field(const int64_t[:] dtindex, object field, out[i] = 1 else: - raise ValueError("Field {field} not supported".format(field=field)) + raise ValueError(f"Field {field} not supported") return out.view(bool) @@ -537,7 +536,7 @@ def get_date_field(const int64_t[:] dtindex, object field): elif field == 'is_leap_year': return isleapyear_arr(get_date_field(dtindex, 'Y')) - raise ValueError("Field {field} not supported".format(field=field)) + raise ValueError(f"Field {field} not supported") @cython.wraparound(False) @@ -653,7 +652,7 @@ def get_timedelta_field(const int64_t[:] tdindex, object field): out[i] = tds.nanoseconds return out - raise ValueError("Field %s not supported" % field) + raise ValueError(f"Field {field} not supported") cpdef isleapyear_arr(ndarray years): diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index b29c841896072..660f4ddcec736 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -197,7 +197,7 @@ cpdef _base_and_stride(str freqstr): groups = opattern.match(freqstr) if not groups: - raise ValueError("Could not evaluate {freq}".format(freq=freqstr)) + raise ValueError(f"Could not evaluate {freqstr}") stride = groups.group(1) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 3ddce28fb6dd1..6e5e62e77b4b1 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -115,8 +115,8 @@ cdef class _NaT(datetime): if is_datetime64_object(other): return _nat_scalar_rules[op] else: - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, type(other).__name__)) + raise TypeError(f'Cannot compare type {type(self).__name__} ' + f'with type {type(other).__name__}') # Note: instead of passing "other, self, _reverse_ops[op]", we observe # that `_nat_scalar_rules` is invariant under `_reverse_ops`, @@ -150,8 +150,7 @@ cdef class _NaT(datetime): result = np.empty(other.shape, dtype="datetime64[ns]") result.fill("NaT") return result - raise TypeError("Cannot add NaT to ndarray with dtype {dtype}" - .format(dtype=other.dtype)) + raise TypeError(f"Cannot add NaT to ndarray with dtype {other.dtype}") return NotImplemented @@ -203,9 +202,8 @@ cdef class _NaT(datetime): result.fill("NaT") return result - raise TypeError( - "Cannot subtract NaT from ndarray with dtype {dtype}" - .format(dtype=other.dtype)) + raise TypeError(f"Cannot subtract NaT from ndarray with " + f"dtype {other.dtype}") return NotImplemented diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index e76f84265a327..b9406074bb130 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -112,11 +112,9 @@ cdef inline check_dts_bounds(npy_datetimestruct *dts): error = True if error: - fmt = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, dts.month, - dts.day, dts.hour, - dts.min, dts.sec) - raise OutOfBoundsDatetime( - 'Out of bounds nanosecond timestamp: {fmt}'.format(fmt=fmt)) + fmt = (f'{dts.year}-{dts.month:02d}-{dts.day:02d} ' + f'{dts.hour:02d}:{dts.min:02d}:{dts.sec:02d}') + raise OutOfBoundsDatetime(f'Out of bounds nanosecond timestamp: {fmt}') # ---------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 434252677f1a1..68a0a4a403c81 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -66,16 +66,16 @@ need_suffix = ['QS', 'BQ', 'BQS', 'YS', 'AS', 'BY', 'BA', 'BYS', 'BAS'] for __prefix in need_suffix: for _m in MONTHS: - key = '%s-%s' % (__prefix, _m) + key = f'{__prefix}-{_m}' _offset_to_period_map[key] = _offset_to_period_map[__prefix] for __prefix in ['A', 'Q']: for _m in MONTHS: - _alias = '%s-%s' % (__prefix, _m) + _alias = f'{__prefix}-{_m}' _offset_to_period_map[_alias] = _alias for _d in DAYS: - _offset_to_period_map['W-%s' % _d] = 'W-%s' % _d + _offset_to_period_map[f'W-{_d}'] = f'W-{_d}' # --------------------------------------------------------------------- @@ -432,9 +432,9 @@ class _BaseOffset: n_str = "" if self.n != 1: - n_str = "%s * " % self.n + n_str = f"{self.n} * " - out = '<%s' % n_str + className + plural + self._repr_attrs() + '>' + out = f'<{n_str}{className}{plural}{self._repr_attrs()}>' return out def _get_offset_day(self, datetime other): @@ -460,16 +460,13 @@ class _BaseOffset: ValueError if n != int(n) """ if util.is_timedelta64_object(n): - raise TypeError('`n` argument must be an integer, ' - 'got {ntype}'.format(ntype=type(n))) + raise TypeError(f'`n` argument must be an integer, got {type(n)}') try: nint = int(n) except (ValueError, TypeError): - raise TypeError('`n` argument must be an integer, ' - 'got {ntype}'.format(ntype=type(n))) + raise TypeError(f'`n` argument must be an integer, got {type(n)}') if n != nint: - raise ValueError('`n` argument must be an integer, ' - 'got {n}'.format(n=n)) + raise ValueError(f'`n` argument must be an integer, got {n}') return nint def __setstate__(self, state): diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 8fe724fa2f6f7..ecf3e35c86d76 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -153,7 +153,7 @@ cdef inline object _parse_delimited_date(object date_string, bint dayfirst): return datetime_new(year, month, day, 0, 0, 0, 0, None), reso return datetime(year, month, day, 0, 0, 0, 0, None), reso - raise DateParseError("Invalid date specified ({}/{})".format(month, day)) + raise DateParseError(f"Invalid date specified ({month}/{day})") cdef inline bint does_string_look_like_time(object parse_string): @@ -311,7 +311,7 @@ cdef parse_datetime_string_with_reso(date_string, freq=None, dayfirst=False, # TODO: allow raise of errors within instead raise DateParseError(err) if parsed is None: - raise DateParseError("Could not parse {dstr}".format(dstr=date_string)) + raise DateParseError(f"Could not parse {date_string}") return parsed, parsed, reso @@ -420,18 +420,18 @@ cdef inline object _parse_dateabbr_string(object date_string, object default, raise ValueError if not (1 <= quarter <= 4): - msg = ('Incorrect quarterly string is given, quarter must be ' - 'between 1 and 4: {dstr}') - raise DateParseError(msg.format(dstr=date_string)) + raise DateParseError(f'Incorrect quarterly string is given, ' + f'quarter must be ' + f'between 1 and 4: {date_string}') if freq is not None: # hack attack, #1228 try: mnum = MONTH_NUMBERS[_get_rule_month(freq)] + 1 except (KeyError, ValueError): - msg = ('Unable to retrieve month information from given ' - 'freq: {freq}'.format(freq=freq)) - raise DateParseError(msg) + raise DateParseError(f'Unable to retrieve month ' + f'information from given ' + f'freq: {freq}') month = (mnum + (quarter - 1) * 3) % 12 + 1 if month > mnum: @@ -464,7 +464,7 @@ cdef inline object _parse_dateabbr_string(object date_string, object default, except ValueError: pass - raise ValueError('Unable to parse {0}'.format(date_string)) + raise ValueError(f'Unable to parse {date_string}') cdef dateutil_parse(object timestr, object default, ignoretz=False, @@ -484,8 +484,7 @@ cdef dateutil_parse(object timestr, object default, ignoretz=False, res, _ = res if res is None: - msg = "Unknown datetime string format, unable to parse: {timestr}" - raise ValueError(msg.format(timestr=timestr)) + raise ValueError(f"Unknown datetime string format, unable to parse: {timestr}") for attr in ["year", "month", "day", "hour", "minute", "second", "microsecond"]: @@ -495,8 +494,7 @@ cdef dateutil_parse(object timestr, object default, ignoretz=False, reso = attr if reso is None: - msg = "Unable to parse datetime string: {timestr}" - raise ValueError(msg.format(timestr=timestr)) + raise ValueError(f"Unable to parse datetime string: {timestr}") if reso == 'microsecond': if repl['microsecond'] == 0: @@ -710,7 +708,7 @@ class _timelex: elif getattr(instream, 'read', None) is None: raise TypeError( 'Parser must be a string or character stream, not ' - '{itype}'.format(itype=instream.__class__.__name__)) + f'{type(instream).__name__}') else: self.stream = instream.read() diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 2512fdb891e3e..80db081a4fc52 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1227,7 +1227,7 @@ def period_format(int64_t value, int freq, object fmt=None): elif freq_group == 12000: # NANOSEC fmt = b'%Y-%m-%d %H:%M:%S.%n' else: - raise ValueError('Unknown freq: {freq}'.format(freq=freq)) + raise ValueError(f'Unknown freq: {freq}') return _period_strftime(value, freq, fmt) @@ -1273,17 +1273,17 @@ cdef object _period_strftime(int64_t value, int freq, object fmt): raise ValueError('Unable to get quarter and year') if i == 0: - repl = '%d' % quarter + repl = str(quarter) elif i == 1: # %f, 2-digit year - repl = '%.2d' % (year % 100) + repl = f'{(year % 100):02d}' elif i == 2: - repl = '%d' % year + repl = str(year) elif i == 3: - repl = '%03d' % (value % 1000) + repl = f'{(value % 1_000):03d}' elif i == 4: - repl = '%06d' % (value % 1000000) + repl = f'{(value % 1_000_000):06d}' elif i == 5: - repl = '%09d' % (value % 1000000000) + repl = f'{(value % 1_000_000_000):09d}' result = result.replace(str_extra_fmts[i], repl) @@ -1391,7 +1391,7 @@ def get_period_field_arr(int code, int64_t[:] arr, int freq): func = _get_accessor_func(code) if func is NULL: - raise ValueError('Unrecognized period code: {code}'.format(code=code)) + raise ValueError(f'Unrecognized period code: {code}') sz = len(arr) out = np.empty(sz, dtype=np.int64) @@ -1578,9 +1578,8 @@ cdef class _Period: freq = to_offset(freq) if freq.n <= 0: - raise ValueError('Frequency must be positive, because it' - ' represents span: {freqstr}' - .format(freqstr=freq.freqstr)) + raise ValueError(f'Frequency must be positive, because it ' + f'represents span: {freq.freqstr}') return freq @@ -1614,9 +1613,8 @@ cdef class _Period: return NotImplemented elif op == Py_NE: return NotImplemented - raise TypeError('Cannot compare type {cls} with type {typ}' - .format(cls=type(self).__name__, - typ=type(other).__name__)) + raise TypeError(f'Cannot compare type {type(self).__name__} ' + f'with type {type(other).__name__}') def __hash__(self): return hash((self.ordinal, self.freqstr)) @@ -1634,8 +1632,8 @@ cdef class _Period: if nanos % offset_nanos == 0: ordinal = self.ordinal + (nanos // offset_nanos) return Period(ordinal=ordinal, freq=self.freq) - msg = 'Input cannot be converted to Period(freq={0})' - raise IncompatibleFrequency(msg.format(self.freqstr)) + raise IncompatibleFrequency(f'Input cannot be converted to ' + f'Period(freq={self.freqstr})') elif util.is_offset_object(other): freqstr = other.rule_code base = get_base_alias(freqstr) @@ -1665,9 +1663,8 @@ cdef class _Period: # GH#17983 sname = type(self).__name__ oname = type(other).__name__ - raise TypeError("unsupported operand type(s) for +: '{self}' " - "and '{other}'".format(self=sname, - other=oname)) + raise TypeError(f"unsupported operand type(s) for +: '{sname}' " + f"and '{oname}'") else: # pragma: no cover return NotImplemented elif is_period_object(other): @@ -2218,7 +2215,7 @@ cdef class _Period: def __repr__(self) -> str: base, mult = get_freq_code(self.freq) formatted = period_format(self.ordinal, base) - return "Period('%s', '%s')" % (formatted, self.freqstr) + return f"Period('{formatted}', '{self.freqstr}')" def __str__(self) -> str: """ @@ -2226,7 +2223,7 @@ cdef class _Period: """ base, mult = get_freq_code(self.freq) formatted = period_format(self.ordinal, base) - value = ("%s" % formatted) + value = str(formatted) return value def __setstate__(self, state): @@ -2477,9 +2474,8 @@ class Period(_Period): try: freq = Resolution.get_freq(reso) except KeyError: - raise ValueError( - "Invalid frequency or could not infer: {reso}" - .format(reso=reso)) + raise ValueError(f"Invalid frequency or could not " + f"infer: {reso}") elif PyDateTime_Check(value): dt = value diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index fbda5f178e164..71e5006761097 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -106,11 +106,11 @@ def array_strptime(object[:] values, object fmt, if bad_directive == "\\": bad_directive = "%" del err - raise ValueError("'%s' is a bad directive in format '%s'" % - (bad_directive, fmt)) + raise ValueError(f"'{bad_directive}' is a bad directive " + f"in format '{fmt}'") # IndexError only occurs when the format string is "%" except IndexError: - raise ValueError("stray %% in format '%s'" % fmt) + raise ValueError("stray % in format '{fmt}'") _regex_cache[fmt] = format_regex result = np.empty(n, dtype='M8[ns]') @@ -139,14 +139,13 @@ def array_strptime(object[:] values, object fmt, if is_coerce: iresult[i] = NPY_NAT continue - raise ValueError("time data %r does not match " - "format %r (match)" % (val, fmt)) + raise ValueError(f"time data '{val}' does not match " + f"format '{fmt}' (match)") if len(val) != found.end(): if is_coerce: iresult[i] = NPY_NAT continue - raise ValueError("unconverted data remains: %s" % - val[found.end():]) + raise ValueError(f"unconverted data remains: {val[found.end():]}") # search else: @@ -155,8 +154,8 @@ def array_strptime(object[:] values, object fmt, if is_coerce: iresult[i] = NPY_NAT continue - raise ValueError("time data %r does not match format " - "%r (search)" % (val, fmt)) + raise ValueError(f"time data {repr(val)} does not match format " + f"{repr(fmt)} (search)") iso_year = -1 year = 1900 @@ -589,8 +588,8 @@ class TimeRE(dict): else: return '' regex = '|'.join(re.escape(stuff) for stuff in to_convert) - regex = '(?P<%s>%s' % (directive, regex) - return '%s)' % regex + regex = f'(?P<{directive}>{regex})' + return regex def pattern(self, format): """ @@ -609,11 +608,11 @@ class TimeRE(dict): format = whitespace_replacement.sub(r'\\s+', format) while '%' in format: directive_index = format.index('%') +1 - processed_format = "%s%s%s" % (processed_format, - format[:directive_index -1], - self[format[directive_index]]) + processed_format = (f"{processed_format}" + f"{format[:directive_index -1]}" + f"{self[format[directive_index]]}") format = format[directive_index +1:] - return "%s%s" % (processed_format, format) + return f"{processed_format}{format}" def compile(self, format): """Return a compiled re object for the format string.""" @@ -737,8 +736,7 @@ cdef parse_timezone_directive(str z): z = z[:3] + z[4:] if len(z) > 5: if z[5] != ':': - msg = "Inconsistent use of : in {0}" - raise ValueError(msg.format(z)) + raise ValueError(f"Inconsistent use of : in {z}") z = z[:5] + z[6:] hours = int(z[1:3]) minutes = int(z[3:5]) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 21dbdfbb111ed..8e5b719749857 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -170,7 +170,7 @@ cdef convert_to_timedelta64(object ts, object unit): if ts.astype('int64') == NPY_NAT: return np.timedelta64(NPY_NAT) elif is_timedelta64_object(ts): - ts = ts.astype("m8[{unit}]".format(unit=unit.lower())) + ts = ts.astype(f"m8[{unit.lower()}]") elif is_integer_object(ts): if ts == NPY_NAT: return np.timedelta64(NPY_NAT) @@ -198,8 +198,7 @@ cdef convert_to_timedelta64(object ts, object unit): if PyDelta_Check(ts): ts = np.timedelta64(delta_to_nanoseconds(ts), 'ns') elif not is_timedelta64_object(ts): - raise ValueError("Invalid type for timedelta " - "scalar: {ts_type}".format(ts_type=type(ts))) + raise ValueError(f"Invalid type for timedelta scalar: {type(ts)}") return ts.astype('timedelta64[ns]') @@ -288,7 +287,7 @@ cpdef inline object precision_from_unit(object unit): m = 1L p = 0 else: - raise ValueError("cannot cast unit {unit}".format(unit=unit)) + raise ValueError(f"cannot cast unit {unit}") return m, p @@ -397,8 +396,7 @@ cdef inline int64_t parse_timedelta_string(str ts) except? -1: result += timedelta_as_neg(r, neg) have_hhmmss = 1 else: - raise ValueError("expecting hh:mm:ss format, " - "received: {ts}".format(ts=ts)) + raise ValueError(f"expecting hh:mm:ss format, received: {ts}") unit, number = [], [] @@ -511,7 +509,7 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): unit = 'm' unit = parse_timedelta_unit(unit) except KeyError: - raise ValueError("invalid abbreviation: {unit}".format(unit=unit)) + raise ValueError(f"invalid abbreviation: {unit}") n = ''.join(number) + '.' + ''.join(frac) return cast_from_unit(float(n), unit) @@ -530,8 +528,7 @@ cpdef inline object parse_timedelta_unit(object unit): try: return timedelta_abbrevs[unit.lower()] except (KeyError, AttributeError): - raise ValueError("invalid unit abbreviation: {unit}" - .format(unit=unit)) + raise ValueError(f"invalid unit abbreviation: {unit}") # ---------------------------------------------------------------------- # Timedelta ops utilities @@ -727,8 +724,7 @@ cdef _to_py_int_float(v): return int(v) elif is_float_object(v): return float(v) - raise TypeError("Invalid type {typ}. Must be int or " - "float.".format(typ=type(v))) + raise TypeError(f"Invalid type {type(v)}. Must be int or float.") # Similar to Timestamp/datetime, this is a construction requirement for @@ -773,10 +769,9 @@ cdef class _Timedelta(timedelta): elif op == Py_NE: return True # only allow ==, != ops - raise TypeError('Cannot compare type {cls} with ' - 'type {other}' - .format(cls=type(self).__name__, - other=type(other).__name__)) + raise TypeError(f'Cannot compare type ' + f'{type(self).__name__} with ' + f'type {type(other).__name__}') if util.is_array(other): return PyObject_RichCompare(np.array([self]), other, op) return PyObject_RichCompare(other, self, reverse_ops[op]) @@ -787,10 +782,8 @@ cdef class _Timedelta(timedelta): return False elif op == Py_NE: return True - raise TypeError('Cannot compare type {cls} with ' - 'type {other}' - .format(cls=type(self).__name__, - other=type(other).__name__)) + raise TypeError(f'Cannot compare type {type(self).__name__} with ' + f'type {type(other).__name__}') return cmp_scalar(self.value, ots.value, op) @@ -1143,7 +1136,8 @@ cdef class _Timedelta(timedelta): return fmt.format(**comp_dict) def __repr__(self) -> str: - return "Timedelta('{val}')".format(val=self._repr_base(format='long')) + repr_based = self._repr_base(format='long') + return f"Timedelta('{repr_based}')" def __str__(self) -> str: return self._repr_base(format='long') @@ -1189,14 +1183,14 @@ cdef class _Timedelta(timedelta): 'P500DT12H0MS' """ components = self.components - seconds = '{}.{:0>3}{:0>3}{:0>3}'.format(components.seconds, - components.milliseconds, - components.microseconds, - components.nanoseconds) + seconds = (f'{components.seconds}.' + f'{components.milliseconds:0>3}' + f'{components.microseconds:0>3}' + f'{components.nanoseconds:0>3}') # Trim unnecessary 0s, 1.000000000 -> 1 seconds = seconds.rstrip('0').rstrip('.') - tpl = ('P{td.days}DT{td.hours}H{td.minutes}M{seconds}S' - .format(td=components, seconds=seconds)) + tpl = (f'P{components.days}DT{components.hours}' + f'H{components.minutes}M{seconds}S') return tpl @@ -1276,7 +1270,7 @@ class Timedelta(_Timedelta): value = convert_to_timedelta64(value, 'ns') elif is_timedelta64_object(value): if unit is not None: - value = value.astype('timedelta64[{0}]'.format(unit)) + value = value.astype(f'timedelta64[{unit}]') value = value.astype('timedelta64[ns]') elif hasattr(value, 'delta'): value = np.timedelta64(delta_to_nanoseconds(value.delta), 'ns') @@ -1288,9 +1282,8 @@ class Timedelta(_Timedelta): return NaT else: raise ValueError( - "Value must be Timedelta, string, integer, " - "float, timedelta or convertible, not {typ}" - .format(typ=type(value).__name__)) + f"Value must be Timedelta, string, integer, " + f"float, timedelta or convertible, not {type(value).__name__}") if is_timedelta64_object(value): value = value.view('i8') @@ -1485,9 +1478,7 @@ class Timedelta(_Timedelta): else: return self.to_timedelta64() // other - raise TypeError('Invalid dtype {dtype} for ' - '{op}'.format(dtype=other.dtype, - op='__floordiv__')) + raise TypeError(f'Invalid dtype {other.dtype} for __floordiv__') elif is_integer_object(other) or is_float_object(other): return Timedelta(self.value // other, unit='ns') @@ -1530,9 +1521,7 @@ class Timedelta(_Timedelta): """) warnings.warn(msg, FutureWarning) return other // self.value - raise TypeError('Invalid dtype {dtype} for ' - '{op}'.format(dtype=other.dtype, - op='__floordiv__')) + raise TypeError(f'Invalid dtype {other.dtype} for __floordiv__') elif is_float_object(other) and util.is_nan(other): # i.e. np.nan @@ -1555,8 +1544,7 @@ class Timedelta(_Timedelta): if hasattr(other, 'dtype') and other.dtype.kind == 'i': # TODO: Remove this check with backwards-compat shim # for integer / Timedelta is removed. - raise TypeError("Invalid type {dtype} for " - "{op}".format(dtype=other.dtype, op='__mod__')) + raise TypeError(f'Invalid dtype {other.dtype} for __mod__') return self.__rdivmod__(other)[1] def __divmod__(self, other): @@ -1569,8 +1557,7 @@ class Timedelta(_Timedelta): if hasattr(other, 'dtype') and other.dtype.kind == 'i': # TODO: Remove this check with backwards-compat shim # for integer / Timedelta is removed. - raise TypeError("Invalid type {dtype} for " - "{op}".format(dtype=other.dtype, op='__mod__')) + raise TypeError(f'Invalid dtype {other.dtype} for __mod__') div = other // self return div, other - div * self diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 03ed26337d539..1a278f46a4a2b 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -370,8 +370,8 @@ class Timestamp(_Timestamp): if tzinfo is not None: if not PyTZInfo_Check(tzinfo): # tzinfo must be a datetime.tzinfo object, GH#17690 - raise TypeError('tzinfo must be a datetime.tzinfo object, ' - 'not %s' % type(tzinfo)) + raise TypeError(f'tzinfo must be a datetime.tzinfo object, ' + f'not {type(tzinfo)}') elif tz is not None: raise ValueError('Can provide at most one of tz, tzinfo') @@ -946,8 +946,8 @@ default 'raise' def validate(k, v): """ validate integers """ if not is_integer_object(v): - raise ValueError("value must be an integer, received " - "{v} for {k}".format(v=type(v), k=k)) + raise ValueError(f"value must be an integer, received " + f"{type(v)} for {k}") return v if year is not None: @@ -1003,9 +1003,9 @@ default 'raise' base1, base2 = base, "" if self.microsecond != 0: - base1 += "%.3d" % self.nanosecond + base1 += f"{self.nanosecond:03d}" else: - base1 += ".%.9d" % self.nanosecond + base1 += f".{self.nanosecond:09d}" return base1 + base2 diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index bc1fdfae99de9..35ee87e714fa8 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -280,8 +280,8 @@ def infer_tzinfo(start, end): if start is not None and end is not None: tz = start.tzinfo if not tz_compare(tz, end.tzinfo): - msg = 'Inputs must both have the same timezone, {tz1} != {tz2}' - raise AssertionError(msg.format(tz1=tz, tz2=end.tzinfo)) + raise AssertionError(f'Inputs must both have the same timezone, ' + f'{tz} != {end.tzinfo}') elif start is not None: tz = start.tzinfo elif end is not None: diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index dd0c6fc75b06f..b368f0fde3edc 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -175,8 +175,8 @@ timedelta-like} if trans_idx.size == 1: stamp = _render_tstamp(vals[trans_idx]) raise pytz.AmbiguousTimeError( - "Cannot infer dst time from %s as there " - "are no repeated times".format(stamp)) + f"Cannot infer dst time from {stamp} as there " + f"are no repeated times") # Split the array into contiguous chunks (where the difference between # indices is 1). These are effectively dst transitions in different # years which is useful for checking that there is not an ambiguous @@ -200,8 +200,8 @@ timedelta-like} switch_idx = (delta <= 0).nonzero()[0] if switch_idx.size > 1: raise pytz.AmbiguousTimeError( - "There are %i dst switches when " - "there should only be 1.".format(switch_idx.size)) + f"There are {switch_idx.size} dst switches when " + f"there should only be 1.") switch_idx = switch_idx[0] + 1 # Pull the only index and adjust a_idx = grp[:switch_idx] @@ -230,8 +230,8 @@ timedelta-like} else: stamp = _render_tstamp(val) raise pytz.AmbiguousTimeError( - "Cannot infer dst time from %r, try using the " - "'ambiguous' argument".format(stamp)) + f"Cannot infer dst time from {stamp}, try using the " + f"'ambiguous' argument") elif left != NPY_NAT: result[i] = left elif right != NPY_NAT: @@ -246,8 +246,8 @@ timedelta-like} # time if -1 < shift_delta + remaining_mins < HOURS_NS: raise ValueError( - "The provided timedelta will relocalize on a " - "nonexistent time: {}".format(nonexistent) + f"The provided timedelta will relocalize on a " + f"nonexistent time: {nonexistent}" ) new_local = val + shift_delta elif shift_forward:
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry ref https://github.com/pandas-dev/pandas/issues/29547
https://api.github.com/repos/pandas-dev/pandas/pulls/29775
2019-11-21T16:05:32Z
2019-11-22T15:32:44Z
2019-11-22T15:32:44Z
2019-11-22T17:39:36Z
Reenabled no-unused-function in setup.py
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index bbea66542a953..8f0f4e17df2f9 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -1406,59 +1406,6 @@ cdef inline StringPath _string_path(char *encoding): # Type conversions / inference support code -cdef _string_box_factorize(parser_t *parser, int64_t col, - int64_t line_start, int64_t line_end, - bint na_filter, kh_str_starts_t *na_hashset): - cdef: - int error, na_count = 0 - Py_ssize_t i, lines - coliter_t it - const char *word = NULL - ndarray[object] result - - int ret = 0 - kh_strbox_t *table - - object pyval - - object NA = na_values[np.object_] - khiter_t k - - table = kh_init_strbox() - lines = line_end - line_start - result = np.empty(lines, dtype=np.object_) - coliter_setup(&it, parser, col, line_start) - - for i in range(lines): - COLITER_NEXT(it, word) - - if na_filter: - if kh_get_str_starts_item(na_hashset, word): - # in the hash table - na_count += 1 - result[i] = NA - continue - - k = kh_get_strbox(table, word) - - # in the hash table - if k != table.n_buckets: - # this increments the refcount, but need to test - pyval = <object>table.vals[k] - else: - # box it. new ref? - pyval = PyBytes_FromString(word) - - k = kh_put_strbox(table, word, &ret) - table.vals[k] = <PyObject*>pyval - - result[i] = pyval - - kh_destroy_strbox(table) - - return result, na_count - - cdef _string_box_utf8(parser_t *parser, int64_t col, int64_t line_start, int64_t line_end, bint na_filter, kh_str_starts_t *na_hashset): diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index 48712dc68829d..21f439ec93e0f 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -399,22 +399,6 @@ static void *CLong(JSOBJ obj, JSONTypeContext *tc, void *outValue, return NULL; } -#ifdef _LP64 -static void *PyIntToINT64(JSOBJ _obj, JSONTypeContext *tc, void *outValue, - size_t *_outLen) { - PyObject *obj = (PyObject *)_obj; - *((JSINT64 *)outValue) = PyLong_AsLong(obj); - return NULL; -} -#else -static void *PyIntToINT32(JSOBJ _obj, JSONTypeContext *tc, void *outValue, - size_t *_outLen) { - PyObject *obj = (PyObject *)_obj; - *((JSINT32 *)outValue) = PyLong_AsLong(obj); - return NULL; -} -#endif - static void *PyLongToINT64(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen) { *((JSINT64 *)outValue) = GET_TC(tc)->longValue; diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 3ddce28fb6dd1..a3274f74fff9e 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -95,10 +95,6 @@ cdef class _NaT(datetime): # higher than np.ndarray and np.matrix __array_priority__ = 100 - def __hash__(_NaT self): - # py3k needs this defined here - return hash(self.value) - def __richcmp__(_NaT self, object other, int op): cdef: int ndim = getattr(other, 'ndim', -1) diff --git a/setup.py b/setup.py index 545765ecb114d..a5c26b064f2f3 100755 --- a/setup.py +++ b/setup.py @@ -462,7 +462,7 @@ def run(self): extra_link_args.append("/DEBUG") else: # args to ignore warnings - extra_compile_args = ["-Wno-unused-function"] + extra_compile_args = [] extra_link_args = [] if debugging_symbols_requested: extra_compile_args.append("-g")
This enables a flag that was disabled 4 years ago in https://github.com/pandas-dev/pandas/commit/e9fde88c47aab023cafa6c98d5654db9dc89197f but maybe worth reconsidering, even though we don't fail on warnings for extensions in CI This yielded the following on master: ```sh pandas/_libs/hashing.c:25313:20: warning: unused function '__pyx_memview_get_object' [-Wunused-function] pandas/_libs/hashing.c:25318:12: warning: unused function '__pyx_memview_set_object' [-Wunused-function] pandas/_libs/hashtable.c:63342:20: warning: unused function '__pyx_memview_get_object' [-Wunused-function] pandas/_libs/hashtable.c:63347:12: warning: unused function '__pyx_memview_set_object' [-Wunused-function] pandas/_libs/parsers.c:21453:18: warning: unused function '__pyx_f_6pandas_5_libs_7parsers__string_box_factorize' [-Wunused-function] pandas/_libs/tslibs/conversion.c:33247:20: warning: unused function '__pyx_memview_get_object' [-Wunused-function] pandas/_libs/tslibs/conversion.c:33252:12: warning: unused function '__pyx_memview_set_object' [-Wunused-function] pandas/_libs/tslibs/nattype.c:3496:18: warning: unused function '__pyx_pw_6pandas_5_libs_6tslibs_7nattype_4_NaT_1__hash__' [-Wunused-function] pandas/_libs/src/ujson/python/objToJSON.c:403:14: warning: unused function 'PyIntToINT64' [-Wunused-function] ``` I'm not sure what the `memview_set_object` and `memview_get_object` complaints are coming from just yet, but the rest are cleaned up in this PR
https://api.github.com/repos/pandas-dev/pandas/pulls/29767
2019-11-21T05:55:15Z
2019-11-22T15:33:17Z
2019-11-22T15:33:17Z
2023-04-12T20:15:54Z
DEPR: MultiIndex.to_hierarchical, labels
diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-36.yaml index 831b68d0bb4d3..f393ed84ecf63 100644 --- a/ci/deps/azure-macos-36.yaml +++ b/ci/deps/azure-macos-36.yaml @@ -20,9 +20,9 @@ dependencies: - matplotlib=2.2.3 - nomkl - numexpr - - numpy=1.13.3 + - numpy=1.14 - openpyxl - - pyarrow + - pyarrow>=0.12.0 - pytables - python-dateutil==2.6.1 - pytz diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml index aa3962da9b4f0..903a4b4a222f1 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-36.yaml @@ -20,7 +20,7 @@ dependencies: - numexpr - numpy=1.15.* - openpyxl - - pyarrow + - pyarrow>=0.12.0 - pytables - python-dateutil - pytz diff --git a/doc/redirects.csv b/doc/redirects.csv index a2146edde6324..fb922eb79e363 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -828,7 +828,6 @@ generated/pandas.MultiIndex.sortlevel,../reference/api/pandas.MultiIndex.sortlev generated/pandas.MultiIndex.swaplevel,../reference/api/pandas.MultiIndex.swaplevel generated/pandas.MultiIndex.to_flat_index,../reference/api/pandas.MultiIndex.to_flat_index generated/pandas.MultiIndex.to_frame,../reference/api/pandas.MultiIndex.to_frame -generated/pandas.MultiIndex.to_hierarchical,../reference/api/pandas.MultiIndex.to_hierarchical generated/pandas.notna,../reference/api/pandas.notna generated/pandas.notnull,../reference/api/pandas.notnull generated/pandas.option_context,../reference/api/pandas.option_context diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 04df37427e4f5..9f3ab22496ae7 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -258,7 +258,7 @@ matplotlib 2.2.2 Visualization openpyxl 2.4.8 Reading / writing for xlsx files pandas-gbq 0.8.0 Google Big Query access psycopg2 PostgreSQL engine for sqlalchemy -pyarrow 0.9.0 Parquet and feather reading / writing +pyarrow 0.12.0 Parquet and feather reading / writing pymysql 0.7.11 MySQL engine for sqlalchemy pyreadstat SPSS files (.sav) reading pytables 3.4.2 HDF5 reading / writing diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index 409791c7530a2..448f020cfa56f 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -305,7 +305,6 @@ MultiIndex components MultiIndex.set_levels MultiIndex.set_codes - MultiIndex.to_hierarchical MultiIndex.to_flat_index MultiIndex.to_frame MultiIndex.is_lexsorted diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index ac440c263088b..d31f161afd3b4 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -240,62 +240,62 @@ The following methods now also correctly output values for unobserved categories Increased minimum versions for dependencies ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Some minimum supported versions of dependencies were updated (:issue:`29723`). +Some minimum supported versions of dependencies were updated (:issue:`29766`, :issue:`29723`). If installed, we now require: -+-----------------+-----------------+----------+ -| Package | Minimum Version | Required | -+=================+=================+==========+ -| numpy | 1.13.3 | X | -+-----------------+-----------------+----------+ -| pytz | 2015.4 | X | -+-----------------+-----------------+----------+ -| python-dateutil | 2.6.1 | X | -+-----------------+-----------------+----------+ -| bottleneck | 1.2.1 | | -+-----------------+-----------------+----------+ -| numexpr | 2.6.2 | | -+-----------------+-----------------+----------+ -| pytest (dev) | 4.0.2 | | -+-----------------+-----------------+----------+ ++-----------------+-----------------+----------+---------+ +| Package | Minimum Version | Required | Changed | ++=================+=================+==========+=========+ +| numpy | 1.13.3 | X | | ++-----------------+-----------------+----------+---------+ +| pytz | 2015.4 | X | | ++-----------------+-----------------+----------+---------+ +| python-dateutil | 2.6.1 | X | | ++-----------------+-----------------+----------+---------+ +| bottleneck | 1.2.1 | | | ++-----------------+-----------------+----------+---------+ +| numexpr | 2.6.2 | | | ++-----------------+-----------------+----------+---------+ +| pytest (dev) | 4.0.2 | | | ++-----------------+-----------------+----------+---------+ For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version. The following table lists the lowest version per library that is currently being tested throughout the development of pandas. Optional libraries below the lowest tested version may still work, but are not considered supported. -+-----------------+-----------------+ -| Package | Minimum Version | -+=================+=================+ -| beautifulsoup4 | 4.6.0 | -+-----------------+-----------------+ -| fastparquet | 0.3.2 | -+-----------------+-----------------+ -| gcsfs | 0.2.2 | -+-----------------+-----------------+ -| lxml | 3.8.0 | -+-----------------+-----------------+ -| matplotlib | 2.2.2 | -+-----------------+-----------------+ -| openpyxl | 2.4.8 | -+-----------------+-----------------+ -| pyarrow | 0.9.0 | -+-----------------+-----------------+ -| pymysql | 0.7.1 | -+-----------------+-----------------+ -| pytables | 3.4.2 | -+-----------------+-----------------+ -| scipy | 0.19.0 | -+-----------------+-----------------+ -| sqlalchemy | 1.1.4 | -+-----------------+-----------------+ -| xarray | 0.8.2 | -+-----------------+-----------------+ -| xlrd | 1.1.0 | -+-----------------+-----------------+ -| xlsxwriter | 0.9.8 | -+-----------------+-----------------+ -| xlwt | 1.2.0 | -+-----------------+-----------------+ ++-----------------+-----------------+---------+ +| Package | Minimum Version | Changed | ++=================+=================+=========+ +| beautifulsoup4 | 4.6.0 | | ++-----------------+-----------------+---------+ +| fastparquet | 0.3.2 | X | ++-----------------+-----------------+---------+ +| gcsfs | 0.2.2 | | ++-----------------+-----------------+---------+ +| lxml | 3.8.0 | | ++-----------------+-----------------+---------+ +| matplotlib | 2.2.2 | | ++-----------------+-----------------+---------+ +| openpyxl | 2.4.8 | | ++-----------------+-----------------+---------+ +| pyarrow | 0.12.0 | X | ++-----------------+-----------------+---------+ +| pymysql | 0.7.1 | | ++-----------------+-----------------+---------+ +| pytables | 3.4.2 | | ++-----------------+-----------------+---------+ +| scipy | 0.19.0 | | ++-----------------+-----------------+---------+ +| sqlalchemy | 1.1.4 | | ++-----------------+-----------------+---------+ +| xarray | 0.8.2 | | ++-----------------+-----------------+---------+ +| xlrd | 1.1.0 | | ++-----------------+-----------------+---------+ +| xlsxwriter | 0.9.8 | | ++-----------------+-----------------+---------+ +| xlwt | 1.2.0 | | ++-----------------+-----------------+---------+ See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. @@ -389,6 +389,11 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - :func:`core.internals.blocks.make_block` no longer accepts the "fastpath" keyword(:issue:`19265`) - :meth:`Block.make_block_same_class` no longer accepts the "dtype" keyword(:issue:`19434`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) +- Removed the previously deprecated :meth:`MultiIndex.to_hierarchical` (:issue:`21613`) +- Removed the previously deprecated :attr:`MultiIndex.labels`, use :attr:`MultiIndex.codes` instead (:issue:`23752`) +- Removed the previously deprecated "labels" keyword from the :class:`MultiIndex` constructor, use "codes" instead (:issue:`23752`) +- Removed the previously deprecated :meth:`MultiIndex.set_labels`, use :meth:`MultiIndex.set_codes` instead (:issue:`23752`) +- Removed the previously deprecated "labels" keyword from :meth:`MultiIndex.set_codes`, :meth:`MultiIndex.copy`, :meth:`MultiIndex.drop`, use "codes" instead (:issue:`23752`) - Removed support for legacy HDF5 formats (:issue:`29787`) - :func:`read_excel` removed support for "skip_footer" argument, use "skipfooter" instead (:issue:`18836`) - :meth:`DataFrame.to_records` no longer supports the argument "convert_datetime64" (:issue:`18902`) diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index bfe31c6a1d794..0be201daea425 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -16,7 +16,7 @@ "odfpy": "1.3.0", "openpyxl": "2.4.8", "pandas_gbq": "0.8.0", - "pyarrow": "0.9.0", + "pyarrow": "0.12.0", "pytables": "3.4.2", "pytest": "5.0.1", "s3fs": "0.3.0", diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 10c0f465f69da..91681060a185c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -160,6 +160,12 @@ def _new_Index(cls, d): from pandas.core.indexes.period import _new_PeriodIndex return _new_PeriodIndex(cls, **d) + + if issubclass(cls, ABCMultiIndex): + if "labels" in d and "codes" not in d: + # GH#23752 "labels" kwarg has been replaced with "codes" + d["codes"] = d.pop("labels") + return cls.__new__(cls, **d) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 86398613798be..048112cbf0836 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -11,7 +11,7 @@ from pandas._libs.hashtable import duplicated_int64 from pandas.compat.numpy import function as nv from pandas.errors import PerformanceWarning, UnsortedIndexError -from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg +from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_int64, @@ -229,9 +229,7 @@ class MultiIndex(Index): of the mentioned helper methods. """ - _deprecations = Index._deprecations | frozenset( - ["labels", "set_labels", "to_hierarchical"] - ) + _deprecations = Index._deprecations | frozenset() # initialize to zero-length tuples to make everything work _typ = "multiindex" @@ -244,7 +242,6 @@ class MultiIndex(Index): # -------------------------------------------------------------------- # Constructors - @deprecate_kwarg(old_arg_name="labels", new_arg_name="codes") def __new__( cls, levels=None, @@ -813,15 +810,6 @@ def set_levels(self, levels, level=None, inplace=False, verify_integrity=True): def codes(self): return self._codes - @property - def labels(self): - warnings.warn( - (".labels was deprecated in version 0.24.0. Use .codes instead."), - FutureWarning, - stacklevel=2, - ) - return self.codes - def _set_codes( self, codes, level=None, copy=False, validate=True, verify_integrity=False ): @@ -854,23 +842,6 @@ def _set_codes( self._tuples = None self._reset_cache() - def set_labels(self, labels, level=None, inplace=False, verify_integrity=True): - warnings.warn( - ( - ".set_labels was deprecated in version 0.24.0. " - "Use .set_codes instead." - ), - FutureWarning, - stacklevel=2, - ) - return self.set_codes( - codes=labels, - level=level, - inplace=inplace, - verify_integrity=verify_integrity, - ) - - @deprecate_kwarg(old_arg_name="labels", new_arg_name="codes") def set_codes(self, codes, level=None, inplace=False, verify_integrity=True): """ Set new codes on MultiIndex. Defaults to returning @@ -947,7 +918,6 @@ def set_codes(self, codes, level=None, inplace=False, verify_integrity=True): if not inplace: return idx - @deprecate_kwarg(old_arg_name="labels", new_arg_name="codes") def copy( self, names=None, @@ -981,7 +951,8 @@ def copy( """ name = kwargs.get("name") names = self._validate_names(name=name, names=names, deep=deep) - + if "labels" in kwargs: + raise TypeError("'labels' argument has been removed; use 'codes' instead") if deep: from copy import deepcopy @@ -1700,62 +1671,6 @@ def to_frame(self, index=True, name=None): result.index = self return result - def to_hierarchical(self, n_repeat, n_shuffle=1): - """ - Return a MultiIndex reshaped to conform to the - shapes given by n_repeat and n_shuffle. - - .. deprecated:: 0.24.0 - - Useful to replicate and rearrange a MultiIndex for combination - with another Index with n_repeat items. - - Parameters - ---------- - n_repeat : int - Number of times to repeat the labels on self. - n_shuffle : int - Controls the reordering of the labels. If the result is going - to be an inner level in a MultiIndex, n_shuffle will need to be - greater than one. The size of each label must divisible by - n_shuffle. - - Returns - ------- - MultiIndex - - Examples - -------- - >>> idx = pd.MultiIndex.from_tuples([(1, 'one'), (1, 'two'), - (2, 'one'), (2, 'two')]) - >>> idx.to_hierarchical(3) - MultiIndex([(1, 'one'), - (1, 'one'), - (1, 'one'), - (1, 'two'), - (1, 'two'), - (1, 'two'), - (2, 'one'), - (2, 'one'), - (2, 'one'), - (2, 'two'), - (2, 'two'), - (2, 'two')], - ) - """ - levels = self.levels - codes = [np.repeat(level_codes, n_repeat) for level_codes in self.codes] - # Assumes that each level_codes is divisible by n_shuffle - codes = [x.reshape(n_shuffle, -1).ravel(order="F") for x in codes] - names = self.names - warnings.warn( - "Method .to_hierarchical is deprecated and will " - "be removed in a future version", - FutureWarning, - stacklevel=2, - ) - return MultiIndex(levels=levels, codes=codes, names=names) - def to_flat_index(self): """ Convert a MultiIndex to an Index of Tuples containing the level values. @@ -2148,7 +2063,6 @@ def repeat(self, repeats, axis=None): def where(self, cond, other=None): raise NotImplementedError(".where is not supported for MultiIndex operations") - @deprecate_kwarg(old_arg_name="labels", new_arg_name="codes") def drop(self, codes, level=None, errors="raise"): """ Make new MultiIndex with passed list of codes deleted diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index dffe04fb63720..01118d7b7cd3e 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -1,7 +1,5 @@ """ feather-format compat """ -from distutils.version import LooseVersion - from pandas.compat._optional import import_optional_dependency from pandas import DataFrame, Int64Index, RangeIndex @@ -96,15 +94,9 @@ def read_feather(path, columns=None, use_threads=True): ------- type of object stored in file """ - pyarrow = import_optional_dependency("pyarrow") + import_optional_dependency("pyarrow") from pyarrow import feather path = _stringify_path(path) - if LooseVersion(pyarrow.__version__) < LooseVersion("0.11.0"): - int_use_threads = int(use_threads) - if int_use_threads < 1: - int_use_threads = 1 - return feather.read_feather(path, columns=columns, nthreads=int_use_threads) - return feather.read_feather(path, columns=columns, use_threads=bool(use_threads)) diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py index 9c53210b75d6b..e88c63b19003f 100644 --- a/pandas/tests/extension/arrow/test_bool.py +++ b/pandas/tests/extension/arrow/test_bool.py @@ -5,7 +5,7 @@ from pandas.tests.extension import base import pandas.util.testing as tm -pytest.importorskip("pyarrow", minversion="0.10.0") +pytest.importorskip("pyarrow", minversion="0.12.0") from .arrays import ArrowBoolArray, ArrowBoolDtype # isort:skip diff --git a/pandas/tests/extension/arrow/test_string.py b/pandas/tests/extension/arrow/test_string.py index 06f149aa4b75f..baedcf0dd9088 100644 --- a/pandas/tests/extension/arrow/test_string.py +++ b/pandas/tests/extension/arrow/test_string.py @@ -2,7 +2,7 @@ import pandas as pd -pytest.importorskip("pyarrow", minversion="0.10.0") +pytest.importorskip("pyarrow", minversion="0.12.0") from .arrays import ArrowStringDtype # isort:skip diff --git a/pandas/tests/indexes/multi/test_constructor.py b/pandas/tests/indexes/multi/test_constructor.py index d2c95b12d5339..c0ec889d170d6 100644 --- a/pandas/tests/indexes/multi/test_constructor.py +++ b/pandas/tests/indexes/multi/test_constructor.py @@ -128,18 +128,6 @@ def test_na_levels(): tm.assert_index_equal(result, expected) -def test_labels_deprecated(idx): - # GH23752 - with tm.assert_produces_warning(FutureWarning): - MultiIndex( - levels=[["foo", "bar", "baz", "qux"]], - labels=[[0, 1, 2, 3]], - names=["first"], - ) - with tm.assert_produces_warning(FutureWarning): - idx.labels - - def test_copy_in_constructor(): levels = np.array(["a", "b", "c"]) codes = np.array([1, 1, 2, 0, 0, 1, 1]) diff --git a/pandas/tests/indexes/multi/test_conversion.py b/pandas/tests/indexes/multi/test_conversion.py index 3fc73dd05bc72..a0b17ae8924b7 100644 --- a/pandas/tests/indexes/multi/test_conversion.py +++ b/pandas/tests/indexes/multi/test_conversion.py @@ -133,59 +133,8 @@ def test_to_frame_resulting_column_order(): assert result == expected -def test_to_hierarchical(): - index = MultiIndex.from_tuples([(1, "one"), (1, "two"), (2, "one"), (2, "two")]) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - result = index.to_hierarchical(3) - expected = MultiIndex( - levels=[[1, 2], ["one", "two"]], - codes=[ - [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], - [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], - ], - ) - tm.assert_index_equal(result, expected) - assert result.names == index.names - - # K > 1 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - result = index.to_hierarchical(3, 2) - expected = MultiIndex( - levels=[[1, 2], ["one", "two"]], - codes=[ - [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], - [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], - ], - ) - tm.assert_index_equal(result, expected) - assert result.names == index.names - - # non-sorted - index = MultiIndex.from_tuples( - [(2, "c"), (1, "b"), (2, "a"), (2, "b")], names=["N1", "N2"] - ) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - result = index.to_hierarchical(2) - expected = MultiIndex.from_tuples( - [ - (2, "c"), - (2, "c"), - (1, "b"), - (1, "b"), - (2, "a"), - (2, "a"), - (2, "b"), - (2, "b"), - ], - names=["N1", "N2"], - ) - tm.assert_index_equal(result, expected) - assert result.names == index.names - - def test_roundtrip_pickle_with_tz(): - return + return # FIXME: this can't be right? # GH 8367 # round-trip of timezone @@ -198,7 +147,7 @@ def test_roundtrip_pickle_with_tz(): def test_pickle(indices): - return + return # FIXME: this can't be right? unpickled = tm.round_trip_pickle(indices) assert indices.equals(unpickled) diff --git a/pandas/tests/indexes/multi/test_copy.py b/pandas/tests/indexes/multi/test_copy.py index 2668197535fcc..12cd0db6936f5 100644 --- a/pandas/tests/indexes/multi/test_copy.py +++ b/pandas/tests/indexes/multi/test_copy.py @@ -35,12 +35,6 @@ def test_shallow_copy(idx): assert_multiindex_copied(i_copy, idx) -def test_labels_deprecated(idx): - # GH23752 - with tm.assert_produces_warning(FutureWarning): - idx.copy(labels=idx.codes) - - def test_view(idx): i_view = idx.view() assert_multiindex_copied(i_view, idx) diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 5ab817d8468c3..ec3c654ecb1ed 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -306,27 +306,6 @@ def test_set_codes(idx): result.set_codes(codes=new_codes, level=1, inplace=True) assert result.equals(expected) - with tm.assert_produces_warning(FutureWarning): - ind.set_codes(labels=new_codes, level=1) - - -def test_set_labels_deprecated(): - # GH23752 - ind = pd.MultiIndex.from_tuples([(0, i) for i in range(130)]) - new_labels = range(129, -1, -1) - expected = pd.MultiIndex.from_tuples([(0, i) for i in new_labels]) - - # [w/o mutation] - with tm.assert_produces_warning(FutureWarning): - result = ind.set_labels(labels=new_labels, level=1) - assert result.equals(expected) - - # [w/ mutation] - result = ind.copy() - with tm.assert_produces_warning(FutureWarning): - result.set_labels(labels=new_labels, level=1, inplace=True) - assert result.equals(expected) - def test_set_levels_codes_names_bad_input(idx): levels, codes = idx.levels, idx.codes
https://api.github.com/repos/pandas-dev/pandas/pulls/29766
2019-11-21T05:15:03Z
2019-11-25T23:12:05Z
2019-11-25T23:12:05Z
2019-11-25T23:30:21Z
REF: make Fixed.version a property
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 7c447cbf78677..f060831a1a036 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -9,7 +9,7 @@ import os import re import time -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union import warnings import numpy as np @@ -2560,21 +2560,22 @@ def __init__(self, parent, group, encoding=None, errors="strict", **kwargs): self.group = group self.encoding = _ensure_encoding(encoding) self.errors = errors - self.set_version() @property def is_old_version(self) -> bool: return self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1 - def set_version(self): + @property + def version(self) -> Tuple[int, int, int]: """ compute and set our version """ version = _ensure_decoded(getattr(self.group._v_attrs, "pandas_version", None)) try: - self.version = tuple(int(x) for x in version.split(".")) - if len(self.version) == 2: - self.version = self.version + (0,) + version = tuple(int(x) for x in version.split(".")) + if len(version) == 2: + version = version + (0,) except AttributeError: - self.version = (0, 0, 0) + version = (0, 0, 0) + return version @property def pandas_type(self): @@ -2600,7 +2601,6 @@ def set_object_info(self): """ set my pandas type & version """ self.attrs.pandas_type = str(self.pandas_kind) self.attrs.pandas_version = str(_version) - self.set_version() def copy(self): new_self = copy.copy(self)
Make things in this file incrementally less stateful
https://api.github.com/repos/pandas-dev/pandas/pulls/29765
2019-11-21T04:14:30Z
2019-11-21T13:31:20Z
2019-11-21T13:31:20Z
2019-11-21T15:44:45Z
TST: add test for ffill/bfill for non unique multilevel
diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 3d9a349d94e10..c46180c1d11cd 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -911,6 +911,41 @@ def test_pct_change(test_series, freq, periods, fill_method, limit): tm.assert_frame_equal(result, expected.to_frame("vals")) +@pytest.mark.parametrize( + "func, expected_status", + [ + ("ffill", ["shrt", "shrt", "lng", np.nan, "shrt", "ntrl", "ntrl"]), + ("bfill", ["shrt", "lng", "lng", "shrt", "shrt", "ntrl", np.nan]), + ], +) +def test_ffill_bfill_non_unique_multilevel(func, expected_status): + # GH 19437 + date = pd.to_datetime( + [ + "2018-01-01", + "2018-01-01", + "2018-01-01", + "2018-01-01", + "2018-01-02", + "2018-01-01", + "2018-01-02", + ] + ) + symbol = ["MSFT", "MSFT", "MSFT", "AAPL", "AAPL", "TSLA", "TSLA"] + status = ["shrt", np.nan, "lng", np.nan, "shrt", "ntrl", np.nan] + + df = DataFrame({"date": date, "symbol": symbol, "status": status}) + df = df.set_index(["date", "symbol"]) + result = getattr(df.groupby("symbol")["status"], func)() + + index = MultiIndex.from_tuples( + tuples=list(zip(*[date, symbol])), names=["date", "symbol"] + ) + expected = Series(expected_status, index=index, name="status") + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("func", [np.any, np.all]) def test_any_all_np_func(func): # GH 20653
- [x] closes #19437 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29763
2019-11-21T01:29:57Z
2019-11-23T23:04:42Z
2019-11-23T23:04:41Z
2019-11-23T23:04:51Z
TST: add test for rolling max with DatetimeIndex
diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index 7055e5b538bea..02969a6c6e822 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -535,6 +535,18 @@ def test_ragged_max(self): expected["B"] = [0.0, 1, 2, 3, 4] tm.assert_frame_equal(result, expected) + def test_minutes_freq_max(self): + # GH 21096 + n = 10 + index = date_range(start="2018-1-1 01:00:00", freq="1min", periods=n) + s = Series(data=0, index=index) + s.iloc[1] = np.nan + s.iloc[-1] = 2 + result = s.rolling(window=f"{n}min").max() + expected = Series(data=[0] * (n - 1) + [2.0], index=index) + + tm.assert_series_equal(result, expected) + def test_ragged_apply(self, raw): df = self.ragged
- [x] closes #21096 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29761
2019-11-21T01:05:23Z
2019-11-25T22:50:54Z
2019-11-25T22:50:54Z
2019-11-30T01:14:42Z
TST: add test for unused level indexing raises KeyError
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index f0928820367e9..44829423be1bb 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -583,6 +583,17 @@ def test_stack_unstack_wrong_level_name(self, method): with pytest.raises(KeyError, match="does not match index name"): getattr(s, method)("mistake") + def test_unused_level_raises(self): + # GH 20410 + mi = MultiIndex( + levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]], + codes=[[1, 0], [1, 0]], + ) + df = DataFrame(-1, index=range(3), columns=mi) + + with pytest.raises(KeyError, match="notevenone"): + df["notevenone"] + def test_unstack_level_name(self): result = self.frame.unstack("second") expected = self.frame.unstack(level=1)
- [x] closes #20410 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29760
2019-11-21T00:52:57Z
2019-11-22T17:02:09Z
2019-11-22T17:02:09Z
2019-11-22T17:02:12Z
STY: fstrings in io.pytables
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 8afbd293a095b..b229e5b4e0f4e 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -368,9 +368,7 @@ def read_hdf(path_or_buf, key=None, mode: str = "r", **kwargs): exists = False if not exists: - raise FileNotFoundError( - "File {path} does not exist".format(path=path_or_buf) - ) + raise FileNotFoundError(f"File {path_or_buf} does not exist") store = HDFStore(path_or_buf, mode=mode, **kwargs) # can't auto open/close if we are using an iterator @@ -485,9 +483,7 @@ def __init__( if complib is not None and complib not in tables.filters.all_complibs: raise ValueError( - "complib only supports {libs} compression.".format( - libs=tables.filters.all_complibs - ) + f"complib only supports {tables.filters.all_complibs} compression." ) if complib is None and complevel is not None: @@ -533,9 +529,7 @@ def __getattr__(self, name: str): except (KeyError, ClosedFileError): pass raise AttributeError( - "'{object}' object has no attribute '{name}'".format( - object=type(self).__name__, name=name - ) + f"'{type(self).__name__}' object has no attribute '{name}'" ) def __contains__(self, key: str): @@ -553,9 +547,8 @@ def __len__(self) -> int: return len(self.groups()) def __repr__(self) -> str: - return "{type}\nFile path: {path}\n".format( - type=type(self), path=pprint_thing(self._path) - ) + pstr = pprint_thing(self._path) + return f"{type(self)}\nFile path: {pstr}\n" def __enter__(self): return self @@ -607,8 +600,8 @@ def open(self, mode: str = "a", **kwargs): # this would truncate, raise here if self.is_open: raise PossibleDataLossError( - "Re-opening the file [{0}] with mode [{1}] " - "will delete the current file!".format(self._path, self._mode) + f"Re-opening the file [{self._path}] with mode [{self._mode}] " + "will delete the current file!" ) self._mode = mode @@ -626,7 +619,7 @@ def open(self, mode: str = "a", **kwargs): self._handle = tables.open_file(self._path, self._mode, **kwargs) except IOError as err: # pragma: no cover if "can not be written" in str(err): - print("Opening {path} in read-only mode".format(path=self._path)) + print(f"Opening {self._path} in read-only mode") self._handle = tables.open_file(self._path, "r", **kwargs) else: raise @@ -636,18 +629,16 @@ def open(self, mode: str = "a", **kwargs): # trap PyTables >= 3.1 FILE_OPEN_POLICY exception # to provide an updated message if "FILE_OPEN_POLICY" in str(err): + hdf_version = tables.get_hdf5_version() err = ValueError( - "PyTables [{version}] no longer supports opening multiple " - "files\n" + f"PyTables [{tables.__version__}] no longer supports " + "opening multiple files\n" "even in read-only mode on this HDF5 version " - "[{hdf_version}]. You can accept this\n" + f"[{hdf_version}]. You can accept this\n" "and not open the same file multiple times at once,\n" "upgrade the HDF5 version, or downgrade to PyTables 3.0.0 " "which allows\n" - "files to be opened multiple times at once\n".format( - version=tables.__version__, - hdf_version=tables.get_hdf5_version(), - ) + "files to be opened multiple times at once\n" ) raise err @@ -716,7 +707,7 @@ def get(self, key: str): """ group = self.get_node(key) if group is None: - raise KeyError("No object named {key} in the file".format(key=key)) + raise KeyError(f"No object named {key} in the file") return self._read_group(group) def select( @@ -760,7 +751,7 @@ def select( """ group = self.get_node(key) if group is None: - raise KeyError("No object named {key} in the file".format(key=key)) + raise KeyError(f"No object named {key} in the file") # create the storer and axes where = _ensure_term(where, scope_level=1) @@ -900,11 +891,11 @@ def select_as_multiple( nrows = None for t, k in itertools.chain([(s, selector)], zip(tbls, keys)): if t is None: - raise KeyError("Invalid table [{key}]".format(key=k)) + raise KeyError(f"Invalid table [{k}]") if not t.is_table: raise TypeError( - "object [{obj}] is not a table, and cannot be used in all " - "select as multiple".format(obj=t.pathname) + f"object [{t.pathname}] is not a table, and cannot be used in all " + "select as multiple" ) if nrows is None: @@ -1289,7 +1280,7 @@ def get_storer(self, key: str): """ return the storer object for a key, raise if not in the file """ group = self.get_node(key) if group is None: - raise KeyError("No object named {key} in the file".format(key=key)) + raise KeyError(f"No object named {key} in the file") s = self._create_storer(group) s.infer_axes() @@ -1365,9 +1356,9 @@ def info(self) -> str: ------- str """ - output = "{type}\nFile path: {path}\n".format( - type=type(self), path=pprint_thing(self._path) - ) + path = pprint_thing(self._path) + output = f"{type(self)}\nFile path: {path}\n" + if self.is_open: lkeys = sorted(self.keys()) if len(lkeys): @@ -1382,11 +1373,8 @@ def info(self) -> str: values.append(pprint_thing(s or "invalid_HDFStore node")) except Exception as detail: keys.append(k) - values.append( - "[invalid_HDFStore node: {detail}]".format( - detail=pprint_thing(detail) - ) - ) + dstr = pprint_thing(detail) + values.append(f"[invalid_HDFStore node: {dstr}]") output += adjoin(12, keys, values) else: @@ -1399,7 +1387,7 @@ def info(self) -> str: # private methods ###### def _check_if_open(self): if not self.is_open: - raise ClosedFileError("{0} file is not open!".format(self._path)) + raise ClosedFileError(f"{self._path} file is not open!") def _validate_format(self, format: str, kwargs: Dict[str, Any]) -> Dict[str, Any]: """ validate / deprecate formats; return the new kwargs """ @@ -1409,7 +1397,7 @@ def _validate_format(self, format: str, kwargs: Dict[str, Any]) -> Dict[str, Any try: kwargs["format"] = _FORMAT_MAP[format.lower()] except KeyError: - raise TypeError("invalid HDFStore format specified [{0}]".format(format)) + raise TypeError(f"invalid HDFStore format specified [{format}]") return kwargs @@ -1418,16 +1406,9 @@ def _create_storer(self, group, format=None, value=None, append=False, **kwargs) def error(t): raise TypeError( - "cannot properly create the storer for: [{t}] [group->" - "{group},value->{value},format->{format},append->{append}," - "kwargs->{kwargs}]".format( - t=t, - group=group, - value=type(value), - format=format, - append=append, - kwargs=kwargs, - ) + f"cannot properly create the storer for: [{t}] [group->" + f"{group},value->{type(value)},format->{format},append->{append}," + f"kwargs->{kwargs}]" ) pt = _ensure_decoded(getattr(group._v_attrs, "pandas_type", None)) @@ -1768,7 +1749,7 @@ def __repr__(self) -> str: ) return ",".join( ( - "{key}->{value}".format(key=key, value=value) + f"{key}->{value}" for key, value in zip(["name", "cname", "axis", "pos", "kind"], temp) ) ) @@ -1898,12 +1879,10 @@ def validate_col(self, itemsize=None): itemsize = self.itemsize if c.itemsize < itemsize: raise ValueError( - "Trying to store a string with len [{itemsize}] in " - "[{cname}] column but\nthis column has a limit of " - "[{c_itemsize}]!\nConsider using min_itemsize to " - "preset the sizes on these columns".format( - itemsize=itemsize, cname=self.cname, c_itemsize=c.itemsize - ) + f"Trying to store a string with len [{itemsize}] in " + f"[{self.cname}] column but\nthis column has a limit of " + f"[{c.itemsize}]!\nConsider using min_itemsize to " + "preset the sizes on these columns" ) return c.itemsize @@ -1915,8 +1894,7 @@ def validate_attr(self, append: bool): existing_kind = getattr(self.attrs, self.kind_attr, None) if existing_kind is not None and existing_kind != self.kind: raise TypeError( - "incompatible kind in col [{existing} - " - "{self_kind}]".format(existing=existing_kind, self_kind=self.kind) + f"incompatible kind in col [{existing_kind} - {self.kind}]" ) def update_info(self, info): @@ -1942,14 +1920,9 @@ def update_info(self, info): else: raise ValueError( - "invalid info for [{name}] for [{key}], " - "existing_value [{existing_value}] conflicts with " - "new value [{value}]".format( - name=self.name, - key=key, - existing_value=existing_value, - value=value, - ) + f"invalid info for [{self.name}] for [{key}], " + f"existing_value [{existing_value}] conflicts with " + f"new value [{value}]" ) else: if value is not None or existing_value is not None: @@ -2060,7 +2033,7 @@ def create_for_block(cls, i=None, name=None, cname=None, version=None, **kwargs) """ return a new datacol with the block i """ if cname is None: - cname = name or "values_block_{idx}".format(idx=i) + cname = name or f"values_block_{i}" if name is None: name = cname @@ -2070,7 +2043,8 @@ def create_for_block(cls, i=None, name=None, cname=None, version=None, **kwargs) if version[0] == 0 and version[1] <= 10 and version[2] == 0: m = re.search(r"values_block_(\d+)", name) if m: - name = "values_{group}".format(group=m.groups()[0]) + grp = m.groups()[0] + name = f"values_{grp}" except IndexError: pass @@ -2090,9 +2064,9 @@ def __init__( ): super().__init__(values=values, kind=kind, typ=typ, cname=cname, **kwargs) self.dtype = None - self.dtype_attr = "{name}_dtype".format(name=self.name) + self.dtype_attr = f"{self.name}_dtype" self.meta = meta - self.meta_attr = "{name}_meta".format(name=self.name) + self.meta_attr = f"{self.name}_meta" self.set_data(data) self.set_metadata(metadata) @@ -2104,7 +2078,7 @@ def __repr__(self) -> str: ) return ",".join( ( - "{key}->{value}".format(key=key, value=value) + f"{key}->{value}" for key, value in zip(["name", "cname", "dtype", "kind", "shape"], temp) ) ) @@ -2158,11 +2132,7 @@ def set_kind(self): elif dtype.startswith("bool"): self.kind = "bool" else: - raise AssertionError( - "cannot interpret dtype of [{dtype}] in [{obj}]".format( - dtype=dtype, obj=self - ) - ) + raise AssertionError(f"cannot interpret dtype of [{dtype}] in [{self}]") # set my typ if we need if self.typ is None: @@ -2253,10 +2223,8 @@ def set_atom_string( inferred_type = lib.infer_dtype(col.ravel(), skipna=False) if inferred_type != "string": raise TypeError( - "Cannot serialize the column [{item}] because\n" - "its data contents are [{type}] object dtype".format( - item=item, type=inferred_type - ) + f"Cannot serialize the column [{item}] because\n" + f"its data contents are [{inferred_type}] object dtype" ) # itemsize is the maximum length of a string (along any dimension) @@ -2279,18 +2247,18 @@ def set_atom_string( self.itemsize = itemsize self.kind = "string" self.typ = self.get_atom_string(block, itemsize) - self.set_data( - data_converted.astype("|S{size}".format(size=itemsize), copy=False) - ) + self.set_data(data_converted.astype(f"|S{itemsize}", copy=False)) def get_atom_coltype(self, kind=None): """ return the PyTables column class for this column """ if kind is None: kind = self.kind if self.kind.startswith("uint"): - col_name = "UInt{name}Col".format(name=kind[4:]) + k4 = kind[4:] + col_name = f"UInt{k4}Col" else: - col_name = "{name}Col".format(name=kind.capitalize()) + kcap = kind.capitalize() + col_name = f"{kcap}Col" return getattr(_tables(), col_name) @@ -2568,10 +2536,9 @@ def __repr__(self) -> str: s = self.shape if s is not None: if isinstance(s, (list, tuple)): - s = "[{shape}]".format(shape=",".join(pprint_thing(x) for x in s)) - return "{type:12.12} (shape->{shape})".format( - type=self.pandas_type, shape=s - ) + jshape = ",".join(pprint_thing(x) for x in s) + s = f"[{jshape}]" + return f"{self.pandas_type:12.12} (shape->{s})" return self.pandas_type def set_object_info(self): @@ -2798,7 +2765,7 @@ def read_array( return ret def read_index(self, key, **kwargs): - variety = _ensure_decoded(getattr(self.attrs, "{key}_variety".format(key=key))) + variety = _ensure_decoded(getattr(self.attrs, f"{key}_variety")) if variety == "multi": return self.read_multi_index(key, **kwargs) @@ -2810,22 +2777,20 @@ def read_index(self, key, **kwargs): _, index = self.read_index_node(getattr(self.group, key), **kwargs) return index else: # pragma: no cover - raise TypeError( - "unrecognized index variety: {variety}".format(variety=variety) - ) + raise TypeError(f"unrecognized index variety: {variety}") def write_index(self, key, index): if isinstance(index, MultiIndex): - setattr(self.attrs, "{key}_variety".format(key=key), "multi") + setattr(self.attrs, f"{key}_variety", "multi") self.write_multi_index(key, index) elif isinstance(index, BlockIndex): - setattr(self.attrs, "{key}_variety".format(key=key), "block") + setattr(self.attrs, f"{key}_variety", "block") self.write_block_index(key, index) elif isinstance(index, IntIndex): - setattr(self.attrs, "{key}_variety".format(key=key), "sparseint") + setattr(self.attrs, f"{key}_variety", "sparseint") self.write_sparse_intindex(key, index) else: - setattr(self.attrs, "{key}_variety".format(key=key), "regular") + setattr(self.attrs, f"{key}_variety", "regular") converted = _convert_index( "index", index, self.encoding, self.errors, self.format_type ) @@ -2846,27 +2811,27 @@ def write_index(self, key, index): node._v_attrs.tz = _get_tz(index.tz) def write_block_index(self, key, index): - self.write_array("{key}_blocs".format(key=key), index.blocs) - self.write_array("{key}_blengths".format(key=key), index.blengths) - setattr(self.attrs, "{key}_length".format(key=key), index.length) + self.write_array(f"{key}_blocs", index.blocs) + self.write_array(f"{key}_blengths", index.blengths) + setattr(self.attrs, f"{key}_length", index.length) def read_block_index(self, key, **kwargs) -> BlockIndex: - length = getattr(self.attrs, "{key}_length".format(key=key)) - blocs = self.read_array("{key}_blocs".format(key=key), **kwargs) - blengths = self.read_array("{key}_blengths".format(key=key), **kwargs) + length = getattr(self.attrs, f"{key}_length") + blocs = self.read_array(f"{key}_blocs", **kwargs) + blengths = self.read_array(f"{key}_blengths", **kwargs) return BlockIndex(length, blocs, blengths) def write_sparse_intindex(self, key, index): - self.write_array("{key}_indices".format(key=key), index.indices) - setattr(self.attrs, "{key}_length".format(key=key), index.length) + self.write_array(f"{key}_indices", index.indices) + setattr(self.attrs, f"{key}_length", index.length) def read_sparse_intindex(self, key, **kwargs) -> IntIndex: - length = getattr(self.attrs, "{key}_length".format(key=key)) - indices = self.read_array("{key}_indices".format(key=key), **kwargs) + length = getattr(self.attrs, f"{key}_length") + indices = self.read_array(f"{key}_indices", **kwargs) return IntIndex(length, indices) def write_multi_index(self, key, index): - setattr(self.attrs, "{key}_nlevels".format(key=key), index.nlevels) + setattr(self.attrs, f"{key}_nlevels", index.nlevels) for i, (lev, level_codes, name) in enumerate( zip(index.levels, index.codes, index.names) @@ -2876,7 +2841,7 @@ def write_multi_index(self, key, index): raise NotImplementedError( "Saving a MultiIndex with an extension dtype is not supported." ) - level_key = "{key}_level{idx}".format(key=key, idx=i) + level_key = f"{key}_level{i}" conv_level = _convert_index( level_key, lev, self.encoding, self.errors, self.format_type ) @@ -2886,25 +2851,25 @@ def write_multi_index(self, key, index): node._v_attrs.name = name # write the name - setattr(node._v_attrs, "{key}_name{name}".format(key=key, name=name), name) + setattr(node._v_attrs, f"{key}_name{name}", name) # write the labels - label_key = "{key}_label{idx}".format(key=key, idx=i) + label_key = f"{key}_label{i}" self.write_array(label_key, level_codes) def read_multi_index(self, key, **kwargs) -> MultiIndex: - nlevels = getattr(self.attrs, "{key}_nlevels".format(key=key)) + nlevels = getattr(self.attrs, f"{key}_nlevels") levels = [] codes = [] names = [] for i in range(nlevels): - level_key = "{key}_level{idx}".format(key=key, idx=i) + level_key = f"{key}_level{i}" name, lev = self.read_index_node(getattr(self.group, level_key), **kwargs) levels.append(lev) names.append(name) - label_key = "{key}_label{idx}".format(key=key, idx=i) + label_key = f"{key}_label{i}" level_codes = self.read_array(label_key, **kwargs) codes.append(level_codes) @@ -3098,7 +3063,7 @@ def shape(self): # items items = 0 for i in range(self.nblocks): - node = getattr(self.group, "block{idx}_items".format(idx=i)) + node = getattr(self.group, f"block{i}_items") shape = getattr(node, "shape", None) if shape is not None: items += shape[0] @@ -3131,17 +3096,15 @@ def read(self, start=None, stop=None, **kwargs): for i in range(self.ndim): _start, _stop = (start, stop) if i == select_axis else (None, None) - ax = self.read_index("axis{idx}".format(idx=i), start=_start, stop=_stop) + ax = self.read_index(f"axis{i}", start=_start, stop=_stop) axes.append(ax) items = axes[0] blocks = [] for i in range(self.nblocks): - blk_items = self.read_index("block{idx}_items".format(idx=i)) - values = self.read_array( - "block{idx}_values".format(idx=i), start=_start, stop=_stop - ) + blk_items = self.read_index(f"block{i}_items") + values = self.read_array(f"block{i}_values", start=_start, stop=_stop) blk = make_block( values, placement=items.get_indexer(blk_items), ndim=len(axes) ) @@ -3160,17 +3123,15 @@ def write(self, obj, **kwargs): if i == 0: if not ax.is_unique: raise ValueError("Columns index has to be unique for fixed format") - self.write_index("axis{idx}".format(idx=i), ax) + self.write_index(f"axis{i}", ax) # Supporting mixed-type DataFrame objects...nontrivial self.attrs.nblocks = len(data.blocks) for i, blk in enumerate(data.blocks): # I have no idea why, but writing values before items fixed #2299 blk_items = data.items.take(blk.mgr_locs) - self.write_array( - "block{idx}_values".format(idx=i), blk.values, items=blk_items - ) - self.write_index("block{idx}_items".format(idx=i), blk_items) + self.write_array(f"block{i}_values", blk.values, items=blk_items) + self.write_index(f"block{i}_items", blk_items) class FrameFixed(BlockManagerFixed): @@ -3231,25 +3192,19 @@ def format_type(self) -> str: def __repr__(self) -> str: """ return a pretty representation of myself """ self.infer_axes() - dc = ",dc->[{columns}]".format( - columns=(",".join(self.data_columns) if len(self.data_columns) else "") - ) + jdc = ",".join(self.data_columns) if len(self.data_columns) else "" + dc = f",dc->[{jdc}]" ver = "" if self.is_old_version: - ver = "[{version}]".format(version=".".join(str(x) for x in self.version)) + jver = ".".join(str(x) for x in self.version) + ver = f"[{jver}]" + jindex_axes = ",".join(a.name for a in self.index_axes) return ( - "{pandas_type:12.12}{ver} (typ->{table_type},nrows->{nrows}," - "ncols->{ncols},indexers->[{index_axes}]{dc})".format( - pandas_type=self.pandas_type, - ver=ver, - table_type=self.table_type_short, - nrows=self.nrows, - ncols=self.ncols, - index_axes=(",".join(a.name for a in self.index_axes)), - dc=dc, - ) + f"{self.pandas_type:12.12}{ver} " + f"(typ->{self.table_type_short},nrows->{self.nrows}," + f"ncols->{self.ncols},indexers->[{jindex_axes}]{dc})" ) def __getitem__(self, c): @@ -3267,9 +3222,7 @@ def validate(self, other): if other.table_type != self.table_type: raise TypeError( "incompatible table_type with existing " - "[{other} - {self}]".format( - other=other.table_type, self=self.table_type - ) + f"[{other.table_type} - {self.table_type}]" ) for c in ["index_axes", "non_index_axes", "values_axes"]: @@ -3282,16 +3235,14 @@ def validate(self, other): oax = ov[i] if sax != oax: raise ValueError( - "invalid combinate of [{c}] on appending data " - "[{sax}] vs current table [{oax}]".format( - c=c, sax=sax, oax=oax - ) + f"invalid combinate of [{c}] on appending data " + f"[{sax}] vs current table [{oax}]" ) # should never get here raise Exception( - "invalid combinate of [{c}] on appending data [{sv}] vs " - "current table [{ov}]".format(c=c, sv=sv, ov=ov) + f"invalid combinate of [{c}] on appending data [{sv}] vs " + f"current table [{ov}]" ) @property @@ -3308,8 +3259,7 @@ def validate_multiindex(self, obj): new object """ levels = [ - l if l is not None else "level_{0}".format(i) - for i, l in enumerate(obj.index.names) + l if l is not None else f"level_{i}" for i, l in enumerate(obj.index.names) ] try: return obj.reset_index(), levels @@ -3396,7 +3346,8 @@ def values_cols(self) -> List[str]: def _get_metadata_path(self, key) -> str: """ return the metadata pathname for this key """ - return "{group}/meta/{key}/meta".format(group=self.group._v_pathname, key=key) + group = self.group._v_pathname + return f"{group}/meta/{key}/meta" def write_metadata(self, key: str, values): """ @@ -3476,8 +3427,8 @@ def validate_min_itemsize(self, min_itemsize): continue if k not in q: raise ValueError( - "min_itemsize has the key [{key}] which is not an axis or " - "data_column".format(key=k) + f"min_itemsize has the key [{k}] which is not an axis or " + "data_column" ) @property @@ -3646,8 +3597,8 @@ def validate_data_columns(self, data_columns, min_itemsize): info = self.info.get(axis, dict()) if info.get("type") == "MultiIndex" and data_columns: raise ValueError( - "cannot use a multi-index on axis [{0}] with " - "data_columns {1}".format(axis, data_columns) + f"cannot use a multi-index on axis [{axis}] with " + f"data_columns {data_columns}" ) # evaluate the passed data_columns, True == use all columns @@ -3706,9 +3657,10 @@ def create_axes( try: axes = _AXES_MAP[type(obj)] except KeyError: + group = self.group._v_name raise TypeError( - "cannot properly create the storer for: [group->{group}," - "value->{value}]".format(group=self.group._v_name, value=type(obj)) + f"cannot properly create the storer for: [group->{group}," + f"value->{type(obj)}]" ) # map axes to numbers @@ -3834,11 +3786,10 @@ def get_blk_items(mgr, blocks): new_blocks.append(b) new_blk_items.append(b_items) except (IndexError, KeyError): + jitems = ",".join(pprint_thing(item) for item in items) raise ValueError( - "cannot match existing table structure for [{items}] " - "on appending data".format( - items=(",".join(pprint_thing(item) for item in items)) - ) + f"cannot match existing table structure for [{jitems}] " + "on appending data" ) blocks = new_blocks blk_items = new_blk_items @@ -3867,10 +3818,8 @@ def get_blk_items(mgr, blocks): existing_col = existing_table.values_axes[i] except (IndexError, KeyError): raise ValueError( - "Incompatible appended table [{blocks}]" - "with existing table [{table}]".format( - blocks=blocks, table=existing_table.values_axes - ) + f"Incompatible appended table [{blocks}]" + f"with existing table [{existing_table.values_axes}]" ) else: existing_col = None @@ -3954,10 +3903,7 @@ def process_filter(field, filt): takers = op(values, filt) return obj.loc(axis=axis_number)[takers] - raise ValueError( - "cannot find the field [{field}] for " - "filtering!".format(field=field) - ) + raise ValueError(f"cannot find the field [{field}] for filtering!") obj = process_filter(field, filt) @@ -4052,8 +3998,8 @@ def read_column( if not a.is_data_indexable: raise ValueError( - "column [{column}] can not be extracted individually; " - "it is not data indexable".format(column=column) + f"column [{column}] can not be extracted individually; " + "it is not data indexable" ) # column must be an indexable or a data column @@ -4067,7 +4013,7 @@ def read_column( ) return Series(_set_tz(a.take_data(), a.tz, True), name=column) - raise KeyError("column [{column}] not found in the table".format(column=column)) + raise KeyError(f"column [{column}] not found in the table") class WORMTable(Table): @@ -4264,16 +4210,14 @@ def write_data_chunk(self, rows, indexes, mask, values): rows = rows[m] except Exception as detail: - raise Exception("cannot create row-data -> {detail}".format(detail=detail)) + raise Exception(f"cannot create row-data -> {detail}") try: if len(rows): self.table.append(rows) self.table.flush() except Exception as detail: - raise TypeError( - "tables cannot write this data -> {detail}".format(detail=detail) - ) + raise TypeError(f"tables cannot write this data -> {detail}") def delete( self, @@ -4733,9 +4677,7 @@ def _convert_index(name: str, index, encoding=None, errors="strict", format_type index_name=index_name, ) raise TypeError( - "[unicode] is not supported as a in index type for [{0}] formats".format( - format_type - ) + f"[unicode] is not supported as a in index type for [{format_type}] formats" ) elif inferred_type == "integer": @@ -4786,7 +4728,7 @@ def _unconvert_index(data, kind, encoding=None, errors="strict"): elif kind == "object": index = np.asarray(data[0]) else: # pragma: no cover - raise ValueError("unrecognized index type {kind}".format(kind=kind)) + raise ValueError(f"unrecognized index type {kind}") return index @@ -4818,7 +4760,7 @@ def _convert_string_array(data, encoding, errors, itemsize=None): ensured = ensure_object(data.ravel()) itemsize = max(1, libwriters.max_len_string_array(ensured)) - data = np.asarray(data, dtype="S{size}".format(size=itemsize)) + data = np.asarray(data, dtype=f"S{itemsize}") return data @@ -4847,7 +4789,7 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None, errors="strict"): if encoding is not None and len(data): itemsize = libwriters.max_len_string_array(ensure_object(data)) - dtype = "U{0}".format(itemsize) + dtype = f"U{itemsize}" if isinstance(data[0], bytes): data = Series(data).str.decode(encoding, errors=errors).values @@ -4960,16 +4902,15 @@ def generate(self, where): except NameError: # raise a nice message, suggesting that the user should use # data_columns + qkeys = ",".join(q.keys()) raise ValueError( - "The passed where expression: {0}\n" + f"The passed where expression: {where}\n" " contains an invalid variable reference\n" " all of the variable references must be a " "reference to\n" " an axis (e.g. 'index' or 'columns'), or a " "data_column\n" - " The currently defined references are: {1}\n".format( - where, ",".join(q.keys()) - ) + f" The currently defined references are: {qkeys}\n" ) def select(self):
honestly not sure why ive got such a bee in my bonnet about this file
https://api.github.com/repos/pandas-dev/pandas/pulls/29758
2019-11-20T23:26:32Z
2019-11-23T23:10:38Z
2019-11-23T23:10:38Z
2019-11-23T23:33:08Z
ANN: types for _create_storer
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b229e5b4e0f4e..b8ed83cd3ebd7 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -174,9 +174,6 @@ class DuplicateWarning(Warning): and is the default for append operations """ -# map object types -_TYPE_MAP = {Series: "series", DataFrame: "frame"} - # storer class map _STORER_MAP = { "series": "SeriesFixed", @@ -797,9 +794,10 @@ def select_as_coordinates( stop : integer (defaults to None), row number to stop selection """ where = _ensure_term(where, scope_level=1) - return self.get_storer(key).read_coordinates( - where=where, start=start, stop=stop, **kwargs - ) + tbl = self.get_storer(key) + if not isinstance(tbl, Table): + raise TypeError("can only read_coordinates with a table") + return tbl.read_coordinates(where=where, start=start, stop=stop, **kwargs) def select_column(self, key: str, column: str, **kwargs): """ @@ -820,7 +818,10 @@ def select_column(self, key: str, column: str, **kwargs): is part of a data block) """ - return self.get_storer(key).read_column(column=column, **kwargs) + tbl = self.get_storer(key) + if not isinstance(tbl, Table): + raise TypeError("can only read_column with a table") + return tbl.read_column(column=column, **kwargs) def select_as_multiple( self, @@ -903,8 +904,12 @@ def select_as_multiple( elif t.nrows != nrows: raise ValueError("all tables must have exactly the same nrows!") + # The isinstance checks here are redundant with the check above, + # but necessary for mypy; see GH#29757 + _tbls = [x for x in tbls if isinstance(x, Table)] + # axis is the concentration axes - axis = list({t.non_index_axes[0][0] for t in tbls})[0] + axis = list({t.non_index_axes[0][0] for t in _tbls})[0] def func(_start, _stop, _where): @@ -1003,9 +1008,9 @@ def remove(self, key: str, where=None, start=None, stop=None): ) # we are actually trying to remove a node (with children) - s = self.get_node(key) - if s is not None: - s._f_remove(recursive=True) + node = self.get_node(key) + if node is not None: + node._f_remove(recursive=True) return None # remove the node @@ -1187,7 +1192,7 @@ def create_table_index(self, key: str, **kwargs): if s is None: return - if not s.is_table: + if not isinstance(s, Table): raise TypeError("cannot create table index on a Fixed format store") s.create_index(**kwargs) @@ -1276,7 +1281,7 @@ def get_node(self, key: str): except _table_mod.exceptions.NoSuchNodeError: # type: ignore return None - def get_storer(self, key: str): + def get_storer(self, key: str) -> Union["GenericFixed", "Table"]: """ return the storer object for a key, raise if not in the file """ group = self.get_node(key) if group is None: @@ -1329,7 +1334,7 @@ def copy( new_store.remove(k) data = self.select(k) - if s.is_table: + if isinstance(s, Table): index: Union[bool, list] = False if propindexes: @@ -1401,13 +1406,16 @@ def _validate_format(self, format: str, kwargs: Dict[str, Any]) -> Dict[str, Any return kwargs - def _create_storer(self, group, format=None, value=None, append=False, **kwargs): + def _create_storer( + self, group, format=None, value=None, **kwargs + ) -> Union["GenericFixed", "Table"]: """ return a suitable class to operate """ def error(t): - raise TypeError( + # return instead of raising so mypy can tell where we are raising + return TypeError( f"cannot properly create the storer for: [{t}] [group->" - f"{group},value->{type(value)},format->{format},append->{append}," + f"{group},value->{type(value)},format->{format}," f"kwargs->{kwargs}]" ) @@ -1419,6 +1427,7 @@ def error(t): if value is None: _tables() + assert _table_mod is not None # for mypy if getattr(group, "table", None) or isinstance( group, _table_mod.table.Table ): @@ -1430,11 +1439,11 @@ def error(t): "nor a value are passed" ) else: - + _TYPE_MAP = {Series: "series", DataFrame: "frame"} try: pt = _TYPE_MAP[type(value)] except KeyError: - error("_TYPE_MAP") + raise error("_TYPE_MAP") # we are actually a table if format == "table": @@ -1445,7 +1454,7 @@ def error(t): try: return globals()[_STORER_MAP[pt]](self, group, **kwargs) except KeyError: - error("_STORER_MAP") + raise error("_STORER_MAP") # existing node (and must be a table) if tt is None: @@ -1486,7 +1495,7 @@ def error(t): try: return globals()[_TABLE_MAP[tt]](self, group, **kwargs) except KeyError: - error("_TABLE_MAP") + raise error("_TABLE_MAP") def _write_to_group( self, @@ -1532,9 +1541,7 @@ def _write_to_group( group = self._handle.create_group(path, p) path = new_path - s = self._create_storer( - group, format, value, append=append, encoding=encoding, **kwargs - ) + s = self._create_storer(group, format, value, encoding=encoding, **kwargs) if append: # raise if we are trying to append to a Fixed format, # or a table that exists (and we are putting) @@ -1551,7 +1558,7 @@ def _write_to_group( # write the object s.write(obj=value, append=append, complib=complib, **kwargs) - if s.is_table and index: + if isinstance(s, Table) and index: s.create_index(columns=index) def _read_group(self, group, **kwargs): @@ -1582,11 +1589,12 @@ class TableIterator: chunksize: Optional[int] store: HDFStore + s: Union["GenericFixed", "Table"] def __init__( self, store: HDFStore, - s, + s: Union["GenericFixed", "Table"], func, where, nrows, @@ -1649,7 +1657,7 @@ def get_result(self, coordinates: bool = False): # return the actual iterator if self.chunksize is not None: - if not self.s.is_table: + if not isinstance(self.s, Table): raise TypeError("can only use an iterator or chunksize on a table") self.coordinates = self.s.read_coordinates(where=self.where) @@ -1658,6 +1666,8 @@ def get_result(self, coordinates: bool = False): # if specified read via coordinates (necessary for multiple selections if coordinates: + if not isinstance(self.s, Table): + raise TypeError("can only read_coordinates on a table") where = self.s.read_coordinates( where=self.where, start=self.start, stop=self.stop )
1) Annotate return type for _create_storer 2) Annotate other functions that we can reason about given 1 3) Fixups to address mypy warnings caused by 1 and 2
https://api.github.com/repos/pandas-dev/pandas/pulls/29757
2019-11-20T22:13:18Z
2019-11-25T23:02:43Z
2019-11-25T23:02:43Z
2019-11-25T23:16:18Z
CLN: io.pytables
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 7c447cbf78677..9d2642ae414d0 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1604,10 +1604,11 @@ class TableIterator: """ chunksize: Optional[int] + store: HDFStore def __init__( self, - store, + store: HDFStore, s, func, where, @@ -1616,7 +1617,7 @@ def __init__( stop=None, iterator: bool = False, chunksize=None, - auto_close=False, + auto_close: bool = False, ): self.store = store self.s = s @@ -1772,9 +1773,6 @@ def set_pos(self, pos: int): self.typ._v_pos = pos return self - def set_table(self, table): - self.table = table - def __repr__(self) -> str: temp = tuple( map(pprint_thing, (self.name, self.cname, self.axis, self.pos, self.kind)) @@ -1800,8 +1798,7 @@ def __ne__(self, other) -> bool: def is_indexed(self) -> bool: """ return whether I am an indexed column """ if not hasattr(self.table, "cols"): - # e.g. if self.set_table hasn't been called yet, self.table - # will be None. + # e.g. if infer hasn't been called yet, self.table will be None. return False # GH#29692 mypy doesn't recognize self.table as having a "cols" attribute # 'error: "None" has no attribute "cols"' @@ -1815,7 +1812,7 @@ def infer(self, handler): """infer this column from the table: create and return a new object""" table = handler.table new_self = self.copy() - new_self.set_table(table) + new_self.table = table new_self.get_attr() new_self.read_metadata(handler) return new_self @@ -1896,7 +1893,7 @@ def validate_names(self): pass def validate_and_set(self, handler: "AppendableTable", append: bool): - self.set_table(handler.table) + self.table = handler.table self.validate_col() self.validate_attr(append) self.validate_metadata(handler) @@ -2941,13 +2938,8 @@ def read_index_node( data = node[start:stop] # If the index was an empty array write_array_empty() will # have written a sentinel. Here we relace it with the original. - if "shape" in node._v_attrs and self._is_empty_array( - getattr(node._v_attrs, "shape") - ): - data = np.empty( - getattr(node._v_attrs, "shape"), - dtype=getattr(node._v_attrs, "value_type"), - ) + if "shape" in node._v_attrs and self._is_empty_array(node._v_attrs.shape): + data = np.empty(node._v_attrs.shape, dtype=node._v_attrs.value_type,) kind = _ensure_decoded(node._v_attrs.kind) name = None @@ -3126,7 +3118,7 @@ class SeriesFixed(GenericFixed): @property def shape(self): try: - return (len(getattr(self.group, "values")),) + return (len(self.group.values),) except (TypeError, AttributeError): return None @@ -3161,7 +3153,7 @@ def shape(self): items += shape[0] # data shape - node = getattr(self.group, "block0_values") + node = self.group.block0_values shape = getattr(node, "shape", None) if shape is not None: shape = list(shape[0 : (ndim - 1)]) @@ -3481,10 +3473,6 @@ def read_metadata(self, key): return self.parent.select(self._get_metadata_path(key)) return None - def set_info(self): - """ update our table index info """ - self.attrs.info = self.info - def set_attrs(self): """ set our table type & indexables """ self.attrs.table_type = str(self.table_type) @@ -3497,7 +3485,7 @@ def set_attrs(self): self.attrs.errors = self.errors self.attrs.levels = self.levels self.attrs.metadata = self.metadata - self.set_info() + self.attrs.info = self.info def get_attrs(self): """ retrieve our attributes """ @@ -4230,7 +4218,7 @@ def write( # table = self.table # update my info - self.set_info() + self.attrs.info = self.info # validate the axes and set the kinds for a in self.axes: @@ -4964,6 +4952,7 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None, errors="strict"): def _maybe_convert(values: np.ndarray, val_kind, encoding, errors): + val_kind = _ensure_decoded(val_kind) if _need_convert(val_kind): conv = _get_converter(val_kind, encoding, errors) # conv = np.frompyfunc(conv, 1, 1) @@ -4971,8 +4960,7 @@ def _maybe_convert(values: np.ndarray, val_kind, encoding, errors): return values -def _get_converter(kind, encoding, errors): - kind = _ensure_decoded(kind) +def _get_converter(kind: str, encoding, errors): if kind == "datetime64": return lambda x: np.asarray(x, dtype="M8[ns]") elif kind == "datetime": @@ -4980,11 +4968,10 @@ def _get_converter(kind, encoding, errors): elif kind == "string": return lambda x: _unconvert_string_array(x, encoding=encoding, errors=errors) else: # pragma: no cover - raise ValueError("invalid kind {kind}".format(kind=kind)) + raise ValueError(f"invalid kind {kind}") def _need_convert(kind) -> bool: - kind = _ensure_decoded(kind) if kind in ("datetime", "datetime64", "string"): return True return False
This is easy stuff broken off of a tough type-inference branch
https://api.github.com/repos/pandas-dev/pandas/pulls/29756
2019-11-20T21:56:19Z
2019-11-21T13:00:32Z
2019-11-21T13:00:32Z
2019-11-21T15:46:31Z
Remove Ambiguous Behavior of Tuple as Grouping
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..cc270366ac940 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -313,6 +313,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed the previously deprecated :meth:`Series.get_value`, :meth:`Series.set_value`, :meth:`DataFrame.get_value`, :meth:`DataFrame.set_value` (:issue:`17739`) - Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to False (:issue:`27600`) - Removed support for nested renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`18529`) +- A tuple passed to :meth:`DataFrame.groupby` is now exclusively treated as a single key (:issue:`18314`) - Removed :meth:`Series.from_array` (:issue:`18258`) - Removed :meth:`DataFrame.from_items` (:issue:`18458`) - Removed :meth:`DataFrame.as_matrix`, :meth:`Series.as_matrix` (:issue:`18458`) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 21c085c775399..232315660da8d 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -14,8 +14,10 @@ class providing the base-class of operations. import re import types from typing import ( + Callable, Dict, FrozenSet, + Hashable, Iterable, List, Mapping, @@ -343,6 +345,15 @@ def _group_selection_context(groupby): groupby._reset_group_selection() +_KeysArgType = Union[ + Hashable, + List[Hashable], + Callable[[Hashable], Hashable], + List[Callable[[Hashable], Hashable]], + Mapping[Hashable, Hashable], +] + + class _GroupBy(PandasObject, SelectionMixin): _group_selection = None _apply_whitelist = frozenset() # type: FrozenSet[str] @@ -350,7 +361,7 @@ class _GroupBy(PandasObject, SelectionMixin): def __init__( self, obj: NDFrame, - keys=None, + keys: Optional[_KeysArgType] = None, axis: int = 0, level=None, grouper: "Optional[ops.BaseGrouper]" = None, @@ -2504,7 +2515,7 @@ def _reindex_output( @Appender(GroupBy.__doc__) def get_groupby( obj: NDFrame, - by=None, + by: Optional[_KeysArgType] = None, axis: int = 0, level=None, grouper: "Optional[ops.BaseGrouper]" = None, diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 2b946d1ff0a7a..74195b0746091 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -4,7 +4,6 @@ """ from typing import Hashable, List, Optional, Tuple -import warnings import numpy as np @@ -14,7 +13,6 @@ ensure_categorical, is_categorical_dtype, is_datetime64_dtype, - is_hashable, is_list_like, is_scalar, is_timedelta64_dtype, @@ -514,28 +512,6 @@ def get_grouper( elif isinstance(key, ops.BaseGrouper): return key, [], obj - # In the future, a tuple key will always mean an actual key, - # not an iterable of keys. In the meantime, we attempt to provide - # a warning. We can assume that the user wanted a list of keys when - # the key is not in the index. We just have to be careful with - # unhashable elements of `key`. Any unhashable elements implies that - # they wanted a list of keys. - # https://github.com/pandas-dev/pandas/issues/18314 - if isinstance(key, tuple): - all_hashable = is_hashable(key) - if ( - all_hashable and key not in obj and set(key).issubset(obj) - ) or not all_hashable: - # column names ('a', 'b') -> ['a', 'b'] - # arrays like (a, b) -> [a, b] - msg = ( - "Interpreting tuple 'by' as a list of keys, rather than " - "a single key. Use 'by=[...]' instead of 'by=(...)'. In " - "the future, a tuple will always mean a single key." - ) - warnings.warn(msg, FutureWarning, stacklevel=5) - key = list(key) - if not isinstance(key, list): keys = [key] match_axis_length = False diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index b848e9caad9be..5f454f7aefae4 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1734,34 +1734,23 @@ def test_empty_dataframe_groupby(): tm.assert_frame_equal(result, expected) -def test_tuple_warns(): +def test_tuple_as_grouping(): # https://github.com/pandas-dev/pandas/issues/18314 df = pd.DataFrame( { - ("a", "b"): [1, 1, 2, 2], - "a": [1, 1, 1, 2], - "b": [1, 2, 2, 2], + ("a", "b"): [1, 1, 1, 1], + "a": [2, 2, 2, 2], + "b": [2, 2, 2, 2], "c": [1, 1, 1, 1], } ) - with tm.assert_produces_warning(FutureWarning) as w: - df[["a", "b", "c"]].groupby(("a", "b")).c.mean() - assert "Interpreting tuple 'by' as a list" in str(w[0].message) + with pytest.raises(KeyError): + df[["a", "b", "c"]].groupby(("a", "b")) - with tm.assert_produces_warning(None): - df.groupby(("a", "b")).c.mean() - - -def test_tuple_warns_unhashable(): - # https://github.com/pandas-dev/pandas/issues/18314 - business_dates = date_range(start="4/1/2014", end="6/30/2014", freq="B") - df = DataFrame(1, index=business_dates, columns=["a", "b"]) - - with tm.assert_produces_warning(FutureWarning) as w: - df.groupby((df.index.year, df.index.month)).nth([0, 3, -1]) - - assert "Interpreting tuple 'by' as a list" in str(w[0].message) + result = df.groupby(("a", "b"))["c"].sum() + expected = pd.Series([4], name="c", index=pd.Index([1], name=("a", "b"))) + tm.assert_series_equal(result, expected) def test_tuple_correct_keyerror():
follow up to #18314
https://api.github.com/repos/pandas-dev/pandas/pulls/29755
2019-11-20T20:54:13Z
2019-11-25T23:44:13Z
2019-11-25T23:44:13Z
2019-11-29T21:33:40Z
TYP: annotate queryables
diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 524013ceef5ff..41d7f96f5e96d 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -55,7 +55,7 @@ class UndefinedVariableError(NameError): NameError subclass for local variables. """ - def __init__(self, name, is_local): + def __init__(self, name, is_local: bool): if is_local: msg = "local variable {0!r} is not defined" else: @@ -69,6 +69,8 @@ def __new__(cls, name, env, side=None, encoding=None): supr_new = super(Term, klass).__new__ return supr_new(klass) + is_local: bool + def __init__(self, name, env, side=None, encoding=None): # name is a str for Term, but may be something else for subclasses self._name = name diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index ff7e713b3e71a..8dee273517f88 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -2,7 +2,7 @@ import ast from functools import partial -from typing import Any, Optional, Tuple +from typing import Any, Dict, Optional, Tuple import numpy as np @@ -24,17 +24,27 @@ class Scope(_scope.Scope): __slots__ = ("queryables",) - def __init__(self, level: int, global_dict=None, local_dict=None, queryables=None): + queryables: Dict[str, Any] + + def __init__( + self, + level: int, + global_dict=None, + local_dict=None, + queryables: Optional[Dict[str, Any]] = None, + ): super().__init__(level + 1, global_dict=global_dict, local_dict=local_dict) self.queryables = queryables or dict() class Term(ops.Term): + env: Scope + def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls return object.__new__(klass) - def __init__(self, name, env, side=None, encoding=None): + def __init__(self, name, env: Scope, side=None, encoding=None): super().__init__(name, env, side=side, encoding=encoding) def _resolve_name(self): @@ -69,7 +79,10 @@ class BinOp(ops.BinOp): _max_selectors = 31 - def __init__(self, op, lhs, rhs, queryables, encoding): + op: str + queryables: Dict[str, Any] + + def __init__(self, op: str, lhs, rhs, queryables: Dict[str, Any], encoding): super().__init__(op, lhs, rhs) self.queryables = queryables self.encoding = encoding @@ -373,9 +386,6 @@ def prune(self, klass): return None -_op_classes = {"unary": UnaryOp} - - class ExprVisitor(BaseExprVisitor): const_type = Constant term_type = Term @@ -510,7 +520,16 @@ class Expr(expr.Expr): "major_axis>=20130101" """ - def __init__(self, where, queryables=None, encoding=None, scope_level: int = 0): + _visitor: Optional[ExprVisitor] + env: Scope + + def __init__( + self, + where, + queryables: Optional[Dict[str, Any]] = None, + encoding=None, + scope_level: int = 0, + ): where = _validate_where(where) diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 2c5c687a44680..71aa885816670 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -9,6 +9,7 @@ import pprint import struct import sys +from typing import List import numpy as np @@ -203,7 +204,7 @@ def resolve(self, key, is_local): raise UndefinedVariableError(key, is_local) - def swapkey(self, old_key, new_key, new_value=None): + def swapkey(self, old_key: str, new_key: str, new_value=None): """ Replace a variable name, with a potentially new value. @@ -228,7 +229,7 @@ def swapkey(self, old_key, new_key, new_value=None): mapping[new_key] = new_value return - def _get_vars(self, stack, scopes): + def _get_vars(self, stack, scopes: List[str]): """ Get specifically scoped variables from a list of stack frames. diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 4c9e10e0f4601..59df074fff62a 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2043,6 +2043,7 @@ def convert( Table row number: the end of the sub-selection. Values larger than the underlying table's row count are normalized to that. """ + assert self.table is not None # for mypy _start = start if start is not None else 0 _stop = min(stop, self.table.nrows) if stop is not None else self.table.nrows @@ -3423,7 +3424,7 @@ def data_orientation(self): ) ) - def queryables(self): + def queryables(self) -> Dict[str, Any]: """ return a dict of the kinds allowable columns for this object """ # compute the values_axes queryables
Made possible by #29692
https://api.github.com/repos/pandas-dev/pandas/pulls/29754
2019-11-20T20:16:30Z
2019-11-21T13:02:31Z
2019-11-21T13:02:31Z
2019-11-21T15:45:35Z
PERF: speed-up when scalar not found in Categorical's categories
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index a3d17b2b32353..00305360bbacc 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -343,6 +343,7 @@ Performance improvements - Performance improvement in :meth:`DataFrame.replace` when provided a list of values to replace (:issue:`28099`) - Performance improvement in :meth:`DataFrame.select_dtypes` by using vectorization instead of iterating over a loop (:issue:`28317`) - Performance improvement in :meth:`Categorical.searchsorted` and :meth:`CategoricalIndex.searchsorted` (:issue:`28795`) +- Performance improvement when searching for a scalar in a :meth:`Categorical` and the scalar is not found in the categories (:issue:`29750`) .. _whatsnew_1000.bug_fixes: diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c6e2a7b7a6e00..89b9c01883de8 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -133,9 +133,9 @@ def f(self, other): return ret else: if opname == "__eq__": - return np.repeat(False, len(self)) + return np.zeros(len(self), dtype=bool) elif opname == "__ne__": - return np.repeat(True, len(self)) + return np.ones(len(self), dtype=bool) else: msg = ( "Cannot compare a Categorical for op {op} with a " diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 22c1d5373372a..d62c4f4cf936e 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -48,7 +48,7 @@ def test_comparisons(self): tm.assert_numpy_array_equal(result, expected) result = self.factor == "d" - expected = np.repeat(False, len(self.factor)) + expected = np.zeros(len(self.factor), dtype=bool) tm.assert_numpy_array_equal(result, expected) # comparisons with categoricals diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 73eacd8c4856e..f3c8c5cb6efa1 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -105,11 +105,11 @@ def test_with_nans(self, closed): assert index.hasnans is False result = index.isna() - expected = np.repeat(False, len(index)) + expected = np.zeros(len(index), dtype=bool) tm.assert_numpy_array_equal(result, expected) result = index.notna() - expected = np.repeat(True, len(index)) + expected = np.ones(len(index), dtype=bool) tm.assert_numpy_array_equal(result, expected) index = self.create_index_with_nan(closed=closed) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 5bfa13c0865f1..facc025409f08 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -730,7 +730,7 @@ def test_nanosecond_index_access(self): assert first_value == x[Timestamp(expected_ts)] def test_booleanindex(self, index): - bool_index = np.repeat(True, len(index)).astype(bool) + bool_index = np.ones(len(index), dtype=bool) bool_index[5:30:2] = False sub_index = index[bool_index]
I took a look at the code in core/category.py and found a usage of np.repeat for creating boolean arrays. np.repeat is much slower than np.zeros/np.ones for that purpose. ```python >>> n = 1_000_000 >>> c = pd.Categorical(['a'] * n + ['b'] * n + ['c'] * n) >>> %timeit c == 'x' 17 ms ± 270 µs per loop # master 82.6 µs ± 488 ns per loop # this PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/29750
2019-11-20T18:23:43Z
2019-11-21T13:39:55Z
2019-11-21T13:39:55Z
2019-11-21T13:45:24Z
CLN: use f-strings in core.categorical.py
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c6e2a7b7a6e00..9a94345a769df 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -73,10 +73,10 @@ def _cat_compare_op(op): - opname = "__{op}__".format(op=op.__name__) + opname = f"__{op.__name__}__" @unpack_zerodim_and_defer(opname) - def f(self, other): + def func(self, other): # On python2, you can usually compare any type to any type, and # Categoricals can be seen as a custom type, but having different # results depending whether categories are the same or not is kind of @@ -137,11 +137,10 @@ def f(self, other): elif opname == "__ne__": return np.repeat(True, len(self)) else: - msg = ( - "Cannot compare a Categorical for op {op} with a " + raise TypeError( + f"Cannot compare a Categorical for op {opname} with a " "scalar, which is not a category." ) - raise TypeError(msg.format(op=opname)) else: # allow categorical vs object dtype array comparisons for equality @@ -149,16 +148,15 @@ def f(self, other): if opname in ["__eq__", "__ne__"]: return getattr(np.array(self), opname)(np.array(other)) - msg = ( - "Cannot compare a Categorical for op {op} with type {typ}." - "\nIf you want to compare values, use 'np.asarray(cat) " - "<op> other'." + raise TypeError( + f"Cannot compare a Categorical for op {opname} with " + f"type {type(other)}.\nIf you want to compare values, " + "use 'np.asarray(cat) <op> other'." ) - raise TypeError(msg.format(op=opname, typ=type(other))) - f.__name__ = opname + func.__name__ = opname - return f + return func def contains(cat, key, container): @@ -1060,11 +1058,9 @@ def add_categories(self, new_categories, inplace=False): new_categories = [new_categories] already_included = set(new_categories) & set(self.dtype.categories) if len(already_included) != 0: - msg = ( - "new categories must not include old categories: " - "{already_included!s}" + raise ValueError( + f"new categories must not include old categories: {already_included}" ) - raise ValueError(msg.format(already_included=already_included)) new_categories = list(self.dtype.categories) + list(new_categories) new_dtype = CategoricalDtype(new_categories, self.ordered) @@ -1120,8 +1116,7 @@ def remove_categories(self, removals, inplace=False): new_categories = [x for x in new_categories if notna(x)] if len(not_included) != 0: - msg = "removals must all be in old categories: {not_included!s}" - raise ValueError(msg.format(not_included=not_included)) + raise ValueError(f"removals must all be in old categories: {not_included}") return self.set_categories( new_categories, ordered=self.ordered, rename=False, inplace=inplace @@ -1299,9 +1294,8 @@ def shift(self, periods, fill_value=None): fill_value = self.categories.get_loc(fill_value) else: raise ValueError( - "'fill_value={}' is not present " - "in this Categorical's " - "categories".format(fill_value) + f"'fill_value={fill_value}' is not present " + "in this Categorical's categories" ) if periods > 0: codes[:periods] = fill_value @@ -1342,8 +1336,8 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): # for all other cases, raise for now (similarly as what happens in # Series.__array_prepare__) raise TypeError( - "Object with dtype {dtype} cannot perform " - "the numpy op {op}".format(dtype=self.dtype, op=ufunc.__name__) + f"Object with dtype {self.dtype} cannot perform " + f"the numpy op {ufunc.__name__}" ) def __setstate__(self, state): @@ -1542,9 +1536,9 @@ def check_for_ordered(self, op): """ assert that we are ordered """ if not self.ordered: raise TypeError( - "Categorical is not ordered for operation {op}\n" + f"Categorical is not ordered for operation {op}\n" "you can use .as_ordered() to change the " - "Categorical to an ordered one\n".format(op=op) + "Categorical to an ordered one\n" ) def _values_for_argsort(self): @@ -1679,8 +1673,7 @@ def sort_values(self, inplace=False, ascending=True, na_position="last"): """ inplace = validate_bool_kwarg(inplace, "inplace") if na_position not in ["last", "first"]: - msg = "invalid na_position: {na_position!r}" - raise ValueError(msg.format(na_position=na_position)) + raise ValueError(f"invalid na_position: {na_position!r}") sorted_idx = nargsort(self, ascending=ascending, na_position=na_position) @@ -1836,8 +1829,7 @@ def fillna(self, value=None, method=None, limit=None): else: raise TypeError( '"value" parameter must be a scalar, dict ' - "or Series, but you passed a " - '"{0}"'.format(type(value).__name__) + f'or Series, but you passed a {type(value).__name__!r}"' ) return self._constructor(codes, dtype=self.dtype, fastpath=True) @@ -1930,8 +1922,11 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None): if fill_value in self.categories: fill_value = self.categories.get_loc(fill_value) else: - msg = "'fill_value' ('{}') is not in this Categorical's categories." - raise TypeError(msg.format(fill_value)) + msg = ( + f"'fill_value' ('{fill_value}') is not in this " + "Categorical's categories." + ) + raise TypeError(msg) codes = take(self._codes, indexer, allow_fill=allow_fill, fill_value=fill_value) result = type(self).from_codes(codes, dtype=dtype) @@ -1969,11 +1964,9 @@ def _tidy_repr(self, max_vals=10, footer=True): head = self[:num]._get_repr(length=False, footer=False) tail = self[-(max_vals - num) :]._get_repr(length=False, footer=False) - result = "{head}, ..., {tail}".format(head=head[:-1], tail=tail[1:]) + result = f"{head[:-1]}, ..., {tail[1:]}" if footer: - result = "{result}\n{footer}".format( - result=result, footer=self._repr_footer() - ) + result = f"{result}\n{self._repr_footer()}" return str(result) @@ -2007,9 +2000,7 @@ def _repr_categories_info(self): category_strs = self._repr_categories() dtype = str(self.categories.dtype) - levheader = "Categories ({length}, {dtype}): ".format( - length=len(self.categories), dtype=dtype - ) + levheader = f"Categories ({len(self.categories)}, {dtype}): " width, height = get_terminal_size() max_width = get_option("display.width") or width if console.in_ipython_frontend(): @@ -2033,10 +2024,8 @@ def _repr_categories_info(self): return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]" def _repr_footer(self): - - return "Length: {length}\n{info}".format( - length=len(self), info=self._repr_categories_info() - ) + info = self._repr_categories_info() + return f"Length: {len(self)}\n{info}" def _get_repr(self, length=True, na_rep="NaN", footer=True): from pandas.io.formats import format as fmt @@ -2058,7 +2047,7 @@ def __repr__(self) -> str: result = self._get_repr(length=len(self) > _maxlen) else: msg = self._get_repr(length=False, footer=True).replace("\n", ", ") - result = "[], {repr_msg}".format(repr_msg=msg) + result = f"[], {msg}" return result @@ -2189,8 +2178,7 @@ def _reverse_indexer(self): def _reduce(self, name, axis=0, **kwargs): func = getattr(self, name, None) if func is None: - msg = "Categorical cannot perform the operation {op}" - raise TypeError(msg.format(op=name)) + raise TypeError(f"Categorical cannot perform the operation {name}") return func(**kwargs) def min(self, numeric_only=None, **kwargs): @@ -2458,11 +2446,10 @@ def isin(self, values): array([ True, False, True, False, True, False]) """ if not is_list_like(values): + values_type = type(values).__name__ raise TypeError( "only list-like objects are allowed to be passed" - " to isin(), you passed a [{values_type}]".format( - values_type=type(values).__name__ - ) + f" to isin(), you passed a [{values_type}]" ) values = sanitize_array(values, None, None) null_mask = np.asarray(isna(values))
also rename an inner function from ``f`` to ``func``, which is clearer.
https://api.github.com/repos/pandas-dev/pandas/pulls/29748
2019-11-20T17:37:07Z
2019-11-21T12:19:53Z
2019-11-21T12:19:53Z
2019-11-21T12:20:04Z
CI: fix imminent mypy failure
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 4c9e10e0f4601..7c447cbf78677 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2044,6 +2044,8 @@ def convert( the underlying table's row count are normalized to that. """ + assert self.table is not None + _start = start if start is not None else 0 _stop = min(stop, self.table.nrows) if stop is not None else self.table.nrows self.values = Int64Index(np.arange(_stop - _start))
`pandas\io\pytables.py:2048: error: "None" has no attribute "nrows"` seen locally after merging master and running mypy
https://api.github.com/repos/pandas-dev/pandas/pulls/29747
2019-11-20T17:33:13Z
2019-11-20T21:03:52Z
2019-11-20T21:03:51Z
2019-11-20T21:22:43Z
DEPR: remove is_period, is_datetimetz
diff --git a/doc/source/reference/general_utility_functions.rst b/doc/source/reference/general_utility_functions.rst index 9c69770c0f1b7..0961acc43f301 100644 --- a/doc/source/reference/general_utility_functions.rst +++ b/doc/source/reference/general_utility_functions.rst @@ -97,13 +97,11 @@ Scalar introspection api.types.is_bool api.types.is_categorical api.types.is_complex - api.types.is_datetimetz api.types.is_float api.types.is_hashable api.types.is_integer api.types.is_interval api.types.is_number - api.types.is_period api.types.is_re api.types.is_re_compilable api.types.is_scalar diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3b87150f544cf..f9e3f3c37dde8 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -325,6 +325,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - :meth:`DataFrame.to_records` no longer supports the argument "convert_datetime64" (:issue:`18902`) - Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) - Changed the default value for the "keep_tz" argument in :meth:`DatetimeIndex.to_series` to ``True`` (:issue:`23739`) +- Removed the previously deprecated :func:`api.types.is_period` and :func:`api.types.is_datetimetz` (:issue:`23917`) - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) - Removed previously deprecated :func:`pandas.tseries.plotting.tsplot` (:issue:`18627`) - Removed the previously deprecated ``reduce`` and ``broadcast`` arguments from :meth:`DataFrame.apply` (:issue:`18577`) diff --git a/pandas/core/dtypes/api.py b/pandas/core/dtypes/api.py index 2b527e1fb5890..cb0912cbcf880 100644 --- a/pandas/core/dtypes/api.py +++ b/pandas/core/dtypes/api.py @@ -12,7 +12,6 @@ is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype, - is_datetimetz, is_dict_like, is_dtype_equal, is_extension_array_dtype, @@ -32,7 +31,6 @@ is_number, is_numeric_dtype, is_object_dtype, - is_period, is_period_dtype, is_re, is_re_compilable, diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index dcc8a274492ee..783669688ea42 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -375,56 +375,6 @@ def is_categorical(arr) -> bool: return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr) -def is_datetimetz(arr) -> bool: - """ - Check whether an array-like is a datetime array-like with a timezone - component in its dtype. - - .. deprecated:: 0.24.0 - - Parameters - ---------- - arr : array-like - The array-like to check. - - Returns - ------- - boolean - Whether or not the array-like is a datetime array-like with a - timezone component in its dtype. - - Examples - -------- - >>> is_datetimetz([1, 2, 3]) - False - - Although the following examples are both DatetimeIndex objects, - the first one returns False because it has no timezone component - unlike the second one, which returns True. - - >>> is_datetimetz(pd.DatetimeIndex([1, 2, 3])) - False - >>> is_datetimetz(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) - True - - The object need not be a DatetimeIndex object. It just needs to have - a dtype which has a timezone component. - - >>> dtype = DatetimeTZDtype("ns", tz="US/Eastern") - >>> s = pd.Series([], dtype=dtype) - >>> is_datetimetz(s) - True - """ - - warnings.warn( - "'is_datetimetz' is deprecated and will be removed in a " - "future version. Use 'is_datetime64tz_dtype' instead.", - FutureWarning, - stacklevel=2, - ) - return is_datetime64tz_dtype(arr) - - def is_offsetlike(arr_or_obj) -> bool: """ Check if obj or all elements of list-like is DateOffset @@ -456,43 +406,6 @@ def is_offsetlike(arr_or_obj) -> bool: return False -def is_period(arr) -> bool: - """ - Check whether an array-like is a periodical index. - - .. deprecated:: 0.24.0 - - Parameters - ---------- - arr : array-like - The array-like to check. - - Returns - ------- - boolean - Whether or not the array-like is a periodical index. - - Examples - -------- - >>> is_period([1, 2, 3]) - False - >>> is_period(pd.Index([1, 2, 3])) - False - >>> is_period(pd.PeriodIndex(["2017-01-01"], freq="D")) - True - """ - - warnings.warn( - "'is_period' is deprecated and will be removed in a future " - "version. Use 'is_period_dtype' or is_period_arraylike' " - "instead.", - FutureWarning, - stacklevel=2, - ) - - return isinstance(arr, ABCPeriodIndex) or is_period_arraylike(arr) - - def is_datetime64_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the datetime64 dtype. diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index e9f68692a9863..97480502f192c 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -50,7 +50,7 @@ class TestTypes(Base): "infer_dtype", "is_extension_array_dtype", ] - deprecated = ["is_period", "is_datetimetz", "is_extension_type"] + deprecated = ["is_extension_type"] dtypes = ["CategoricalDtype", "DatetimeTZDtype", "PeriodDtype", "IntervalDtype"] def test_types(self): diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index d8420673104d5..ae625ed8e389f 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -207,25 +207,6 @@ def test_is_categorical(): assert not com.is_categorical([1, 2, 3]) -def test_is_datetimetz(): - with tm.assert_produces_warning(FutureWarning): - assert not com.is_datetimetz([1, 2, 3]) - assert not com.is_datetimetz(pd.DatetimeIndex([1, 2, 3])) - - assert com.is_datetimetz(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) - - dtype = DatetimeTZDtype("ns", tz="US/Eastern") - s = pd.Series([], dtype=dtype) - assert com.is_datetimetz(s) - - -def test_is_period_deprecated(): - with tm.assert_produces_warning(FutureWarning): - assert not com.is_period([1, 2, 3]) - assert not com.is_period(pd.Index([1, 2, 3])) - assert com.is_period(pd.PeriodIndex(["2017-01-01"], freq="D")) - - def test_is_datetime64_dtype(): assert not com.is_datetime64_dtype(object) assert not com.is_datetime64_dtype([1, 2, 3]) diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index f4bf4c1fc83d9..fc896e6a9d348 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -12,10 +12,8 @@ is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype, - is_datetimetz, is_dtype_equal, is_interval_dtype, - is_period, is_period_dtype, is_string_dtype, ) @@ -294,25 +292,15 @@ def test_basic(self): assert not is_datetime64tz_dtype(np.dtype("float64")) assert not is_datetime64tz_dtype(1.0) - with tm.assert_produces_warning(FutureWarning): - assert is_datetimetz(s) - assert is_datetimetz(s.dtype) - assert not is_datetimetz(np.dtype("float64")) - assert not is_datetimetz(1.0) - def test_dst(self): dr1 = date_range("2013-01-01", periods=3, tz="US/Eastern") s1 = Series(dr1, name="A") assert is_datetime64tz_dtype(s1) - with tm.assert_produces_warning(FutureWarning): - assert is_datetimetz(s1) dr2 = date_range("2013-08-01", periods=3, tz="US/Eastern") s2 = Series(dr2, name="A") assert is_datetime64tz_dtype(s2) - with tm.assert_produces_warning(FutureWarning): - assert is_datetimetz(s2) assert s1.dtype == s2.dtype @pytest.mark.parametrize("tz", ["UTC", "US/Eastern"]) @@ -457,22 +445,14 @@ def test_basic(self): assert is_period_dtype(pidx.dtype) assert is_period_dtype(pidx) - with tm.assert_produces_warning(FutureWarning): - assert is_period(pidx) s = Series(pidx, name="A") assert is_period_dtype(s.dtype) assert is_period_dtype(s) - with tm.assert_produces_warning(FutureWarning): - assert is_period(s) assert not is_period_dtype(np.dtype("float64")) assert not is_period_dtype(1.0) - with tm.assert_produces_warning(FutureWarning): - assert not is_period(np.dtype("float64")) - with tm.assert_produces_warning(FutureWarning): - assert not is_period(1.0) def test_empty(self): dt = PeriodDtype()
deprecated in 0.24.0
https://api.github.com/repos/pandas-dev/pandas/pulls/29744
2019-11-20T16:09:23Z
2019-11-21T13:24:19Z
2019-11-21T13:24:19Z
2019-11-21T15:43:36Z
io/parsers: ensure decimal is str on PythonParser
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..ee6a20d15ab90 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -487,6 +487,7 @@ I/O - Bug in :meth:`Styler.background_gradient` not able to work with dtype ``Int64`` (:issue:`28869`) - Bug in :meth:`DataFrame.to_clipboard` which did not work reliably in ipython (:issue:`22707`) - Bug in :func:`read_json` where default encoding was not set to ``utf-8`` (:issue:`29565`) +- Bug in :class:`PythonParser` where str and bytes were being mixed when dealing with the decimal field (:issue:`29650`) - Plotting diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index cf1511c1221b3..bbec148b8745d 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -488,7 +488,7 @@ def _read(filepath_or_buffer: FilePathOrBuffer, kwds): "cache_dates": True, "thousands": None, "comment": None, - "decimal": b".", + "decimal": ".", # 'engine': 'c', "parse_dates": False, "keep_date_col": False, @@ -568,7 +568,7 @@ def parser_f( # Quoting, Compression, and File Format compression="infer", thousands=None, - decimal=b".", + decimal: str = ".", lineterminator=None, quotechar='"', quoting=csv.QUOTE_MINIMAL,
- [x] closes #29650 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29743
2019-11-20T15:39:46Z
2019-11-22T15:35:22Z
2019-11-22T15:35:22Z
2019-11-22T15:46:06Z
TYP: disallow comment-based annotation syntax
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index edd8fcd418c47..7c6c98d910492 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -194,6 +194,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include="*.py" --include="*.pyx" -E 'class.*:\n\n( )+"""' . RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for use of comment-based annotation syntax' ; echo $MSG + invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas + RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check that no file in the repo contains trailing whitespaces' ; echo $MSG set -o pipefail if [[ "$AZURE" == "true" ]]; then diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 33084d0d23771..042d6926d84f5 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -804,7 +804,7 @@ Types imports should follow the ``from typing import ...`` convention. So rather import typing - primes = [] # type: typing.List[int] + primes: typing.List[int] = [] You should write @@ -812,19 +812,19 @@ You should write from typing import List, Optional, Union - primes = [] # type: List[int] + primes: List[int] = [] ``Optional`` should be used where applicable, so instead of .. code-block:: python - maybe_primes = [] # type: List[Union[int, None]] + maybe_primes: List[Union[int, None]] = [] You should write .. code-block:: python - maybe_primes = [] # type: List[Optional[int]] + maybe_primes: List[Optional[int]] = [] In some cases in the code base classes may define class variables that shadow builtins. This causes an issue as described in `Mypy 1775 <https://github.com/python/mypy/issues/1775#issuecomment-310969854>`_. The defensive solution here is to create an unambiguous alias of the builtin and use that without your annotation. For example, if you come across a definition like @@ -840,7 +840,7 @@ The appropriate way to annotate this would be as follows str_type = str class SomeClass2: - str = None # type: str_type + str: str_type = None In some cases you may be tempted to use ``cast`` from the typing module when you know better than the analyzer. This occurs particularly when using custom inference functions. For example diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 890db5b41907e..814f855cceeac 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -58,16 +58,16 @@ RegisteredOption = namedtuple("RegisteredOption", "key defval doc validator cb") # holds deprecated option metdata -_deprecated_options = {} # type: Dict[str, DeprecatedOption] +_deprecated_options: Dict[str, DeprecatedOption] = {} # holds registered option metdata -_registered_options = {} # type: Dict[str, RegisteredOption] +_registered_options: Dict[str, RegisteredOption] = {} # holds the current values for registered options -_global_config = {} # type: Dict[str, str] +_global_config: Dict[str, str] = {} # keys which have a special meaning -_reserved_keys = ["all"] # type: List[str] +_reserved_keys: List[str] = ["all"] class OptionError(AttributeError, KeyError): diff --git a/pandas/_version.py b/pandas/_version.py index 0cdedf3da3ea7..dfed9574c7cb0 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -47,7 +47,7 @@ class NotThisMethod(Exception): pass -HANDLERS = {} # type: Dict[str, Dict[str, Callable]] +HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index ea5aaf6b6476d..fffe09a74571e 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -106,7 +106,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs): return skipna -ARGSORT_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[Union[int, str]]] +ARGSORT_DEFAULTS: "OrderedDict[str, Optional[Union[int, str]]]" = OrderedDict() ARGSORT_DEFAULTS["axis"] = -1 ARGSORT_DEFAULTS["kind"] = "quicksort" ARGSORT_DEFAULTS["order"] = None @@ -122,7 +122,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs): # two different signatures of argsort, this second validation # for when the `kind` param is supported -ARGSORT_DEFAULTS_KIND = OrderedDict() # type: OrderedDict[str, Optional[int]] +ARGSORT_DEFAULTS_KIND: "OrderedDict[str, Optional[int]]" = OrderedDict() ARGSORT_DEFAULTS_KIND["axis"] = -1 ARGSORT_DEFAULTS_KIND["order"] = None validate_argsort_kind = CompatValidator( @@ -169,14 +169,14 @@ def validate_clip_with_axis(axis, args, kwargs): return axis -COMPRESS_DEFAULTS = OrderedDict() # type: OrderedDict[str, Any] +COMPRESS_DEFAULTS: "OrderedDict[str, Any]" = OrderedDict() COMPRESS_DEFAULTS["axis"] = None COMPRESS_DEFAULTS["out"] = None validate_compress = CompatValidator( COMPRESS_DEFAULTS, fname="compress", method="both", max_fname_arg_count=1 ) -CUM_FUNC_DEFAULTS = OrderedDict() # type: OrderedDict[str, Any] +CUM_FUNC_DEFAULTS: "OrderedDict[str, Any]" = OrderedDict() CUM_FUNC_DEFAULTS["dtype"] = None CUM_FUNC_DEFAULTS["out"] = None validate_cum_func = CompatValidator( @@ -202,7 +202,7 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): return skipna -ALLANY_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[bool]] +ALLANY_DEFAULTS: "OrderedDict[str, Optional[bool]]" = OrderedDict() ALLANY_DEFAULTS["dtype"] = None ALLANY_DEFAULTS["out"] = None ALLANY_DEFAULTS["keepdims"] = False @@ -224,28 +224,28 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): MINMAX_DEFAULTS, fname="max", method="both", max_fname_arg_count=1 ) -RESHAPE_DEFAULTS = dict(order="C") # type: Dict[str, str] +RESHAPE_DEFAULTS: Dict[str, str] = dict(order="C") validate_reshape = CompatValidator( RESHAPE_DEFAULTS, fname="reshape", method="both", max_fname_arg_count=1 ) -REPEAT_DEFAULTS = dict(axis=None) # type: Dict[str, Any] +REPEAT_DEFAULTS: Dict[str, Any] = dict(axis=None) validate_repeat = CompatValidator( REPEAT_DEFAULTS, fname="repeat", method="both", max_fname_arg_count=1 ) -ROUND_DEFAULTS = dict(out=None) # type: Dict[str, Any] +ROUND_DEFAULTS: Dict[str, Any] = dict(out=None) validate_round = CompatValidator( ROUND_DEFAULTS, fname="round", method="both", max_fname_arg_count=1 ) -SORT_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[Union[int, str]]] +SORT_DEFAULTS: "OrderedDict[str, Optional[Union[int, str]]]" = OrderedDict() SORT_DEFAULTS["axis"] = -1 SORT_DEFAULTS["kind"] = "quicksort" SORT_DEFAULTS["order"] = None validate_sort = CompatValidator(SORT_DEFAULTS, fname="sort", method="kwargs") -STAT_FUNC_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[Any]] +STAT_FUNC_DEFAULTS: "OrderedDict[str, Optional[Any]]" = OrderedDict() STAT_FUNC_DEFAULTS["dtype"] = None STAT_FUNC_DEFAULTS["out"] = None @@ -273,13 +273,13 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): MEDIAN_DEFAULTS, fname="median", method="both", max_fname_arg_count=1 ) -STAT_DDOF_FUNC_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[bool]] +STAT_DDOF_FUNC_DEFAULTS: "OrderedDict[str, Optional[bool]]" = OrderedDict() STAT_DDOF_FUNC_DEFAULTS["dtype"] = None STAT_DDOF_FUNC_DEFAULTS["out"] = None STAT_DDOF_FUNC_DEFAULTS["keepdims"] = False validate_stat_ddof_func = CompatValidator(STAT_DDOF_FUNC_DEFAULTS, method="kwargs") -TAKE_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[str]] +TAKE_DEFAULTS: "OrderedDict[str, Optional[str]]" = OrderedDict() TAKE_DEFAULTS["out"] = None TAKE_DEFAULTS["mode"] = "raise" validate_take = CompatValidator(TAKE_DEFAULTS, fname="take", method="kwargs") diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index fc60c01d7b808..182b07d57ea49 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -11,8 +11,8 @@ class DirNamesMixin: - _accessors = set() # type: Set[str] - _deprecations = frozenset() # type: FrozenSet[str] + _accessors: Set[str] = set() + _deprecations: FrozenSet[str] = frozenset() def _dir_deletions(self): """ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 9c14102529b48..18adb12a9ad72 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -50,7 +50,7 @@ from pandas.core.construction import array, extract_array from pandas.core.indexers import validate_indices -_shared_docs = {} # type: Dict[str, str] +_shared_docs: Dict[str, str] = {} # --------------- # diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 34a8ed1fa7a83..8c49b2b803241 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -34,8 +34,9 @@ def frame_apply( """ construct and return a row or column based frame apply object """ axis = obj._get_axis_number(axis) + klass: Type[FrameApply] if axis == 0: - klass = FrameRowApply # type: Type[FrameApply] + klass = FrameRowApply elif axis == 1: klass = FrameColumnApply diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 82dabe735581b..fa0e025c22c88 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -29,7 +29,7 @@ _not_implemented_message = "{} does not implement {}." -_extension_array_shared_docs = dict() # type: Dict[str, str] +_extension_array_shared_docs: Dict[str, str] = dict() def try_cast_to_ea(cls_or_instance, obj, dtype=None): diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 8e66db4c61032..dc3c49b7e06a9 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -51,7 +51,7 @@ class AttributesMixin: - _data = None # type: np.ndarray + _data: np.ndarray @classmethod def _simple_new(cls, values, **kwargs): diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 8e3c727a14c99..71420e6e58090 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -320,7 +320,7 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps, dtl.DatelikeOps # ----------------------------------------------------------------- # Constructors - _dtype = None # type: Union[np.dtype, DatetimeTZDtype] + _dtype: Union[np.dtype, DatetimeTZDtype] _freq = None def __init__(self, values, dtype=_NS_DTYPE, freq=None, copy=False): diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 63296b4a26354..12b76df9a5983 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -40,9 +40,9 @@ class _IntegerDtype(ExtensionDtype): The attributes name & type are set when these subclasses are created. """ - name = None # type: str + name: str base = None - type = None # type: Type + type: Type na_value = np.nan def __repr__(self) -> str: diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index f3d51b28ad399..41a8c48452647 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -161,7 +161,7 @@ class PeriodArray(dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps): _scalar_type = Period # Names others delegate to us - _other_ops = [] # type: List[str] + _other_ops: List[str] = [] _bool_ops = ["is_leap_year"] _object_ops = ["start_time", "end_time", "freq"] _field_ops = [ @@ -894,9 +894,9 @@ def period_array( data = np.asarray(data) + dtype: Optional[PeriodDtype] if freq: - # typed Optional here because the else block below assigns None - dtype = PeriodDtype(freq) # type: Optional[PeriodDtype] + dtype = PeriodDtype(freq) else: dtype = None diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 816beb758dd33..bacd0b9699e93 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -161,8 +161,8 @@ class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps): _scalar_type = Timedelta __array_priority__ = 1000 # define my properties & methods for delegation - _other_ops = [] # type: List[str] - _bool_ops = [] # type: List[str] + _other_ops: List[str] = [] + _bool_ops: List[str] = [] _object_ops = ["freq"] _field_ops = ["days", "seconds", "microseconds", "nanoseconds"] _datetimelike_ops = _field_ops + _object_ops + _bool_ops diff --git a/pandas/core/base.py b/pandas/core/base.py index c9855701eeb03..176a92132e20a 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -36,7 +36,7 @@ from pandas.core.arrays import ExtensionArray import pandas.core.nanops as nanops -_shared_docs = dict() # type: Dict[str, str] +_shared_docs: Dict[str, str] = dict() _indexops_doc_kwargs = dict( klass="IndexOpsMixin", inplace="", @@ -603,7 +603,7 @@ def _is_builtin_func(self, arg): class ShallowMixin: - _attributes = [] # type: List[str] + _attributes: List[str] = [] def _shallow_copy(self, obj=None, **kwargs): """ @@ -627,7 +627,7 @@ class IndexOpsMixin: # ndarray compatibility __array_priority__ = 1000 - _deprecations = frozenset( + _deprecations: FrozenSet[str] = frozenset( [ "tolist", # tolist is not deprecated, just suppressed in the __dir__ "base", @@ -637,7 +637,7 @@ class IndexOpsMixin: "flags", "strides", ] - ) # type: FrozenSet[str] + ) def transpose(self, *args, **kwargs): """ diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 4d1fc42070ea8..253d64d50d0cd 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -378,7 +378,7 @@ class BaseExprVisitor(ast.NodeVisitor): preparser : callable """ - const_type = Constant # type: Type[Term] + const_type: Type[Term] = Constant term_type = Term binary_ops = _cmp_ops_syms + _bool_ops_syms + _arith_ops_syms diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index c90f1cdeaabfd..8acdf32c8768e 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -81,7 +81,7 @@ def __from_arrow__( provided for registering virtual subclasses. """ - _metadata = () # type: Tuple[str, ...] + _metadata: Tuple[str, ...] = () def __str__(self) -> str: return self.name diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 3d1388db371ca..523c8e8bd02d0 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -20,7 +20,7 @@ # GH26403: sentinel value used for the default value of ordered in the # CategoricalDtype constructor to detect when ordered=None is explicitly passed -ordered_sentinel = object() # type: object +ordered_sentinel: object = object() def register_extension_dtype(cls: Type[ExtensionDtype]) -> Type[ExtensionDtype]: @@ -66,7 +66,7 @@ class Registry: """ def __init__(self): - self.dtypes = [] # type: List[Type[ExtensionDtype]] + self.dtypes: List[Type[ExtensionDtype]] = [] def register(self, dtype: Type[ExtensionDtype]) -> None: """ @@ -119,21 +119,21 @@ class PandasExtensionDtype(ExtensionDtype): THIS IS NOT A REAL NUMPY DTYPE """ - type = None # type: Any - kind = None # type: Any + type: Any + kind: Any # The Any type annotations above are here only because mypy seems to have a # problem dealing with with multiple inheritance from PandasExtensionDtype # and ExtensionDtype's @properties in the subclasses below. The kind and # type variables in those subclasses are explicitly typed below. subdtype = None - str = None # type: Optional[str_type] + str: Optional[str_type] = None num = 100 - shape = tuple() # type: Tuple[int, ...] + shape: Tuple[int, ...] = tuple() itemsize = 8 base = None isbuiltin = 0 isnative = 0 - _cache = {} # type: Dict[str_type, 'PandasExtensionDtype'] + _cache: Dict[str_type, "PandasExtensionDtype"] = {} def __str__(self) -> str_type: """ @@ -214,12 +214,12 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): # TODO: Document public vs. private API name = "category" - type = CategoricalDtypeType # type: Type[CategoricalDtypeType] - kind = "O" # type: str_type + type: Type[CategoricalDtypeType] = CategoricalDtypeType + kind: str_type = "O" str = "|O08" base = np.dtype("O") _metadata = ("categories", "ordered", "_ordered_from_sentinel") - _cache = {} # type: Dict[str_type, PandasExtensionDtype] + _cache: Dict[str_type, PandasExtensionDtype] = {} def __init__( self, categories=None, ordered: Union[Ordered, object] = ordered_sentinel @@ -650,15 +650,15 @@ class DatetimeTZDtype(PandasExtensionDtype): datetime64[ns, tzfile('/usr/share/zoneinfo/US/Central')] """ - type = Timestamp # type: Type[Timestamp] - kind = "M" # type: str_type + type: Type[Timestamp] = Timestamp + kind: str_type = "M" str = "|M8[ns]" num = 101 base = np.dtype("M8[ns]") na_value = NaT _metadata = ("unit", "tz") _match = re.compile(r"(datetime64|M8)\[(?P<unit>.+), (?P<tz>.+)\]") - _cache = {} # type: Dict[str_type, PandasExtensionDtype] + _cache: Dict[str_type, PandasExtensionDtype] = {} def __init__(self, unit="ns", tz=None): if isinstance(unit, DatetimeTZDtype): @@ -812,14 +812,14 @@ class PeriodDtype(PandasExtensionDtype): period[M] """ - type = Period # type: Type[Period] - kind = "O" # type: str_type + type: Type[Period] = Period + kind: str_type = "O" str = "|O08" base = np.dtype("O") num = 102 _metadata = ("freq",) _match = re.compile(r"(P|p)eriod\[(?P<freq>.+)\]") - _cache = {} # type: Dict[str_type, PandasExtensionDtype] + _cache: Dict[str_type, PandasExtensionDtype] = {} def __new__(cls, freq=None): """ @@ -972,13 +972,13 @@ class IntervalDtype(PandasExtensionDtype): """ name = "interval" - kind = None # type: Optional[str_type] + kind: Optional[str_type] = None str = "|O08" base = np.dtype("O") num = 103 _metadata = ("subtype",) _match = re.compile(r"(I|i)nterval\[(?P<subtype>.+)\]") - _cache = {} # type: Dict[str_type, PandasExtensionDtype] + _cache: Dict[str_type, PandasExtensionDtype] = {} def __new__(cls, subtype=None): from pandas.core.dtypes.common import ( diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8b31b6d503eda..46b213b25df49 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -381,9 +381,9 @@ class DataFrame(NDFrame): def _constructor(self) -> Type["DataFrame"]: return DataFrame - _constructor_sliced = Series # type: Type[Series] - _deprecations = NDFrame._deprecations | frozenset([]) # type: FrozenSet[str] - _accessors = set() # type: Set[str] + _constructor_sliced: Type[Series] = Series + _deprecations: FrozenSet[str] = NDFrame._deprecations | frozenset([]) + _accessors: Set[str] = set() @property def _constructor_expanddim(self): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7f83bb9e69f7a..b16a72f01c739 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -92,7 +92,7 @@ # goal is to be able to define the docs close to function, while still being # able to share -_shared_docs = dict() # type: Dict[str, str] +_shared_docs: Dict[str, str] = dict() _shared_doc_kwargs = dict( axes="keywords for axes", klass="Series/DataFrame", @@ -154,7 +154,7 @@ class NDFrame(PandasObject, SelectionMixin): copy : bool, default False """ - _internal_names = [ + _internal_names: List[str] = [ "_data", "_cacher", "_item_cache", @@ -168,15 +168,15 @@ class NDFrame(PandasObject, SelectionMixin): "_metadata", "__array_struct__", "__array_interface__", - ] # type: List[str] - _internal_names_set = set(_internal_names) # type: Set[str] - _accessors = set() # type: Set[str] - _deprecations = frozenset( + ] + _internal_names_set: Set[str] = set(_internal_names) + _accessors: Set[str] = set() + _deprecations: FrozenSet[str] = frozenset( ["get_dtype_counts", "get_values", "ftypes", "ix"] - ) # type: FrozenSet[str] - _metadata = [] # type: List[str] + ) + _metadata: List[str] = [] _is_copy = None - _data = None # type: BlockManager + _data: BlockManager _attrs: Dict[Optional[Hashable], Any] # ---------------------------------------------------------------------- @@ -3599,7 +3599,7 @@ class animal locomotion result._set_is_copy(self, copy=not result._is_view) return result - _xs = xs # type: Callable + _xs: Callable = xs def __getitem__(self, item): raise AbstractMethodError(self) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 900e11dedb8b1..99ef281e842b1 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1105,7 +1105,7 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: axis = self.axis obj = self._obj_with_exclusions - result = OrderedDict() # type: OrderedDict + result: OrderedDict = OrderedDict() if axis != obj._info_axis_number: for name, data in self: fres = func(data, *args, **kwargs) @@ -1122,7 +1122,7 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: # only for axis==0 obj = self._obj_with_exclusions - result = OrderedDict() # type: dict + result: OrderedDict = OrderedDict() cannot_agg = [] errors = None for item in obj: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 21c085c775399..9e12ac82fb3ae 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -345,7 +345,7 @@ def _group_selection_context(groupby): class _GroupBy(PandasObject, SelectionMixin): _group_selection = None - _apply_whitelist = frozenset() # type: FrozenSet[str] + _apply_whitelist: FrozenSet[str] = frozenset() def __init__( self, @@ -2518,12 +2518,11 @@ def get_groupby( mutated: bool = False, ): + klass: Union[Type["SeriesGroupBy"], Type["DataFrameGroupBy"]] if isinstance(obj, Series): from pandas.core.groupby.generic import SeriesGroupBy - klass = ( - SeriesGroupBy - ) # type: Union[Type["SeriesGroupBy"], Type["DataFrameGroupBy"]] + klass = SeriesGroupBy elif isinstance(obj, DataFrame): from pandas.core.groupby.generic import DataFrameGroupBy diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 2b946d1ff0a7a..308d4d1864bdd 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -93,7 +93,7 @@ class Grouper: >>> df.groupby(Grouper(level='date', freq='60s', axis=1)) """ - _attributes = ("key", "level", "freq", "axis", "sort") # type: Tuple[str, ...] + _attributes: Tuple[str, ...] = ("key", "level", "freq", "axis", "sort") def __new__(cls, *args, **kwargs): if kwargs.get("freq") is not None: @@ -373,8 +373,8 @@ def __repr__(self) -> str: def __iter__(self): return iter(self.indices) - _codes = None # type: np.ndarray - _group_index = None # type: Index + _codes: Optional[np.ndarray] = None + _group_index: Optional[Index] = None @property def ngroups(self) -> int: @@ -405,6 +405,7 @@ def result_index(self) -> Index: def group_index(self) -> Index: if self._group_index is None: self._make_codes() + assert self._group_index is not None return self._group_index def _make_codes(self) -> None: @@ -576,8 +577,8 @@ def get_grouper( else: levels = [level] * len(keys) - groupings = [] # type: List[Grouping] - exclusions = [] # type: List[Hashable] + groupings: List[Grouping] = [] + exclusions: List[Hashable] = [] # if the actual grouper should be obj[key] def is_in_axis(key) -> bool: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index a7e0a901a5394..4780254e060e6 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -90,7 +90,7 @@ def __init__( self._filter_empty_groups = self.compressed = len(groupings) != 1 self.axis = axis - self._groupings = list(groupings) # type: List[grouper.Grouping] + self._groupings: List[grouper.Grouping] = list(groupings) self.sort = sort self.group_keys = group_keys self.mutated = mutated @@ -153,7 +153,7 @@ def apply(self, f, data: FrameOrSeries, axis: int = 0): group_keys = self._get_group_keys() result_values = None - sdata = splitter._get_sorted_data() # type: FrameOrSeries + sdata: FrameOrSeries = splitter._get_sorted_data() if sdata.ndim == 2 and np.any(sdata.dtypes.apply(is_extension_array_dtype)): # calling splitter.fast_apply will raise TypeError via apply_frame_axis0 # if we pass EA instead of ndarray @@ -551,7 +551,7 @@ def _cython_operation( if vdim == 1 and arity == 1: result = result[:, 0] - names = self._name_functions.get(how, None) # type: Optional[List[str]] + names: Optional[List[str]] = self._name_functions.get(how, None) if swapped: result = result.swapaxes(0, axis) @@ -923,7 +923,7 @@ def _chop(self, sdata: DataFrame, slice_obj: slice) -> DataFrame: def get_splitter(data: FrameOrSeries, *args, **kwargs) -> DataSplitter: if isinstance(data, Series): - klass = SeriesSplitter # type: Type[DataSplitter] + klass: Type[DataSplitter] = SeriesSplitter else: # i.e. DataFrame klass = FrameSplitter diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 8978a09825ee9..10c0f465f69da 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -205,11 +205,11 @@ class Index(IndexOpsMixin, PandasObject): """ # tolist is not actually deprecated, just suppressed in the __dir__ - _deprecations = ( + _deprecations: FrozenSet[str] = ( PandasObject._deprecations | IndexOpsMixin._deprecations | frozenset(["asobject", "contains", "dtype_str", "get_values", "set_value"]) - ) # type: FrozenSet[str] + ) # To hand over control to subclasses _join_precedence = 1 @@ -321,10 +321,9 @@ def __new__( # the DatetimeIndex construction. # Note we can pass copy=False because the .astype below # will always make a copy - result = DatetimeIndex( - data, copy=False, name=name, **kwargs - ) # type: "Index" - return result.astype(object) + return DatetimeIndex(data, copy=False, name=name, **kwargs).astype( + object + ) else: return DatetimeIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) @@ -332,8 +331,9 @@ def __new__( if is_dtype_equal(_o_dtype, dtype): # Note we can pass copy=False because the .astype below # will always make a copy - result = TimedeltaIndex(data, copy=False, name=name, **kwargs) - return result.astype(object) + return TimedeltaIndex(data, copy=False, name=name, **kwargs).astype( + object + ) else: return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index df3420ea14e24..e420cf0cb0d78 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -826,9 +826,9 @@ class DatetimelikeDelegateMixin(PandasDelegate): """ # raw_methods : dispatch methods that shouldn't be boxed in an Index - _raw_methods = set() # type: Set[str] + _raw_methods: Set[str] = set() # raw_properties : dispatch properties that shouldn't be boxed in an Index - _raw_properties = set() # type: Set[str] + _raw_properties: Set[str] = set() name = None _data: ExtensionArray diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 6f677848b1c79..e68b340130b9b 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,7 +1,7 @@ from datetime import timedelta import operator from sys import getsizeof -from typing import Union +from typing import Optional, Union import warnings import numpy as np @@ -73,10 +73,10 @@ class RangeIndex(Int64Index): _typ = "rangeindex" _engine_type = libindex.Int64Engine - _range = None # type: range + _range: range # check whether self._data has been called - _cached_data = None # type: np.ndarray + _cached_data: Optional[np.ndarray] = None # -------------------------------------------------------------------- # Constructors @@ -654,7 +654,7 @@ def _concat_same_dtype(self, indexes, name): non_empty_indexes = [obj for obj in indexes if len(obj)] for obj in non_empty_indexes: - rng = obj._range # type: range + rng: range = obj._range if start is None: # This is set by the first non-empty index diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 673764ef6a124..b52015b738c6e 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -100,7 +100,7 @@ class IndexingError(Exception): class _NDFrameIndexer(_NDFrameIndexerBase): - _valid_types = None # type: str + _valid_types: str axis = None def __call__(self, axis=None): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index d53fbe2e60e9a..5e60440f1577e 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -126,7 +126,7 @@ def __init__( do_integrity_check: bool = True, ): self.axes = [ensure_index(ax) for ax in axes] - self.blocks = tuple(blocks) # type: Tuple[Block, ...] + self.blocks: Tuple[Block, ...] = tuple(blocks) for block in blocks: if self.ndim != block.ndim: diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 7e50348962fc5..a2a40bbf93604 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -660,7 +660,7 @@ def _get_counts_nanvar( count = np.nan d = np.nan else: - mask2 = count <= ddof # type: np.ndarray + mask2: np.ndarray = count <= ddof if mask2.any(): np.putmask(d, mask2, np.nan) np.putmask(count, mask2, np.nan) diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py index 5d3f9cd92aa1a..e3db65f11a332 100644 --- a/pandas/core/ops/docstrings.py +++ b/pandas/core/ops/docstrings.py @@ -233,7 +233,7 @@ def _make_flex_doc(op_name, typ): dtype: float64 """ -_op_descriptions = { +_op_descriptions: Dict[str, Dict[str, Optional[str]]] = { # Arithmetic Operators "add": { "op": "+", @@ -310,7 +310,7 @@ def _make_flex_doc(op_name, typ): "reverse": None, "series_examples": None, }, -} # type: Dict[str, Dict[str, Optional[str]]] +} _op_names = list(_op_descriptions.keys()) for key in _op_names: diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 81ec4f45ec8e1..25731c4e1c54c 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -31,7 +31,7 @@ from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import DateOffset, Day, Nano, Tick -_shared_docs_kwargs = dict() # type: Dict[str, str] +_shared_docs_kwargs: Dict[str, str] = dict() class Resampler(_GroupBy, ShallowMixin): diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 4d838db6c95f6..fdd31b3b7c022 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -583,8 +583,9 @@ def __init__( self.indicator = indicator + self.indicator_name: Optional[str] if isinstance(self.indicator, str): - self.indicator_name = self.indicator # type: Optional[str] + self.indicator_name = self.indicator elif isinstance(self.indicator, bool): self.indicator_name = "_merge" if self.indicator else None else: diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index b126b6e221ccc..c7d3adece521e 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -211,10 +211,9 @@ def _add_margins( if margins_name in table.columns.get_level_values(level): raise ValueError(msg) + key: Union[str, Tuple[str, ...]] if len(rows) > 1: - key = (margins_name,) + ("",) * ( - len(rows) - 1 - ) # type: Union[str, Tuple[str, ...]] + key = (margins_name,) + ("",) * (len(rows) - 1) else: key = margins_name @@ -564,7 +563,7 @@ def crosstab( if pass_objs: common_idx = get_objs_combined_axis(pass_objs, intersect=True, sort=False) - data = {} # type: dict + data: Dict = {} data.update(zip(rownames, index)) data.update(zip(colnames, columns)) @@ -615,11 +614,11 @@ def _normalize(table, normalize, margins: bool, margins_name="All"): if margins is False: # Actual Normalizations - normalizers = { + normalizers: Dict[Union[bool, str], Callable] = { "all": lambda x: x / x.sum(axis=1).sum(axis=0), "columns": lambda x: x / x.sum(), "index": lambda x: x.div(x.sum(axis=1), axis=0), - } # type: Dict[Union[bool, str], Callable] + } normalizers[True] = normalizers["all"] diff --git a/pandas/core/series.py b/pandas/core/series.py index a950b4496baa7..6045d6a654508 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -170,7 +170,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): Copy input data. """ - _metadata = [] # type: List[str] + _metadata: List[str] = [] _accessors = {"dt", "cat", "str", "sparse"} _deprecations = ( base.IndexOpsMixin._deprecations @@ -184,7 +184,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): hasnans = property( base.IndexOpsMixin.hasnans.func, doc=base.IndexOpsMixin.hasnans.__doc__ ) - _data = None # type: SingleBlockManager + _data: SingleBlockManager # ---------------------------------------------------------------------- # Constructors @@ -781,9 +781,10 @@ def __array_ufunc__( inputs = tuple(extract_array(x, extract_numpy=True) for x in inputs) result = getattr(ufunc, method)(*inputs, **kwargs) + + name: Optional[Hashable] if len(set(names)) == 1: - # we require names to be hashable, right? - name = names[0] # type: Any + name = names[0] else: name = None diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 413e7e85eb6fe..137c37f938dfa 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -52,7 +52,7 @@ ) _cpython_optimized_decoders = _cpython_optimized_encoders + ("utf-16", "utf-32") -_shared_docs = dict() # type: Dict[str, str] +_shared_docs: Dict[str, str] = dict() def cat_core(list_of_columns: List, sep: str): @@ -3284,7 +3284,7 @@ def rindex(self, sub, start=0, end=None): """ # _doc_args holds dict of strings to use in substituting casemethod docs - _doc_args = {} # type: Dict[str, Dict[str, str]] + _doc_args: Dict[str, Dict[str, str]] = {} _doc_args["lower"] = dict(type="lowercase", method="lower", version="") _doc_args["upper"] = dict(type="uppercase", method="upper", version="") _doc_args["title"] = dict(type="titlecase", method="title", version="") diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index fd2e8aa2ad02f..6a35664ece765 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -53,7 +53,7 @@ class _Window(PandasObject, ShallowMixin, SelectionMixin): - _attributes = [ + _attributes: List[str] = [ "window", "min_periods", "center", @@ -61,8 +61,8 @@ class _Window(PandasObject, ShallowMixin, SelectionMixin): "axis", "on", "closed", - ] # type: List[str] - exclusions = set() # type: Set[str] + ] + exclusions: Set[str] = set() def __init__( self, @@ -449,7 +449,7 @@ def _apply( window_indexer = self._get_window_indexer() results = [] - exclude = [] # type: List[Scalar] + exclude: List[Scalar] = [] for i, b in enumerate(blocks): try: values = self._prep_values(b.values) diff --git a/pandas/io/common.py b/pandas/io/common.py index bd3808cf37b6b..c0eddb679c6f8 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -418,7 +418,7 @@ def _get_handle( except ImportError: need_text_wrapping = BufferedIOBase # type: ignore - handles = list() # type: List[IO] + handles: List[IO] = list() f = path_or_buf # Convert pathlib.Path/py.path.local or string diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py index 97556f9685001..78054936f50f2 100644 --- a/pandas/io/excel/_odfreader.py +++ b/pandas/io/excel/_odfreader.py @@ -76,12 +76,12 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: empty_rows = 0 max_row_len = 0 - table = [] # type: List[List[Scalar]] + table: List[List[Scalar]] = [] for i, sheet_row in enumerate(sheet_rows): sheet_cells = [x for x in sheet_row.childNodes if x.qname in cell_names] empty_cells = 0 - table_row = [] # type: List[Scalar] + table_row: List[Scalar] = [] for j, sheet_cell in enumerate(sheet_cells): if sheet_cell.qname == table_cell_name: diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index d0d6096a4425e..d278c6b3bbef2 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -531,7 +531,7 @@ def _convert_cell(self, cell, convert_float: bool) -> Scalar: return cell.value def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: - data = [] # type: List[List[Scalar]] + data: List[List[Scalar]] = [] for row in sheet.rows: data.append([self._convert_cell(cell, convert_float) for cell in row]) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 41bddc7683764..b18f0db622b3e 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -262,6 +262,8 @@ def __init__( def _chk_truncate(self) -> None: from pandas.core.reshape.concat import concat + self.tr_row_num: Optional[int] + min_rows = self.min_rows max_rows = self.max_rows # truncation determined by max_rows, actual truncated number of rows @@ -280,7 +282,7 @@ def _chk_truncate(self) -> None: else: row_num = max_rows // 2 series = concat((series.iloc[:row_num], series.iloc[-row_num:])) - self.tr_row_num = row_num # type: Optional[int] + self.tr_row_num = row_num else: self.tr_row_num = None self.tr_series = series @@ -448,13 +450,13 @@ def _get_adjustment() -> TextAdjustment: class TableFormatter: - show_dimensions = None # type: bool - is_truncated = None # type: bool - formatters = None # type: formatters_type - columns = None # type: Index + show_dimensions: bool + is_truncated: bool + formatters: formatters_type + columns: Index @property - def should_show_dimensions(self) -> Optional[bool]: + def should_show_dimensions(self) -> bool: return self.show_dimensions is True or ( self.show_dimensions == "truncate" and self.is_truncated ) @@ -616,6 +618,8 @@ def _chk_truncate(self) -> None: # Cut the data to the information actually printed max_cols = self.max_cols max_rows = self.max_rows + self.max_rows_adj: Optional[int] + max_rows_adj: Optional[int] if max_cols == 0 or max_rows == 0: # assume we are in the terminal (w, h) = get_terminal_size() @@ -631,7 +635,7 @@ def _chk_truncate(self) -> None: self.header = cast(bool, self.header) n_add_rows = self.header + dot_row + show_dimension_rows + prompt_row # rows available to fill with actual data - max_rows_adj = self.h - n_add_rows # type: Optional[int] + max_rows_adj = self.h - n_add_rows self.max_rows_adj = max_rows_adj # Format only rows and columns that could potentially fit the @@ -1073,7 +1077,7 @@ def _get_formatted_index(self, frame: "DataFrame") -> List[str]: return adjoined def _get_column_name_list(self) -> List[str]: - names = [] # type: List[str] + names: List[str] = [] columns = self.frame.columns if isinstance(columns, ABCMultiIndex): names.extend("" if name is None else name for name in columns.names) @@ -1124,8 +1128,9 @@ def format_array( List[str] """ + fmt_klass: Type[GenericArrayFormatter] if is_datetime64_dtype(values.dtype): - fmt_klass = Datetime64Formatter # type: Type[GenericArrayFormatter] + fmt_klass = Datetime64Formatter elif is_datetime64tz_dtype(values): fmt_klass = Datetime64TZFormatter elif is_timedelta64_dtype(values.dtype): @@ -1375,11 +1380,12 @@ def format_values_with(float_format): # There is a special default string when we are fixed-width # The default is otherwise to use str instead of a formatting string + float_format: Optional[float_format_type] if self.float_format is None: if self.fixed_width: float_format = partial( "{value: .{digits:d}f}".format, digits=self.digits - ) # type: Optional[float_format_type] + ) else: float_format = self.float_format else: diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py index 38f2e332017f0..0c6b0c1a5810b 100644 --- a/pandas/io/formats/html.py +++ b/pandas/io/formats/html.py @@ -45,7 +45,7 @@ def __init__( self.frame = self.fmt.frame self.columns = self.fmt.tr_frame.columns - self.elements = [] # type: List[str] + self.elements: List[str] = [] self.bold_rows = self.fmt.bold_rows self.escape = self.fmt.escape self.show_dimensions = self.fmt.show_dimensions @@ -138,11 +138,10 @@ def _write_cell( else: start_tag = "<{kind}>".format(kind=kind) + esc: Union[OrderedDict[str, str], Dict] if self.escape: # escape & first to prevent double escaping of & - esc = OrderedDict( - [("&", r"&amp;"), ("<", r"&lt;"), (">", r"&gt;")] - ) # type: Union[OrderedDict[str, str], Dict] + esc = OrderedDict([("&", r"&amp;"), ("<", r"&lt;"), (">", r"&gt;")]) else: esc = {} @@ -408,7 +407,7 @@ def _write_regular_rows( else: index_values = self.fmt.tr_frame.index.format() - row = [] # type: List[str] + row: List[str] = [] for i in range(nrows): if truncate_v and i == (self.fmt.tr_row_num): diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py index 6f903e770c86c..008a99427f3c7 100644 --- a/pandas/io/formats/latex.py +++ b/pandas/io/formats/latex.py @@ -133,7 +133,7 @@ def pad_empties(x): if self.fmt.has_index_names and self.fmt.show_index_names: nlevels += 1 strrows = list(zip(*strcols)) - self.clinebuf = [] # type: List[List[int]] + self.clinebuf: List[List[int]] = [] for i, row in enumerate(strrows): if i == nlevels and self.fmt.header: diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index 061103820ca83..a4f1488fb6b69 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -513,7 +513,7 @@ def format_object_attrs( list of 2-tuple """ - attrs = [] # type: List[Tuple[str, Union[str, int]]] + attrs: List[Tuple[str, Union[str, int]]] = [] if hasattr(obj, "dtype") and include_dtype: # error: "Sequence[Any]" has no attribute "dtype" attrs.append(("dtype", "'{}'".format(obj.dtype))) # type: ignore diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 26a3248262f9a..89d5b52ffbf1e 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -62,8 +62,10 @@ def to_json( if orient == "table" and isinstance(obj, Series): obj = obj.to_frame(name=obj.name or "values") + + writer: Type["Writer"] if orient == "table" and isinstance(obj, DataFrame): - writer = JSONTableWriter # type: Type["Writer"] + writer = JSONTableWriter elif isinstance(obj, Series): writer = SeriesWriter elif isinstance(obj, DataFrame): diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index 702241bde2b34..df513d4d37d71 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -267,10 +267,10 @@ def _pull_field(js, spec): meta = [m if isinstance(m, list) else [m] for m in meta] # Disastrously inefficient for now - records = [] # type: List + records: List = [] lengths = [] - meta_vals = defaultdict(list) # type: DefaultDict + meta_vals: DefaultDict = defaultdict(list) meta_keys = [sep.join(val) for val in meta] def _recursive_extract(data, path, seen_meta, level=0): diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index ff3583b79d79c..cf1511c1221b3 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -522,8 +522,8 @@ def _read(filepath_or_buffer: FilePathOrBuffer, kwds): _c_unsupported = {"skipfooter"} _python_unsupported = {"low_memory", "float_precision"} -_deprecated_defaults = {} # type: Dict[str, Any] -_deprecated_args = set() # type: Set[str] +_deprecated_defaults: Dict[str, Any] = {} +_deprecated_args: Set[str] = set() def _make_parser_function(name, default_sep=","): diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 9a1bfdd2be798..ba53d8cfd0de5 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1343,7 +1343,7 @@ def copy( data = self.select(k) if s.is_table: - index = False # type: Union[bool, list] + index: Union[bool, list] = False if propindexes: index = [a.name for a in s.axes if a.is_indexed] new_store.append( @@ -2548,9 +2548,9 @@ class Fixed: group : the group node where the table resides """ - pandas_kind = None # type: str - obj_type = None # type: Type[Union[DataFrame, Series]] - ndim = None # type: int + pandas_kind: str + obj_type: Type[Union[DataFrame, Series]] + ndim: int is_table = False def __init__(self, parent, group, encoding=None, errors="strict", **kwargs): @@ -2708,7 +2708,7 @@ class GenericFixed(Fixed): _index_type_map = {DatetimeIndex: "datetime", PeriodIndex: "period"} _reverse_index_map = {v: k for k, v in _index_type_map.items()} - attributes = [] # type: List[str] + attributes: List[str] = [] # indexer helpders def _class_to_alias(self, cls) -> str: @@ -3254,7 +3254,7 @@ class Table(Fixed): """ pandas_kind = "wide_table" - table_type = None # type: str + table_type: str levels = 1 is_table = True is_shape_reversed = False @@ -4147,11 +4147,11 @@ class LegacyTable(Table): """ - _indexables = [ + _indexables: Optional[List[IndexCol]] = [ IndexCol(name="index", axis=1, pos=0), IndexCol(name="column", axis=2, pos=1, index_kind="columns_kind"), DataCol(name="fields", cname="values", kind_attr="fields", pos=2), - ] # type: Optional[List[IndexCol]] + ] table_type = "legacy" ndim = 3 @@ -4424,7 +4424,7 @@ class AppendableFrameTable(AppendableTable): pandas_kind = "frame_table" table_type = "appendable_frame" ndim = 2 - obj_type = DataFrame # type: Type[Union[DataFrame, Series]] + obj_type: Type[Union[DataFrame, Series]] = DataFrame @property def is_transposed(self) -> bool: @@ -4650,7 +4650,7 @@ def _reindex_axis(obj, axis: int, labels: Index, other=None): if other is not None: labels = ensure_index(other.unique()).intersection(labels, sort=False) if not labels.equals(ax): - slicer = [slice(None, None)] * obj.ndim # type: List[Union[slice, Index]] + slicer: List[Union[slice, Index]] = [slice(None, None)] * obj.ndim slicer[axis] = labels obj = obj.loc[tuple(slicer)] return obj diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 5341dc3a6338a..0c5375ccc5d5c 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -57,7 +57,7 @@ def _kind(self): _layout_type = "vertical" _default_rot = 0 - orientation = None # type: Optional[str] + orientation: Optional[str] = None _pop_attributes = [ "label", "style", diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index 601fde80e9a94..5d11e160bbd71 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -43,7 +43,7 @@ class TestPDApi(Base): ] # these are already deprecated; awaiting removal - deprecated_modules = [] # type: List[str] + deprecated_modules: List[str] = [] # misc misc = ["IndexSlice", "NaT"] @@ -94,10 +94,10 @@ class TestPDApi(Base): classes.extend(["Panel", "SparseSeries", "SparseDataFrame"]) # these are already deprecated; awaiting removal - deprecated_classes = [] # type: List[str] + deprecated_classes: List[str] = [] # these should be deprecated in the future - deprecated_classes_in_future = [] # type: List[str] + deprecated_classes_in_future: List[str] = [] # external modules exposed in pandas namespace modules = ["np", "datetime"] @@ -173,10 +173,10 @@ class TestPDApi(Base): funcs_to = ["to_datetime", "to_msgpack", "to_numeric", "to_pickle", "to_timedelta"] # top-level to deprecate in the future - deprecated_funcs_in_future = [] # type: List[str] + deprecated_funcs_in_future: List[str] = [] # these are already deprecated; awaiting removal - deprecated_funcs = [] # type: List[str] + deprecated_funcs: List[str] = [] # private modules in pandas namespace private_modules = [ diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 3bacd560e75cf..5cab0c1fe6d59 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -57,7 +57,7 @@ def timedelta_index(request): class SharedTests: - index_cls = None # type: Type[Union[DatetimeIndex, PeriodIndex, TimedeltaIndex]] + index_cls: Type[Union[DatetimeIndex, PeriodIndex, TimedeltaIndex]] def test_compare_len1_raises(self): # make sure we raise when comparing with different lengths, specific diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index a075521b67561..c6ce08080314a 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -1889,11 +1889,11 @@ def test_invalid_parser(): pd.eval("x + y", local_dict={"x": 1, "y": 2}, parser="asdf") -_parsers = { +_parsers: Dict[str, Type[BaseExprVisitor]] = { "python": PythonExprVisitor, "pytables": pytables.ExprVisitor, "pandas": PandasExprVisitor, -} # type: Dict[str, Type[BaseExprVisitor]] +} @pytest.mark.parametrize("engine", _engines) diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index ae625ed8e389f..6d91d13027f69 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -290,7 +290,7 @@ def test_is_datetime_arraylike(): assert com.is_datetime_arraylike(pd.DatetimeIndex([1, 2, 3])) -integer_dtypes = [] # type: List +integer_dtypes: List = [] @pytest.mark.parametrize( @@ -322,7 +322,7 @@ def test_is_not_integer_dtype(dtype): assert not com.is_integer_dtype(dtype) -signed_integer_dtypes = [] # type: List +signed_integer_dtypes: List = [] @pytest.mark.parametrize( @@ -358,7 +358,7 @@ def test_is_not_signed_integer_dtype(dtype): assert not com.is_signed_integer_dtype(dtype) -unsigned_integer_dtypes = [] # type: List +unsigned_integer_dtypes: List = [] @pytest.mark.parametrize( diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index e968962caf0b7..5e4fb6d69e52c 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -62,10 +62,10 @@ class BaseArithmeticOpsTests(BaseOpsUtil): * divmod_exc = TypeError """ - series_scalar_exc = TypeError # type: Optional[Type[TypeError]] - frame_scalar_exc = TypeError # type: Optional[Type[TypeError]] - series_array_exc = TypeError # type: Optional[Type[TypeError]] - divmod_exc = TypeError # type: Optional[Type[TypeError]] + series_scalar_exc: Optional[Type[TypeError]] = TypeError + frame_scalar_exc: Optional[Type[TypeError]] = TypeError + series_array_exc: Optional[Type[TypeError]] = TypeError + divmod_exc: Optional[Type[TypeError]] = TypeError def test_arith_series_with_scalar(self, data, all_arithmetic_operators): # series & scalar diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 1ac6370860ba6..c35c4c3568f74 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -31,7 +31,7 @@ class Base: """ base class for index sub-class tests """ - _holder = None # type: Optional[Type[Index]] + _holder: Optional[Type[Index]] = None _compat_props = ["shape", "ndim", "size", "nbytes"] def test_pickle_compat_construction(self): diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 469c011001467..8b29cf3813d13 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -927,7 +927,7 @@ class TestReplaceSeriesCoercion(CoercionBase): klasses = ["series"] method = "replace" - rep = {} # type: Dict[str, List] + rep: Dict[str, List] = {} rep["object"] = ["a", "b"] rep["int64"] = [4, 5] rep["float64"] = [1.1, 2.2] diff --git a/pandas/tests/io/parser/conftest.py b/pandas/tests/io/parser/conftest.py index 183ad500b15f3..a87e1e796c194 100644 --- a/pandas/tests/io/parser/conftest.py +++ b/pandas/tests/io/parser/conftest.py @@ -7,9 +7,9 @@ class BaseParser: - engine = None # type: Optional[str] + engine: Optional[str] = None low_memory = True - float_precision_choices = [] # type: List[Optional[str]] + float_precision_choices: List[Optional[str]] = [] def update_kwargs(self, kwargs): kwargs = kwargs.copy() diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 1c80dd9e59164..fe65820a7c975 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -583,7 +583,7 @@ class _TestSQLApi(PandasSQLTest): """ flavor = "sqlite" - mode = None # type: str + mode: str def setup_connect(self): self.conn = self.connect() @@ -1234,7 +1234,7 @@ class _TestSQLAlchemy(SQLAlchemyMixIn, PandasSQLTest): """ - flavor = None # type: str + flavor: str @pytest.fixture(autouse=True, scope="class") def setup_class(cls): diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index e443a7cc932be..d70780741aa88 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -1,5 +1,5 @@ from datetime import date, datetime, time as dt_time, timedelta -from typing import Dict, List, Tuple, Type +from typing import Dict, List, Optional, Tuple, Type import numpy as np import pytest @@ -95,7 +95,7 @@ def test_to_M8(): class Base: - _offset = None # type: Type[DateOffset] + _offset: Optional[Type[DateOffset]] = None d = Timestamp(datetime(2008, 1, 2)) timezones = [ @@ -743,7 +743,7 @@ def test_onOffset(self): for offset, d, expected in tests: assert_onOffset(offset, d, expected) - apply_cases = [] # type: _ApplyCases + apply_cases: _ApplyCases = [] apply_cases.append( ( BDay(), @@ -2631,7 +2631,7 @@ def test_onOffset(self, case): offset, d, expected = case assert_onOffset(offset, d, expected) - apply_cases = [] # type: _ApplyCases + apply_cases: _ApplyCases = [] apply_cases.append( ( CDay(), @@ -2878,7 +2878,7 @@ def test_onOffset(self, case): offset, d, expected = case assert_onOffset(offset, d, expected) - apply_cases = [] # type: _ApplyCases + apply_cases: _ApplyCases = [] apply_cases.append( ( CBMonthEnd(), @@ -3027,7 +3027,7 @@ def test_onOffset(self, case): offset, dt, expected = case assert_onOffset(offset, dt, expected) - apply_cases = [] # type: _ApplyCases + apply_cases: _ApplyCases = [] apply_cases.append( ( CBMonthBegin(), diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 9ec0dce438099..898060d011372 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -49,7 +49,7 @@ # Offset names ("time rules") and related functions #: cache of previously seen offsets -_offset_map = {} # type: Dict[str, DateOffset] +_offset_map: Dict[str, DateOffset] = {} def get_period_alias(offset_str): diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index d4f02286ff8d6..9417dc4b48499 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -344,7 +344,7 @@ class AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass): Abstract interface to create holidays following certain rules. """ - rules = [] # type: List[Holiday] + rules: List[Holiday] = [] start_date = Timestamp(datetime(1970, 1, 1)) end_date = Timestamp(datetime(2200, 12, 31)) _cache = None diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index f5e40e712642e..e516d30d5490f 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1817,8 +1817,8 @@ class QuarterOffset(DateOffset): Quarter representation - doesn't call super. """ - _default_startingMonth = None # type: Optional[int] - _from_name_startingMonth = None # type: Optional[int] + _default_startingMonth: Optional[int] = None + _from_name_startingMonth: Optional[int] = None _adjust_dst = True _attributes = frozenset(["n", "normalize", "startingMonth"]) # TODO: Consider combining QuarterOffset and YearOffset __init__ at some diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index f8c08ed8c099f..b8f17cd848292 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -327,9 +327,11 @@ def my_dog(has='fleas'): pass """ + addendum: Optional[str] + def __init__(self, addendum: Optional[str], join: str = "", indents: int = 0): if indents > 0: - self.addendum = indent(addendum, indents=indents) # type: Optional[str] + self.addendum = indent(addendum, indents=indents) else: self.addendum = addendum self.join = join
https://api.github.com/repos/pandas-dev/pandas/pulls/29741
2019-11-20T15:32:52Z
2019-11-21T16:27:40Z
2019-11-21T16:27:39Z
2019-11-21T16:27:40Z
DOC: fix typos
diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx index d3b5ecfdaa178..1906193622953 100644 --- a/pandas/_libs/hashing.pyx +++ b/pandas/_libs/hashing.pyx @@ -75,7 +75,7 @@ def hash_object_array(object[:] arr, object key, object encoding='utf8'): lens[i] = l cdata = data - # keep the references alive thru the end of the + # keep the references alive through the end of the # function datas.append(data) vecs[i] = cdata diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in index c4284ae403e5c..f8f3858b803a5 100644 --- a/pandas/_libs/hashtable_func_helper.pxi.in +++ b/pandas/_libs/hashtable_func_helper.pxi.in @@ -144,13 +144,13 @@ def duplicated_{{dtype}}({{c_type}}[:] values, object keep='first'): if keep == 'last': {{if dtype == 'object'}} for i in range(n - 1, -1, -1): - # equivalent: range(n)[::-1], which cython doesnt like in nogil + # equivalent: range(n)[::-1], which cython doesn't like in nogil kh_put_{{ttype}}(table, <PyObject*>values[i], &ret) out[i] = ret == 0 {{else}} with nogil: for i in range(n - 1, -1, -1): - # equivalent: range(n)[::-1], which cython doesnt like in nogil + # equivalent: range(n)[::-1], which cython doesn't like in nogil kh_put_{{ttype}}(table, values[i], &ret) out[i] = ret == 0 {{endif}} diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index 86b06397123b7..d6bad0f20d760 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -1914,7 +1914,7 @@ def roll_weighted_var(float64_t[:] values, float64_t[:] weights, values: float64_t[:] values to roll window over weights: float64_t[:] - array of weights whose lenght is window size + array of weights whose length is window size minp: int64_t minimum number of observations to calculate variance of a window diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index e3f1ae78efcec..9c14102529b48 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -109,7 +109,7 @@ def _ensure_data(values, dtype=None): except (TypeError, ValueError, OverflowError): # if we are trying to coerce to a dtype - # and it is incompat this will fall thru to here + # and it is incompat this will fall through to here return ensure_object(values), "object" # datetimelike diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index e52bc17fcc319..8e66db4c61032 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1486,7 +1486,7 @@ def mean(self, skipna=True): values = self if not len(values): - # short-circut for empty max / min + # short-circuit for empty max / min return NaT result = nanops.nanmean(values.view("i8"), skipna=skipna) diff --git a/pandas/core/series.py b/pandas/core/series.py index 3f69dd53491c1..14056c99bd686 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2087,7 +2087,7 @@ def idxmin(self, axis=0, skipna=True, *args, **kwargs): will be NA. *args, **kwargs Additional arguments and keywords have no effect but might be - accepted for compatability with NumPy. + accepted for compatibility with NumPy. Returns ------- diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index dce0afd8670b2..6fc4e21d33d16 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1450,7 +1450,7 @@ def _get_level_lengths(index, hidden_elements=None): Optional argument is a list of index positions which should not be visible. - Result is a dictionary of (level, inital_position): span + Result is a dictionary of (level, initial_position): span """ sentinel = object() levels = index.format(sparsify=sentinel, adjoin=False, names=False)
Changes only words in comments; function names not touched.
https://api.github.com/repos/pandas-dev/pandas/pulls/29739
2019-11-20T15:09:31Z
2019-11-20T16:31:34Z
2019-11-20T16:31:34Z
2019-11-20T16:40:39Z
DOC: Add link to dev calendar and meeting notes
diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst index a523ae0c957f1..757b197c717e6 100644 --- a/doc/source/development/index.rst +++ b/doc/source/development/index.rst @@ -19,3 +19,4 @@ Development developer policies roadmap + meeting diff --git a/doc/source/development/meeting.rst b/doc/source/development/meeting.rst new file mode 100644 index 0000000000000..1d19408692cda --- /dev/null +++ b/doc/source/development/meeting.rst @@ -0,0 +1,32 @@ +.. _meeting: + +================== +Developer Meetings +================== + +We hold regular developer meetings on the second Wednesday +of each month at 18:00 UTC. These meetings and their minutes are open to +the public. All are welcome to join. + +Minutes +------- + +The minutes of past meetings are available in `this Google Document <https://docs.google.com/document/d/1tGbTiYORHiSPgVMXawiweGJlBw5dOkVJLY-licoBmBU/edit?usp=sharing>`__. + +Calendar +-------- + +This calendar shows all the developer meetings. + +.. raw:: html + + <iframe src="https://calendar.google.com/calendar/embed?src=pgbn14p6poja8a1cf2dv2jhrmg%40group.calendar.google.com" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe> + +You can subscribe to this calendar with the following links: + +* `iCal <https://calendar.google.com/calendar/ical/pgbn14p6poja8a1cf2dv2jhrmg%40group.calendar.google.com/public/basic.ics>`__ +* `Google calendar <https://calendar.google.com/calendar/embed?src=pgbn14p6poja8a1cf2dv2jhrmg%40group.calendar.google.com>`__ + +Additionally, we'll sometimes have one-off meetings on specific topics. +These will be published on the same calendar. +
https://api.github.com/repos/pandas-dev/pandas/pulls/29737
2019-11-20T13:43:09Z
2019-11-25T14:03:56Z
2019-11-25T14:03:56Z
2019-11-25T14:03:56Z
xfail clipboard for now
diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index 4559ba264d8b7..666dfd245acaa 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -258,6 +258,7 @@ def test_round_trip_valid_encodings(self, enc, df): @pytest.mark.clipboard @pytest.mark.skipif(not _DEPS_INSTALLED, reason="clipboard primitives not installed") @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑´...", "abcd..."]) +@pytest.mark.xfail(reason="flaky in CI", strict=False) def test_raw_roundtrip(data): # PR #25040 wide unicode wasn't copied correctly on PY3 on windows clipboard_set(data)
xref #29676, https://github.com/pandas-dev/pandas/pull/29712.
https://api.github.com/repos/pandas-dev/pandas/pulls/29736
2019-11-20T12:54:01Z
2019-11-20T14:09:51Z
2019-11-20T14:09:50Z
2019-11-20T14:09:54Z
DEPR: enforce deprecations for kwargs in factorize, FrozenNDArray.ser…
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 98d861d999ea9..90ad5f4f3237d 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -280,6 +280,10 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed the previously deprecated ``assert_raises_regex`` function in ``pandas.util.testing`` (:issue:`29174`) - Removed :meth:`Index.is_lexsorted_for_tuple` (:issue:`29305`) - Removed support for nexted renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`29608`) +- Removed previously deprecated "order" argument from :func:`factorize` (:issue:`19751`) +- Removed previously deprecated "v" argument from :meth:`FrozenNDarray.searchsorted`, use "value" instead (:issue:`22672`) +- Removed previously deprecated "raise_conflict" argument from :meth:`DataFrame.update`, use "errors" instead (:issue:`23585`) +- Removed previously deprecated keyword "n" from :meth:`DatetimeIndex.shift`, :meth:`TimedeltaIndex.shift`, :meth:`PeriodIndex.shift`, use "periods" instead (:issue:`22458`) - .. _whatsnew_1000.performance: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index ea75d46048e63..e3f1ae78efcec 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -10,7 +10,7 @@ from pandas._libs import Timestamp, algos, hashtable as htable, lib from pandas._libs.tslib import iNaT -from pandas.util._decorators import Appender, Substitution, deprecate_kwarg +from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.cast import ( construct_1d_object_array_from_listlike, @@ -494,7 +494,7 @@ def _factorize_array( Parameters ---------- - %(values)s%(sort)s%(order)s + %(values)s%(sort)s na_sentinel : int, default -1 Value to mark "not found". %(size_hint)s\ @@ -585,14 +585,6 @@ def _factorize_array( coerced to ndarrays before factorization. """ ), - order=dedent( - """\ - order : None - .. deprecated:: 0.23.0 - - This parameter has no effect and is deprecated. - """ - ), sort=dedent( """\ sort : bool, default False @@ -608,13 +600,8 @@ def _factorize_array( ), ) @Appender(_shared_docs["factorize"]) -@deprecate_kwarg(old_arg_name="order", new_arg_name=None) def factorize( - values, - sort: bool = False, - order=None, - na_sentinel: int = -1, - size_hint: Optional[int] = None, + values, sort: bool = False, na_sentinel: int = -1, size_hint: Optional[int] = None, ) -> Tuple[np.ndarray, Union[np.ndarray, ABCIndex]]: # Implementation notes: This method is responsible for 3 things # 1.) coercing data to array-like (ndarray, Index, extension array) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0b76566adf802..5baba0bae1d45 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5528,11 +5528,6 @@ def combiner(x, y): return self.combine(other, combiner, overwrite=False) - @deprecate_kwarg( - old_arg_name="raise_conflict", - new_arg_name="errors", - mapping={False: "ignore", True: "raise"}, - ) def update( self, other, join="left", overwrite=True, filter_func=None, errors="ignore" ): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index b8670b765ca90..df3420ea14e24 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -11,7 +11,7 @@ from pandas._libs.algos import unique_deltas from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError -from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg +from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_int64, @@ -732,8 +732,7 @@ def astype(self, dtype, copy=True): # _data.astype call above return Index(new_values, dtype=new_values.dtype, name=self.name, copy=False) - @deprecate_kwarg(old_arg_name="n", new_arg_name="periods") - def shift(self, periods, freq=None): + def shift(self, periods=1, freq=None): """ Shift index by desired number of time frequency increments. @@ -742,7 +741,7 @@ def shift(self, periods, freq=None): Parameters ---------- - periods : int + periods : int, default 1 Number of periods (or increments) to shift by, can be positive or negative. diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index 1b33269d404d6..2c9521d23f71a 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -11,8 +11,6 @@ import numpy as np -from pandas.util._decorators import deprecate_kwarg - from pandas.core.dtypes.cast import coerce_indexer_dtype from pandas.core.base import PandasObject @@ -155,7 +153,6 @@ def __repr__(self) -> str: prepr = pprint_thing(self, escape_chars=("\t", "\r", "\n"), quote_strings=True) return f"{type(self).__name__}({prepr}, dtype='{self.dtype}')" - @deprecate_kwarg(old_arg_name="v", new_arg_name="value") def searchsorted(self, value, side="left", sorter=None): """ Find indices to insert `value` so as to maintain order. diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index 12d06dc517f19..e72de487abb2f 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -369,13 +369,6 @@ def test_update_raise_on_overlap(self): with pytest.raises(ValueError, match="Data overlaps"): df.update(other, errors="raise") - @pytest.mark.parametrize("raise_conflict", [True, False]) - def test_update_deprecation(self, raise_conflict): - df = DataFrame([[1.5, 1, 3.0]]) - other = DataFrame() - with tm.assert_produces_warning(FutureWarning): - df.update(other, raise_conflict=raise_conflict) - def test_update_from_non_df(self): d = {"a": Series([1, 2, 3, 4]), "b": Series([5, 6, 7, 8])} df = DataFrame(d) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 2ec267c66091b..2944767ba4c02 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -549,8 +549,6 @@ def test_shift_periods(self): idx = pd.date_range(start=START, end=END, periods=3) tm.assert_index_equal(idx.shift(periods=0), idx) tm.assert_index_equal(idx.shift(0), idx) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=True): - tm.assert_index_equal(idx.shift(n=0), idx) def test_pickle_unpickle(self): unpickled = tm.round_trip_pickle(self.rng) diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_arithmetic.py index 80e4b1fe1e430..f8274a82f1b6f 100644 --- a/pandas/tests/indexes/period/test_arithmetic.py +++ b/pandas/tests/indexes/period/test_arithmetic.py @@ -117,5 +117,3 @@ def test_shift_periods(self): idx = period_range(freq="A", start="1/1/2001", end="12/1/2009") tm.assert_index_equal(idx.shift(periods=0), idx) tm.assert_index_equal(idx.shift(0), idx) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=True): - tm.assert_index_equal(idx.shift(n=0), idx) diff --git a/pandas/tests/indexes/test_frozen.py b/pandas/tests/indexes/test_frozen.py index 712feb7b8ef61..c7b219b5ee890 100644 --- a/pandas/tests/indexes/test_frozen.py +++ b/pandas/tests/indexes/test_frozen.py @@ -112,5 +112,4 @@ def test_searchsorted(self): expected = 2 assert self.container.searchsorted(7) == expected - with tm.assert_produces_warning(FutureWarning): - assert self.container.searchsorted(v=7) == expected + assert self.container.searchsorted(value=7) == expected diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index baf78d7188b41..9e89a1b6f0467 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -256,7 +256,7 @@ def test_deprecate_order(self): # gh 19727 - check warning is raised for deprecated keyword, order. # Test not valid once order keyword is removed. data = np.array([2 ** 63, 1, 2 ** 63], dtype=np.uint64) - with tm.assert_produces_warning(expected_warning=FutureWarning): + with pytest.raises(TypeError, match="got an unexpected keyword"): algos.factorize(data, order=True) with tm.assert_produces_warning(False): algos.factorize(data)
…achsorted, DataFrame.update, DatetimeIndex.shift, TimedeltaIndex.shift, PeriodIndex.shift
https://api.github.com/repos/pandas-dev/pandas/pulls/29732
2019-11-20T03:25:04Z
2019-11-20T12:24:31Z
2019-11-20T12:24:31Z
2019-11-20T15:26:10Z
DEPR: change DTI.to_series keep_tz default to True
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 98d861d999ea9..111b2e736b21c 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -275,6 +275,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - :meth:`pandas.Series.str.cat` does not accept list-likes *within* list-likes anymore (:issue:`27611`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) - Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) +- Changed the default value for the "keep_tz" argument in :meth:`DatetimeIndex.to_series` to ``True`` (:issue:`23739`) - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) - Removed the previously deprecated ``reduce`` and ``broadcast`` arguments from :meth:`DataFrame.apply` (:issue:`18577`) - Removed the previously deprecated ``assert_raises_regex`` function in ``pandas.util.testing`` (:issue:`29174`) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 4a95f0a2ab7e9..b6891bc7e2b59 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -663,14 +663,14 @@ def _get_time_micros(self): values = self._data._local_timestamps() return fields.get_time_micros(values) - def to_series(self, keep_tz=None, index=None, name=None): + def to_series(self, keep_tz=lib._no_default, index=None, name=None): """ Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index. Parameters ---------- - keep_tz : optional, defaults False + keep_tz : optional, defaults True Return the data keeping the timezone. If keep_tz is True: @@ -686,10 +686,10 @@ def to_series(self, keep_tz=None, index=None, name=None): Series will have a datetime64[ns] dtype. TZ aware objects will have the tz removed. - .. versionchanged:: 0.24 - The default value will change to True in a future release. - You can set ``keep_tz=True`` to already obtain the future - behaviour and silence the warning. + .. versionchanged:: 1.0.0 + The default value is now True. In a future version, + this keyword will be removed entirely. Stop passing the + argument to obtain the future behavior and silence the warning. index : Index, optional Index of resulting Series. If None, defaults to original index. @@ -708,27 +708,27 @@ def to_series(self, keep_tz=None, index=None, name=None): if name is None: name = self.name - if keep_tz is None and self.tz is not None: - warnings.warn( - "The default of the 'keep_tz' keyword in " - "DatetimeIndex.to_series will change " - "to True in a future release. You can set " - "'keep_tz=True' to obtain the future behaviour and " - "silence this warning.", - FutureWarning, - stacklevel=2, - ) - keep_tz = False - elif keep_tz is False: - warnings.warn( - "Specifying 'keep_tz=False' is deprecated and this " - "option will be removed in a future release. If " - "you want to remove the timezone information, you " - "can do 'idx.tz_convert(None)' before calling " - "'to_series'.", - FutureWarning, - stacklevel=2, - ) + if keep_tz is not lib._no_default: + if keep_tz: + warnings.warn( + "The 'keep_tz' keyword in DatetimeIndex.to_series " + "is deprecated and will be removed in a future version. " + "You can stop passing 'keep_tz' to silence this warning.", + FutureWarning, + stacklevel=2, + ) + else: + warnings.warn( + "Specifying 'keep_tz=False' is deprecated and this " + "option will be removed in a future release. If " + "you want to remove the timezone information, you " + "can do 'idx.tz_convert(None)' before calling " + "'to_series'.", + FutureWarning, + stacklevel=2, + ) + else: + keep_tz = True if keep_tz and self.tz is not None: # preserve the tz & copy diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 21470151dcfbd..6206b333d29e1 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -493,29 +493,29 @@ def test_convert_dti_to_series(self): tm.assert_series_equal(result, expected) # convert to series while keeping the timezone - result = idx.to_series(keep_tz=True, index=[0, 1]) + msg = "stop passing 'keep_tz'" + with tm.assert_produces_warning(FutureWarning) as m: + result = idx.to_series(keep_tz=True, index=[0, 1]) tm.assert_series_equal(result, expected) + assert msg in str(m[0].message) # convert to utc - with tm.assert_produces_warning(FutureWarning): + with tm.assert_produces_warning(FutureWarning) as m: df["B"] = idx.to_series(keep_tz=False, index=[0, 1]) result = df["B"] comp = Series(DatetimeIndex(expected.values).tz_localize(None), name="B") tm.assert_series_equal(result, comp) - - with tm.assert_produces_warning(FutureWarning) as m: - result = idx.to_series(index=[0, 1]) - tm.assert_series_equal(result, expected.dt.tz_convert(None)) - msg = ( - "The default of the 'keep_tz' keyword in " - "DatetimeIndex.to_series will change to True in a future " - "release." - ) + msg = "do 'idx.tz_convert(None)' before calling" assert msg in str(m[0].message) - with tm.assert_produces_warning(FutureWarning): + result = idx.to_series(index=[0, 1]) + tm.assert_series_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning) as m: result = idx.to_series(keep_tz=False, index=[0, 1]) tm.assert_series_equal(result, expected.dt.tz_convert(None)) + msg = "do 'idx.tz_convert(None)' before calling" + assert msg in str(m[0].message) # list of datetimes with a tz df["B"] = idx.to_pydatetime() diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index cccce96a874dd..cc2e37c14bdf0 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1795,7 +1795,7 @@ def test_constructor_with_datetimes(self): # preserver an index with a tz on dict construction i = date_range("1/1/2011", periods=5, freq="10s", tz="US/Eastern") - expected = DataFrame({"a": i.to_series(keep_tz=True).reset_index(drop=True)}) + expected = DataFrame({"a": i.to_series().reset_index(drop=True)}) df = DataFrame() df["a"] = i tm.assert_frame_equal(df, expected) @@ -1806,9 +1806,7 @@ def test_constructor_with_datetimes(self): # multiples i_no_tz = date_range("1/1/2011", periods=5, freq="10s") df = DataFrame({"a": i, "b": i_no_tz}) - expected = DataFrame( - {"a": i.to_series(keep_tz=True).reset_index(drop=True), "b": i_no_tz} - ) + expected = DataFrame({"a": i.to_series().reset_index(drop=True), "b": i_no_tz}) tm.assert_frame_equal(df, expected) def test_constructor_datetimes_with_nulls(self): diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index d9bdceb258592..58093ba4d90a5 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -179,7 +179,7 @@ def setup_method(self, method): self.int_series = Series(arr, index=self.int_index, name="a") self.float_series = Series(arr, index=self.float_index, name="a") self.dt_series = Series(arr, index=self.dt_index, name="a") - self.dt_tz_series = self.dt_tz_index.to_series(keep_tz=True) + self.dt_tz_series = self.dt_tz_index.to_series() self.period_series = Series(arr, index=self.period_index, name="a") self.string_series = Series(arr, index=self.string_index, name="a") self.unicode_series = Series(arr, index=self.unicode_index, name="a")
We _also_ have a deprecation to remove the keyword altogether, but we can't enforce that until we give people time to stop passing `keep_tz=True`
https://api.github.com/repos/pandas-dev/pandas/pulls/29731
2019-11-20T03:22:20Z
2019-11-20T12:26:25Z
2019-11-20T12:26:25Z
2019-11-20T15:23:20Z
DEPR: remove reduce kwd from DataFrame.apply
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5baba0bae1d45..4c4254be7f4cb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6593,9 +6593,7 @@ def transform(self, func, axis=0, *args, **kwargs): return self.T.transform(func, *args, **kwargs).T return super().transform(func, *args, **kwargs) - def apply( - self, func, axis=0, raw=False, reduce=None, result_type=None, args=(), **kwds - ): + def apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds): """ Apply a function along an axis of the DataFrame.
Looks like #29017 was supposed to do this and I just missed the reduce keyword
https://api.github.com/repos/pandas-dev/pandas/pulls/29730
2019-11-20T02:33:53Z
2019-11-20T21:05:19Z
2019-11-20T21:05:19Z
2019-11-20T21:13:55Z
DOC: fix _validate_names docstring
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 2cb4a5c8bb2f6..ff3583b79d79c 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -395,25 +395,22 @@ def _validate_integer(name, val, min_val=0): def _validate_names(names): """ - Check if the `names` parameter contains duplicates. - - If duplicates are found, we issue a warning before returning. + Raise ValueError if the `names` parameter contains duplicates. Parameters ---------- names : array-like or None An array containing a list of the names used for the output DataFrame. - Returns - ------- - names : array-like or None - The original `names` parameter. + Raises + ------ + ValueError + If names are not unique. """ if names is not None: if len(names) != len(set(names)): raise ValueError("Duplicate names are not allowed.") - return names def _read(filepath_or_buffer: FilePathOrBuffer, kwds):
https://api.github.com/repos/pandas-dev/pandas/pulls/29729
2019-11-20T02:10:53Z
2019-11-20T17:11:18Z
2019-11-20T17:11:18Z
2019-11-20T17:36:06Z
DEPR: remove nthreads kwarg from read_feather
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index f158c1158b54e..30d9a964b3d7e 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -320,6 +320,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) - Removed the previously deprecated ``reduce`` and ``broadcast`` arguments from :meth:`DataFrame.apply` (:issue:`18577`) - Removed the previously deprecated ``assert_raises_regex`` function in ``pandas.util.testing`` (:issue:`29174`) +- Removed previously deprecated "nthreads" argument from :func:`read_feather`, use "use_threads" instead (:issue:`23053`) - Removed :meth:`Index.is_lexsorted_for_tuple` (:issue:`29305`) - Removed support for nexted renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`29608`) - Removed previously deprecated "order" argument from :func:`factorize` (:issue:`19751`) diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index d9e88f42c2ef2..dffe04fb63720 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -3,7 +3,6 @@ from distutils.version import LooseVersion from pandas.compat._optional import import_optional_dependency -from pandas.util._decorators import deprecate_kwarg from pandas import DataFrame, Int64Index, RangeIndex @@ -66,7 +65,6 @@ def to_feather(df: DataFrame, path): feather.write_feather(df, path) -@deprecate_kwarg(old_arg_name="nthreads", new_arg_name="use_threads") def read_feather(path, columns=None, use_threads=True): """ Load a feather-format object from the file path. @@ -89,11 +87,6 @@ def read_feather(path, columns=None, use_threads=True): If not provided, all columns are read. .. versionadded:: 0.24.0 - nthreads : int, default 1 - Number of CPU threads to use when reading to pandas.DataFrame. - - .. versionadded:: 0.21.0 - .. deprecated:: 0.24.0 use_threads : bool, default True Whether to parallelize reading using multiple threads. diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 0f68a6534dad1..e06f2c31a2870 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -107,23 +107,6 @@ def test_unsupported_other(self): # Some versions raise ValueError, others raise ArrowInvalid. self.check_error_on_write(df, Exception) - def test_rw_nthreads(self): - df = pd.DataFrame({"A": np.arange(100000)}) - expected_warning = ( - "the 'nthreads' keyword is deprecated, use 'use_threads' instead" - ) - # TODO: make the warning work with check_stacklevel=True - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w: - self.check_round_trip(df, nthreads=2) - # we have an extra FutureWarning because of #GH23752 - assert any(expected_warning in str(x) for x in w) - - # TODO: make the warning work with check_stacklevel=True - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w: - self.check_round_trip(df, nthreads=1) - # we have an extra FutureWarnings because of #GH23752 - assert any(expected_warning in str(x) for x in w) - def test_rw_use_threads(self): df = pd.DataFrame({"A": np.arange(100000)}) self.check_round_trip(df, use_threads=True)
https://api.github.com/repos/pandas-dev/pandas/pulls/29728
2019-11-20T01:05:28Z
2019-11-20T17:07:19Z
2019-11-20T17:07:19Z
2019-11-20T17:35:41Z
DEPR: remove tsplot
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index f158c1158b54e..318fe62a73ed2 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -318,6 +318,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) - Changed the default value for the "keep_tz" argument in :meth:`DatetimeIndex.to_series` to ``True`` (:issue:`23739`) - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) +- Removed previously deprecated :func:`pandas.tseries.plotting.tsplot` (:issue:`18627`) - Removed the previously deprecated ``reduce`` and ``broadcast`` arguments from :meth:`DataFrame.apply` (:issue:`18577`) - Removed the previously deprecated ``assert_raises_regex`` function in ``pandas.util.testing`` (:issue:`29174`) - Removed :meth:`Index.is_lexsorted_for_tuple` (:issue:`29305`) diff --git a/pandas/plotting/__init__.py b/pandas/plotting/__init__.py index ebe047c58b889..55c861e384d67 100644 --- a/pandas/plotting/__init__.py +++ b/pandas/plotting/__init__.py @@ -38,7 +38,6 @@ - hist_series and hist_frame (for `Series.hist` and `DataFrame.hist`) - boxplot (`pandas.plotting.boxplot(df)` equivalent to `DataFrame.boxplot`) - boxplot_frame and boxplot_frame_groupby -- tsplot (deprecated) - register and deregister (register converters for the tick formats) - Plots not called as `Series` and `DataFrame` methods: - table diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 6c8bcdada5957..b8f5a0d83b5c1 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -1,5 +1,4 @@ from contextlib import contextmanager -import warnings from pandas.util._decorators import deprecate_kwarg @@ -426,33 +425,6 @@ def autocorrelation_plot(series, ax=None, **kwargs): return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs) -def tsplot(series, plotf, ax=None, **kwargs): - """ - Plots a Series on the given Matplotlib axes or the current axes - - Parameters - ---------- - axes : Axes - series : Series - - Notes - _____ - Supports same kwargs as Axes.plot - - - .. deprecated:: 0.23.0 - Use Series.plot() instead - """ - warnings.warn( - "'tsplot' is deprecated and will be removed in a " - "future version. Please use Series.plot() instead.", - FutureWarning, - stacklevel=2, - ) - plot_backend = _get_plot_backend("matplotlib") - return plot_backend.tsplot(series=series, plotf=plotf, ax=ax, **kwargs) - - class _Options(dict): """ Stores pandas plotting options. diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 973bda8292b2a..f5161b481ca50 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -99,33 +99,12 @@ def test_nonnumeric_exclude(self): with pytest.raises(TypeError, match=msg): df["A"].plot() - def test_tsplot_deprecated(self): - from pandas.tseries.plotting import tsplot - - _, ax = self.plt.subplots() - ts = tm.makeTimeSeries() - - with tm.assert_produces_warning(FutureWarning): - tsplot(ts, self.plt.Axes.plot, ax=ax) - @pytest.mark.slow def test_tsplot(self): - from pandas.tseries.plotting import tsplot - _, ax = self.plt.subplots() ts = tm.makeTimeSeries() - def f(*args, **kwds): - with tm.assert_produces_warning(FutureWarning): - return tsplot(s, self.plt.Axes.plot, *args, **kwds) - - for s in self.period_ser: - _check_plot_works(f, s.index.freq, ax=ax, series=s) - - for s in self.datetime_ser: - _check_plot_works(f, s.index.freq.rule_code, ax=ax, series=s) - for s in self.period_ser: _check_plot_works(s.plot, ax=ax) @@ -194,17 +173,6 @@ def check_format_of_first_point(ax, expected_string): check_format_of_first_point(ax, "t = 2014-01-01 y = 1.000000") tm.close() - # tsplot - from pandas.tseries.plotting import tsplot - - _, ax = self.plt.subplots() - with tm.assert_produces_warning(FutureWarning): - tsplot(annual, self.plt.Axes.plot, ax=ax) - check_format_of_first_point(ax, "t = 2014 y = 1.000000") - with tm.assert_produces_warning(FutureWarning): - tsplot(daily, self.plt.Axes.plot, ax=ax) - check_format_of_first_point(ax, "t = 2014-01-01 y = 1.000000") - @pytest.mark.slow def test_line_plot_period_series(self): for s in self.period_ser: @@ -892,16 +860,6 @@ def test_to_weekly_resampling(self): for l in ax.get_lines(): assert PeriodIndex(data=l.get_xdata()).freq == idxh.freq - _, ax = self.plt.subplots() - from pandas.tseries.plotting import tsplot - - with tm.assert_produces_warning(FutureWarning): - tsplot(high, self.plt.Axes.plot, ax=ax) - with tm.assert_produces_warning(FutureWarning): - lines = tsplot(low, self.plt.Axes.plot, ax=ax) - for l in lines: - assert PeriodIndex(data=l.get_xdata()).freq == idxh.freq - @pytest.mark.slow def test_from_weekly_resampling(self): idxh = date_range("1/1/1999", periods=52, freq="W") @@ -926,21 +884,6 @@ def test_from_weekly_resampling(self): tm.assert_numpy_array_equal(xdata, expected_h) tm.close() - _, ax = self.plt.subplots() - from pandas.tseries.plotting import tsplot - - with tm.assert_produces_warning(FutureWarning): - tsplot(low, self.plt.Axes.plot, ax=ax) - with tm.assert_produces_warning(FutureWarning): - lines = tsplot(high, self.plt.Axes.plot, ax=ax) - for l in lines: - assert PeriodIndex(data=l.get_xdata()).freq == idxh.freq - xdata = l.get_xdata(orig=False) - if len(xdata) == 12: # idxl lines - tm.assert_numpy_array_equal(xdata, expected_l) - else: - tm.assert_numpy_array_equal(xdata, expected_h) - @pytest.mark.slow def test_from_resampling_area_line_mixed(self): idxh = date_range("1/1/1999", periods=52, freq="W") diff --git a/pandas/tseries/plotting.py b/pandas/tseries/plotting.py deleted file mode 100644 index df41b4b5b40d9..0000000000000 --- a/pandas/tseries/plotting.py +++ /dev/null @@ -1,3 +0,0 @@ -# flake8: noqa - -from pandas.plotting._matplotlib.timeseries import tsplot
https://api.github.com/repos/pandas-dev/pandas/pulls/29726
2019-11-19T23:20:10Z
2019-11-20T16:33:48Z
2019-11-20T16:33:48Z
2019-11-20T16:34:59Z
DEPR: remove Index fastpath kwarg
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index f231c2b31abb1..89b85c376f5b4 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -377,6 +377,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. **Other removals** - Removed the previously deprecated :meth:`Index.summary` (:issue:`18217`) +- Removed the previously deprecated "fastpath" keyword from the :class:`Index` constructor (:issue:`23110`) - Removed the previously deprecated :meth:`Series.get_value`, :meth:`Series.set_value`, :meth:`DataFrame.get_value`, :meth:`DataFrame.set_value` (:issue:`17739`) - Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to False (:issue:`27600`) - Removed support for nested renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`18529`) diff --git a/pandas/conftest.py b/pandas/conftest.py index b032e14d8f7e1..122d6e94d9c1a 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -854,3 +854,16 @@ def float_frame(): [30 rows x 4 columns] """ return DataFrame(tm.getSeriesData()) + + +@pytest.fixture(params=[pd.Index, pd.Series], ids=["index", "series"]) +def index_or_series(request): + """ + Fixture to parametrize over Index and Series, made necessary by a mypy + bug, giving an error: + + List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]" + + See GH#????? + """ + return request.param diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index dd38bd0ee5f70..d082d42ae7977 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -259,14 +259,7 @@ def _outer_indexer(self, left, right): # Constructors def __new__( - cls, - data=None, - dtype=None, - copy=False, - name=None, - fastpath=None, - tupleize_cols=True, - **kwargs, + cls, data=None, dtype=None, copy=False, name=None, tupleize_cols=True, **kwargs, ) -> "Index": from .range import RangeIndex @@ -278,16 +271,6 @@ def __new__( if name is None and hasattr(data, "name"): name = data.name - if fastpath is not None: - warnings.warn( - "The 'fastpath' keyword is deprecated, and will be " - "removed in a future version.", - FutureWarning, - stacklevel=2, - ) - if fastpath: - return cls._simple_new(data, name) - if isinstance(data, ABCPandasArray): # ensure users don't accidentally put a PandasArray in an index. data = data.to_numpy() diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e0ffc726bc3a1..d061f61effff3 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -1,6 +1,5 @@ import operator from typing import Any -import warnings import numpy as np @@ -172,19 +171,8 @@ def __new__( dtype=None, copy=False, name=None, - fastpath=None, ): - if fastpath is not None: - warnings.warn( - "The 'fastpath' keyword is deprecated, and will be " - "removed in a future version.", - FutureWarning, - stacklevel=2, - ) - if fastpath: - return cls._simple_new(data, name=name, dtype=dtype) - dtype = CategoricalDtype._from_values_or_dtype(data, categories, ordered, dtype) if name is None and hasattr(data, "name"): diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 29f56259dac79..b30d8c732fbef 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,5 +1,3 @@ -import warnings - import numpy as np from pandas._libs import index as libindex @@ -47,17 +45,8 @@ class NumericIndex(Index): _is_numeric_dtype = True - def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None): + def __new__(cls, data=None, dtype=None, copy=False, name=None): cls._validate_dtype(dtype) - if fastpath is not None: - warnings.warn( - "The 'fastpath' keyword is deprecated, and will be " - "removed in a future version.", - FutureWarning, - stacklevel=2, - ) - if fastpath: - return cls._simple_new(data, name=name) # Coerce to ndarray if not already ndarray or Index if not isinstance(data, (np.ndarray, Index)): diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index e68b340130b9b..f7bbbee461e8d 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -81,26 +81,9 @@ class RangeIndex(Int64Index): # Constructors def __new__( - cls, - start=None, - stop=None, - step=None, - dtype=None, - copy=False, - name=None, - fastpath=None, + cls, start=None, stop=None, step=None, dtype=None, copy=False, name=None, ): - if fastpath is not None: - warnings.warn( - "The 'fastpath' keyword is deprecated, and will be " - "removed in a future version.", - FutureWarning, - stacklevel=2, - ) - if fastpath: - return cls._simple_new(range(start, stop, step), name=name) - cls._validate_dtype(dtype) # RangeIndex diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 584e22f8488f5..77713deada44a 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -5,6 +5,7 @@ from decimal import Decimal from itertools import combinations import operator +from typing import Any, List import numpy as np import pytest @@ -30,6 +31,19 @@ def adjust_negative_zero(zero, expected): return expected +# TODO: remove this kludge once mypy stops giving false positives here +# List comprehension has incompatible type List[PandasObject]; expected List[RangeIndex] +# See GH#????? +ser_or_index: List[Any] = [pd.Series, pd.Index] +lefts: List[Any] = [pd.RangeIndex(10, 40, 10)] +lefts.extend( + [ + cls([10, 20, 30], dtype=dtype) + for dtype in ["i1", "i2", "i4", "i8", "u1", "u2", "u4", "u8", "f2", "f4", "f8"] + for cls in ser_or_index + ] +) + # ------------------------------------------------------------------ # Comparisons @@ -81,26 +95,7 @@ class TestNumericArraylikeArithmeticWithDatetimeLike: # TODO: also check name retentention @pytest.mark.parametrize("box_cls", [np.array, pd.Index, pd.Series]) @pytest.mark.parametrize( - "left", - [pd.RangeIndex(10, 40, 10)] - + [ - cls([10, 20, 30], dtype=dtype) - for dtype in [ - "i1", - "i2", - "i4", - "i8", - "u1", - "u2", - "u4", - "u8", - "f2", - "f4", - "f8", - ] - for cls in [pd.Series, pd.Index] - ], - ids=lambda x: type(x).__name__ + str(x.dtype), + "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype), ) def test_mul_td64arr(self, left, box_cls): # GH#22390 @@ -120,26 +115,7 @@ def test_mul_td64arr(self, left, box_cls): # TODO: also check name retentention @pytest.mark.parametrize("box_cls", [np.array, pd.Index, pd.Series]) @pytest.mark.parametrize( - "left", - [pd.RangeIndex(10, 40, 10)] - + [ - cls([10, 20, 30], dtype=dtype) - for dtype in [ - "i1", - "i2", - "i4", - "i8", - "u1", - "u2", - "u4", - "u8", - "f2", - "f4", - "f8", - ] - for cls in [pd.Series, pd.Index] - ], - ids=lambda x: type(x).__name__ + str(x.dtype), + "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype), ) def test_div_td64arr(self, left, box_cls): # GH#22390 diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index e8d9ecfac61e4..6f443f1841dcc 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -272,8 +272,9 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): return super()._from_sequence(scalars, dtype=dtype, copy=copy) -@pytest.mark.parametrize("box", [pd.Series, pd.Index]) -def test_array_unboxes(box): +def test_array_unboxes(index_or_series): + box = index_or_series + data = box([decimal.Decimal("1"), decimal.Decimal("2")]) # make sure it works with pytest.raises(TypeError): diff --git a/pandas/tests/dtypes/test_concat.py b/pandas/tests/dtypes/test_concat.py index 0ca2f7c976535..02daa185b1cdb 100644 --- a/pandas/tests/dtypes/test_concat.py +++ b/pandas/tests/dtypes/test_concat.py @@ -2,7 +2,7 @@ import pandas.core.dtypes.concat as _concat -from pandas import DatetimeIndex, Index, Period, PeriodIndex, Series, TimedeltaIndex +from pandas import DatetimeIndex, Period, PeriodIndex, Series, TimedeltaIndex @pytest.mark.parametrize( @@ -40,9 +40,8 @@ ), ], ) -@pytest.mark.parametrize("klass", [Index, Series]) -def test_get_dtype_kinds(klass, to_concat, expected): - to_concat_klass = [klass(c) for c in to_concat] +def test_get_dtype_kinds(index_or_series, to_concat, expected): + to_concat_klass = [index_or_series(c) for c in to_concat] result = _concat.get_dtype_kinds(to_concat_klass) assert result == set(expected) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 15844df5d7b04..21c828328e5b8 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2762,32 +2762,18 @@ def test_index_subclass_constructor_wrong_kwargs(index_maker): def test_deprecated_fastpath(): + msg = "[Uu]nexpected keyword argument" + with pytest.raises(TypeError, match=msg): + pd.Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True) - with tm.assert_produces_warning(FutureWarning): - idx = pd.Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True) + with pytest.raises(TypeError, match=msg): + pd.Int64Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True) - expected = pd.Index(["a", "b"], name="test") - tm.assert_index_equal(idx, expected) + with pytest.raises(TypeError, match=msg): + pd.RangeIndex(0, 5, 2, name="test", fastpath=True) - with tm.assert_produces_warning(FutureWarning): - idx = pd.Int64Index( - np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True - ) - - expected = pd.Index([1, 2, 3], name="test", dtype="int64") - tm.assert_index_equal(idx, expected) - - with tm.assert_produces_warning(FutureWarning): - idx = pd.RangeIndex(0, 5, 2, name="test", fastpath=True) - - expected = pd.RangeIndex(0, 5, 2, name="test") - tm.assert_index_equal(idx, expected) - - with tm.assert_produces_warning(FutureWarning): - idx = pd.CategoricalIndex(["a", "b", "c"], name="test", fastpath=True) - - expected = pd.CategoricalIndex(["a", "b", "c"], name="test") - tm.assert_index_equal(idx, expected) + with pytest.raises(TypeError, match=msg): + pd.CategoricalIndex(["a", "b", "c"], name="test", fastpath=True) def test_shape_of_invalid_index(): diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 8b29cf3813d13..e3ad3f733a302 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -513,12 +513,12 @@ def _assert_where_conversion( res = target.where(cond, values) self._assert(res, expected, expected_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index], ids=["series", "index"]) @pytest.mark.parametrize( "fill_val,exp_dtype", [(1, np.object), (1.1, np.object), (1 + 1j, np.object), (True, np.object)], ) - def test_where_object(self, klass, fill_val, exp_dtype): + def test_where_object(self, index_or_series, fill_val, exp_dtype): + klass = index_or_series obj = klass(list("abcd")) assert obj.dtype == np.object cond = klass([True, False, True, False]) @@ -539,12 +539,12 @@ def test_where_object(self, klass, fill_val, exp_dtype): exp = klass(["a", values[1], "c", values[3]]) self._assert_where_conversion(obj, cond, values, exp, exp_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index], ids=["series", "index"]) @pytest.mark.parametrize( "fill_val,exp_dtype", [(1, np.int64), (1.1, np.float64), (1 + 1j, np.complex128), (True, np.object)], ) - def test_where_int64(self, klass, fill_val, exp_dtype): + def test_where_int64(self, index_or_series, fill_val, exp_dtype): + klass = index_or_series if klass is pd.Index and exp_dtype is np.complex128: pytest.skip("Complex Index not supported") obj = klass([1, 2, 3, 4]) @@ -561,7 +561,6 @@ def test_where_int64(self, klass, fill_val, exp_dtype): exp = klass([1, values[1], 3, values[3]]) self._assert_where_conversion(obj, cond, values, exp, exp_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index], ids=["series", "index"]) @pytest.mark.parametrize( "fill_val, exp_dtype", [ @@ -571,7 +570,8 @@ def test_where_int64(self, klass, fill_val, exp_dtype): (True, np.object), ], ) - def test_where_float64(self, klass, fill_val, exp_dtype): + def test_where_float64(self, index_or_series, fill_val, exp_dtype): + klass = index_or_series if klass is pd.Index and exp_dtype is np.complex128: pytest.skip("Complex Index not supported") obj = klass([1.1, 2.2, 3.3, 4.4]) @@ -781,19 +781,18 @@ def _assert_fillna_conversion(self, original, value, expected, expected_dtype): res = target.fillna(value) self._assert(res, expected, expected_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index], ids=["series", "index"]) @pytest.mark.parametrize( "fill_val, fill_dtype", [(1, np.object), (1.1, np.object), (1 + 1j, np.object), (True, np.object)], ) - def test_fillna_object(self, klass, fill_val, fill_dtype): + def test_fillna_object(self, index_or_series, fill_val, fill_dtype): + klass = index_or_series obj = klass(["a", np.nan, "c", "d"]) assert obj.dtype == np.object exp = klass(["a", fill_val, "c", "d"]) self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index], ids=["series", "index"]) @pytest.mark.parametrize( "fill_val,fill_dtype", [ @@ -803,7 +802,8 @@ def test_fillna_object(self, klass, fill_val, fill_dtype): (True, np.object), ], ) - def test_fillna_float64(self, klass, fill_val, fill_dtype): + def test_fillna_float64(self, index_or_series, fill_val, fill_dtype): + klass = index_or_series obj = klass([1.1, np.nan, 3.3, 4.4]) assert obj.dtype == np.float64 @@ -831,7 +831,6 @@ def test_fillna_series_complex128(self, fill_val, fill_dtype): exp = pd.Series([1 + 1j, fill_val, 3 + 3j, 4 + 4j]) self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index], ids=["series", "index"]) @pytest.mark.parametrize( "fill_val,fill_dtype", [ @@ -842,7 +841,8 @@ def test_fillna_series_complex128(self, fill_val, fill_dtype): ], ids=["datetime64", "datetime64tz", "object", "object"], ) - def test_fillna_datetime(self, klass, fill_val, fill_dtype): + def test_fillna_datetime(self, index_or_series, fill_val, fill_dtype): + klass = index_or_series obj = klass( [ pd.Timestamp("2011-01-01"), @@ -863,7 +863,6 @@ def test_fillna_datetime(self, klass, fill_val, fill_dtype): ) self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) - @pytest.mark.parametrize("klass", [pd.Series, pd.Index]) @pytest.mark.parametrize( "fill_val,fill_dtype", [ @@ -874,7 +873,8 @@ def test_fillna_datetime(self, klass, fill_val, fill_dtype): ("x", np.object), ], ) - def test_fillna_datetime64tz(self, klass, fill_val, fill_dtype): + def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype): + klass = index_or_series tz = "US/Eastern" obj = klass( diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index ef9b0bdf053e9..49f666344dfa2 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -421,15 +421,15 @@ def test_date_format_raises(self): self.df.to_json(orient="table", date_format="iso") self.df.to_json(orient="table") - @pytest.mark.parametrize("kind", [pd.Series, pd.Index]) - def test_convert_pandas_type_to_json_field_int(self, kind): + def test_convert_pandas_type_to_json_field_int(self, index_or_series): + kind = index_or_series data = [1, 2, 3] result = convert_pandas_type_to_json_field(kind(data, name="name")) expected = {"name": "name", "type": "integer"} assert result == expected - @pytest.mark.parametrize("kind", [pd.Series, pd.Index]) - def test_convert_pandas_type_to_json_field_float(self, kind): + def test_convert_pandas_type_to_json_field_float(self, index_or_series): + kind = index_or_series data = [1.0, 2.0, 3.0] result = convert_pandas_type_to_json_field(kind(data, name="name")) expected = {"name": "name", "type": "number"} diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 58093ba4d90a5..f24bb9e72aef5 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -516,8 +516,8 @@ def test_value_counts_unique_nunique_null(self, null_obj): assert o.nunique() == 8 assert o.nunique(dropna=False) == 9 - @pytest.mark.parametrize("klass", [Index, Series]) - def test_value_counts_inferred(self, klass): + def test_value_counts_inferred(self, index_or_series): + klass = index_or_series s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"] s = klass(s_values) expected = Series([4, 3, 2, 1], index=["b", "a", "d", "c"]) @@ -547,8 +547,8 @@ def test_value_counts_inferred(self, klass): expected = Series([0.4, 0.3, 0.2, 0.1], index=["b", "a", "d", "c"]) tm.assert_series_equal(hist, expected) - @pytest.mark.parametrize("klass", [Index, Series]) - def test_value_counts_bins(self, klass): + def test_value_counts_bins(self, index_or_series): + klass = index_or_series s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"] s = klass(s_values) @@ -612,8 +612,8 @@ def test_value_counts_bins(self, klass): assert s.nunique() == 0 - @pytest.mark.parametrize("klass", [Index, Series]) - def test_value_counts_datetime64(self, klass): + def test_value_counts_datetime64(self, index_or_series): + klass = index_or_series # GH 3002, datetime64[ns] # don't test names though @@ -1090,13 +1090,13 @@ class TestToIterable: ], ids=["tolist", "to_list", "list", "iter"], ) - @pytest.mark.parametrize("typ", [Series, Index]) @pytest.mark.filterwarnings("ignore:\\n Passing:FutureWarning") # TODO(GH-24559): Remove the filterwarnings - def test_iterable(self, typ, method, dtype, rdtype): + def test_iterable(self, index_or_series, method, dtype, rdtype): # gh-10904 # gh-13258 # coerce iteration to underlying python / pandas types + typ = index_or_series s = typ([1], dtype=dtype) result = method(s)[0] assert isinstance(result, rdtype) @@ -1120,11 +1120,13 @@ def test_iterable(self, typ, method, dtype, rdtype): ], ids=["tolist", "to_list", "list", "iter"], ) - @pytest.mark.parametrize("typ", [Series, Index]) - def test_iterable_object_and_category(self, typ, method, dtype, rdtype, obj): + def test_iterable_object_and_category( + self, index_or_series, method, dtype, rdtype, obj + ): # gh-10904 # gh-13258 # coerce iteration to underlying python / pandas types + typ = index_or_series s = typ([obj], dtype=dtype) result = method(s)[0] assert isinstance(result, rdtype) @@ -1144,12 +1146,12 @@ def test_iterable_items(self, dtype, rdtype): @pytest.mark.parametrize( "dtype, rdtype", dtypes + [("object", int), ("category", int)] ) - @pytest.mark.parametrize("typ", [Series, Index]) @pytest.mark.filterwarnings("ignore:\\n Passing:FutureWarning") # TODO(GH-24559): Remove the filterwarnings - def test_iterable_map(self, typ, dtype, rdtype): + def test_iterable_map(self, index_or_series, dtype, rdtype): # gh-13236 # coerce iteration to underlying python / pandas types + typ = index_or_series s = typ([1], dtype=dtype) result = s.map(type)[0] if not isinstance(rdtype, tuple): @@ -1332,8 +1334,8 @@ def test_numpy_array_all_dtypes(any_numpy_dtype): ), ], ) -@pytest.mark.parametrize("box", [pd.Series, pd.Index]) -def test_array(array, attr, box): +def test_array(array, attr, index_or_series): + box = index_or_series if array.dtype.name in ("Int64", "Sparse[int64, 0]") and box is pd.Index: pytest.skip("No index type for {}".format(array.dtype)) result = box(array, copy=False).array @@ -1396,8 +1398,8 @@ def test_array_multiindex_raises(): ), ], ) -@pytest.mark.parametrize("box", [pd.Series, pd.Index]) -def test_to_numpy(array, expected, box): +def test_to_numpy(array, expected, index_or_series): + box = index_or_series thing = box(array) if array.dtype.name in ("Int64", "Sparse[int64, 0]") and box is pd.Index: diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 1261c3bbc86db..c00e792fb210f 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -202,9 +202,9 @@ def test_api_mi_raises(self): assert not hasattr(mi, "str") @pytest.mark.parametrize("dtype", [object, "category"]) - @pytest.mark.parametrize("box", [Series, Index]) - def test_api_per_dtype(self, box, dtype, any_skipna_inferred_dtype): + def test_api_per_dtype(self, index_or_series, dtype, any_skipna_inferred_dtype): # one instance of parametrized fixture + box = index_or_series inferred_dtype, values = any_skipna_inferred_dtype t = box(values, dtype=dtype) # explicit dtype to avoid casting @@ -236,13 +236,17 @@ def test_api_per_dtype(self, box, dtype, any_skipna_inferred_dtype): assert not hasattr(t, "str") @pytest.mark.parametrize("dtype", [object, "category"]) - @pytest.mark.parametrize("box", [Series, Index]) def test_api_per_method( - self, box, dtype, any_allowed_skipna_inferred_dtype, any_string_method + self, + index_or_series, + dtype, + any_allowed_skipna_inferred_dtype, + any_string_method, ): # this test does not check correctness of the different methods, # just that the methods work on the specified (inferred) dtypes, # and raise on all others + box = index_or_series # one instance of each parametrized fixture inferred_dtype, values = any_allowed_skipna_inferred_dtype @@ -375,10 +379,10 @@ def test_iter_object_try_string(self): assert i == 100 assert s == "h" - @pytest.mark.parametrize("box", [Series, Index]) @pytest.mark.parametrize("other", [None, Series, Index]) - def test_str_cat_name(self, box, other): + def test_str_cat_name(self, index_or_series, other): # GH 21053 + box = index_or_series values = ["a", "b"] if other: other = other(values) @@ -387,8 +391,8 @@ def test_str_cat_name(self, box, other): result = box(values, name="name").str.cat(other, sep=",") assert result.name == "name" - @pytest.mark.parametrize("box", [Series, Index]) - def test_str_cat(self, box): + def test_str_cat(self, index_or_series): + box = index_or_series # test_cat above tests "str_cat" from ndarray; # here testing "str.cat" from Series/Indext to ndarray/list s = box(["a", "a", "b", "b", "c", np.nan]) @@ -427,9 +431,9 @@ def test_str_cat(self, box): with pytest.raises(ValueError, match=rgx): s.str.cat(list(z)) - @pytest.mark.parametrize("box", [Series, Index]) - def test_str_cat_raises_intuitive_error(self, box): + def test_str_cat_raises_intuitive_error(self, index_or_series): # GH 11334 + box = index_or_series s = box(["a", "b", "c", "d"]) message = "Did you mean to supply a `sep` keyword?" with pytest.raises(ValueError, match=message): @@ -440,8 +444,11 @@ def test_str_cat_raises_intuitive_error(self, box): @pytest.mark.parametrize("sep", ["", None]) @pytest.mark.parametrize("dtype_target", ["object", "category"]) @pytest.mark.parametrize("dtype_caller", ["object", "category"]) - @pytest.mark.parametrize("box", [Series, Index]) - def test_str_cat_categorical(self, box, dtype_caller, dtype_target, sep): + def test_str_cat_categorical( + self, index_or_series, dtype_caller, dtype_target, sep + ): + box = index_or_series + s = Index(["a", "a", "b", "a"], dtype=dtype_caller) s = s if box == Index else Series(s, index=s) t = Index(["b", "a", "b", "c"], dtype=dtype_target) @@ -494,8 +501,8 @@ def test_str_cat_wrong_dtype_raises(self, box, data): # need to use outer and na_rep, as otherwise Index would not raise s.str.cat(t, join="outer", na_rep="-") - @pytest.mark.parametrize("box", [Series, Index]) - def test_str_cat_mixed_inputs(self, box): + def test_str_cat_mixed_inputs(self, index_or_series): + box = index_or_series s = Index(["a", "b", "c", "d"]) s = s if box == Index else Series(s, index=s) @@ -596,9 +603,10 @@ def test_str_cat_mixed_inputs(self, box): s.str.cat(iter([t.values, list(s)])) @pytest.mark.parametrize("join", ["left", "outer", "inner", "right"]) - @pytest.mark.parametrize("box", [Series, Index]) - def test_str_cat_align_indexed(self, box, join): + def test_str_cat_align_indexed(self, index_or_series, join): # https://github.com/pandas-dev/pandas/issues/18657 + box = index_or_series + s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"]) t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"]) sa, ta = s.align(t, join=join) @@ -656,10 +664,14 @@ def test_str_cat_align_mixed_inputs(self, join): with pytest.raises(ValueError, match=rgx): s.str.cat([t, z], join=join) - @pytest.mark.parametrize("box", [Series, Index]) - @pytest.mark.parametrize("other", [Series, Index]) - def test_str_cat_all_na(self, box, other): + index_or_series2 = [Series, Index] # type: ignore + # List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]" + # See GH#>???? + + @pytest.mark.parametrize("other", index_or_series2) + def test_str_cat_all_na(self, index_or_series, other): # GH 24044 + box = index_or_series # check that all NaNs in caller / target work s = Index(["a", "b", "c", "d"])
https://api.github.com/repos/pandas-dev/pandas/pulls/29725
2019-11-19T23:17:20Z
2019-11-27T04:49:13Z
2019-11-27T04:49:13Z
2020-04-29T02:55:05Z
DEPR: remove Series.valid, is_copy, get_ftype_counts, Index.get_duplicate, Series.clip_upper, clip_lower
diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index 37d27093efefd..4540504974f56 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -30,7 +30,6 @@ Attributes and underlying data DataFrame.dtypes DataFrame.ftypes DataFrame.get_dtype_counts - DataFrame.get_ftype_counts DataFrame.select_dtypes DataFrame.values DataFrame.get_values @@ -40,7 +39,6 @@ Attributes and underlying data DataFrame.shape DataFrame.memory_usage DataFrame.empty - DataFrame.is_copy Conversion ~~~~~~~~~~ @@ -142,8 +140,6 @@ Computations / descriptive stats DataFrame.all DataFrame.any DataFrame.clip - DataFrame.clip_lower - DataFrame.clip_upper DataFrame.compound DataFrame.corr DataFrame.corrwith diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 59910ba357130..c501e8bc91379 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -45,7 +45,6 @@ Attributes Series.dtypes Series.ftypes Series.data - Series.is_copy Series.name Series.put @@ -148,8 +147,6 @@ Computations / descriptive stats Series.autocorr Series.between Series.clip - Series.clip_lower - Series.clip_upper Series.corr Series.count Series.cov diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3b87150f544cf..753654efd9416 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -332,6 +332,11 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed previously deprecated "nthreads" argument from :func:`read_feather`, use "use_threads" instead (:issue:`23053`) - Removed :meth:`Index.is_lexsorted_for_tuple` (:issue:`29305`) - Removed support for nexted renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`29608`) +- Removed the previously deprecated :meth:`Series.valid`; use :meth:`Series.dropna` instead (:issue:`18800`) +- Removed the previously properties :attr:`DataFrame.is_copy`, :attr:`Series.is_copy` (:issue:`18812`) +- Removed the previously deprecated :meth:`DataFrame.get_ftype_counts`, :meth:`Series.get_ftype_counts` (:issue:`18243`) +- Removed the previously deprecated :meth:`Index.get_duplicated`, use ``idx[idx.duplicated()].unique()`` instead (:issue:`20239`) +- Removed the previously deprecated :meth:`Series.clip_upper`, :meth:`Series.clip_lower`, :meth:`DataFrame.clip_upper`, :meth:`DataFrame.clip_lower` (:issue:`24203`) - Removed previously deprecated "order" argument from :func:`factorize` (:issue:`19751`) - Removed previously deprecated "v" argument from :meth:`FrozenNDarray.searchsorted`, use "value" instead (:issue:`22672`) - :func:`read_stata` and :meth:`DataFrame.to_stata` no longer supports the "encoding" argument (:issue:`21400`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6fbe95fa973cb..7f83bb9e69f7a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -172,16 +172,7 @@ class NDFrame(PandasObject, SelectionMixin): _internal_names_set = set(_internal_names) # type: Set[str] _accessors = set() # type: Set[str] _deprecations = frozenset( - [ - "clip_lower", - "clip_upper", - "get_dtype_counts", - "get_ftype_counts", - "get_values", - "is_copy", - "ftypes", - "ix", - ] + ["get_dtype_counts", "get_values", "ftypes", "ix"] ) # type: FrozenSet[str] _metadata = [] # type: List[str] _is_copy = None @@ -252,29 +243,6 @@ def attrs(self) -> Dict[Optional[Hashable], Any]: def attrs(self, value: Mapping[Optional[Hashable], Any]) -> None: self._attrs = dict(value) - @property - def is_copy(self): - """ - Return the copy. - """ - warnings.warn( - "Attribute 'is_copy' is deprecated and will be removed " - "in a future version.", - FutureWarning, - stacklevel=2, - ) - return self._is_copy - - @is_copy.setter - def is_copy(self, msg): - warnings.warn( - "Attribute 'is_copy' is deprecated and will be removed " - "in a future version.", - FutureWarning, - stacklevel=2, - ) - self._is_copy = msg - def _validate_dtype(self, dtype): """ validate the passed dtype """ @@ -5595,49 +5563,6 @@ def get_dtype_counts(self): return Series(self._data.get_dtype_counts()) - def get_ftype_counts(self): - """ - Return counts of unique ftypes in this object. - - .. deprecated:: 0.23.0 - - Returns - ------- - dtype : Series - Series with the count of columns with each type and - sparsity (dense/sparse). - - See Also - -------- - ftypes : Return ftypes (indication of sparse/dense and dtype) in - this object. - - Examples - -------- - >>> a = [['a', 1, 1.0], ['b', 2, 2.0], ['c', 3, 3.0]] - >>> df = pd.DataFrame(a, columns=['str', 'int', 'float']) - >>> df - str int float - 0 a 1 1.0 - 1 b 2 2.0 - 2 c 3 3.0 - - >>> df.get_ftype_counts() # doctest: +SKIP - float64:dense 1 - int64:dense 1 - object:dense 1 - dtype: int64 - """ - warnings.warn( - "get_ftype_counts is deprecated and will be removed in a future version", - FutureWarning, - stacklevel=2, - ) - - from pandas import Series - - return Series(self._data.get_ftype_counts()) - @property def dtypes(self): """ @@ -7526,208 +7451,6 @@ def clip(self, lower=None, upper=None, axis=None, inplace=False, *args, **kwargs return result - def clip_upper(self, threshold, axis=None, inplace=False): - """ - Trim values above a given threshold. - - .. deprecated:: 0.24.0 - Use clip(upper=threshold) instead. - - Elements above the `threshold` will be changed to match the - `threshold` value(s). Threshold can be a single value or an array, - in the latter case it performs the truncation element-wise. - - Parameters - ---------- - threshold : numeric or array-like - Maximum value allowed. All values above threshold will be set to - this value. - - * float : every value is compared to `threshold`. - * array-like : The shape of `threshold` should match the object - it's compared to. When `self` is a Series, `threshold` should be - the length. When `self` is a DataFrame, `threshold` should 2-D - and the same shape as `self` for ``axis=None``, or 1-D and the - same length as the axis being compared. - - axis : {0 or 'index', 1 or 'columns'}, default 0 - Align object with `threshold` along the given axis. - inplace : bool, default False - Whether to perform the operation in place on the data. - - .. versionadded:: 0.21.0 - - Returns - ------- - Series or DataFrame - Original data with values trimmed. - - See Also - -------- - Series.clip : General purpose method to trim Series values to given - threshold(s). - DataFrame.clip : General purpose method to trim DataFrame values to - given threshold(s). - - Examples - -------- - >>> s = pd.Series([1, 2, 3, 4, 5]) - >>> s - 0 1 - 1 2 - 2 3 - 3 4 - 4 5 - dtype: int64 - - >>> s.clip(upper=3) - 0 1 - 1 2 - 2 3 - 3 3 - 4 3 - dtype: int64 - - >>> elemwise_thresholds = [5, 4, 3, 2, 1] - >>> elemwise_thresholds - [5, 4, 3, 2, 1] - - >>> s.clip(upper=elemwise_thresholds) - 0 1 - 1 2 - 2 3 - 3 2 - 4 1 - dtype: int64 - """ - warnings.warn( - "clip_upper(threshold) is deprecated, use clip(upper=threshold) instead", - FutureWarning, - stacklevel=2, - ) - return self._clip_with_one_bound( - threshold, method=self.le, axis=axis, inplace=inplace - ) - - def clip_lower(self, threshold, axis=None, inplace=False): - """ - Trim values below a given threshold. - - .. deprecated:: 0.24.0 - Use clip(lower=threshold) instead. - - Elements below the `threshold` will be changed to match the - `threshold` value(s). Threshold can be a single value or an array, - in the latter case it performs the truncation element-wise. - - Parameters - ---------- - threshold : numeric or array-like - Minimum value allowed. All values below threshold will be set to - this value. - - * float : every value is compared to `threshold`. - * array-like : The shape of `threshold` should match the object - it's compared to. When `self` is a Series, `threshold` should be - the length. When `self` is a DataFrame, `threshold` should 2-D - and the same shape as `self` for ``axis=None``, or 1-D and the - same length as the axis being compared. - - axis : {0 or 'index', 1 or 'columns'}, default 0 - Align `self` with `threshold` along the given axis. - - inplace : bool, default False - Whether to perform the operation in place on the data. - - .. versionadded:: 0.21.0 - - Returns - ------- - Series or DataFrame - Original data with values trimmed. - - See Also - -------- - Series.clip : General purpose method to trim Series values to given - threshold(s). - DataFrame.clip : General purpose method to trim DataFrame values to - given threshold(s). - - Examples - -------- - - Series single threshold clipping: - - >>> s = pd.Series([5, 6, 7, 8, 9]) - >>> s.clip(lower=8) - 0 8 - 1 8 - 2 8 - 3 8 - 4 9 - dtype: int64 - - Series clipping element-wise using an array of thresholds. `threshold` - should be the same length as the Series. - - >>> elemwise_thresholds = [4, 8, 7, 2, 5] - >>> s.clip(lower=elemwise_thresholds) - 0 5 - 1 8 - 2 7 - 3 8 - 4 9 - dtype: int64 - - DataFrames can be compared to a scalar. - - >>> df = pd.DataFrame({"A": [1, 3, 5], "B": [2, 4, 6]}) - >>> df - A B - 0 1 2 - 1 3 4 - 2 5 6 - - >>> df.clip(lower=3) - A B - 0 3 3 - 1 3 4 - 2 5 6 - - Or to an array of values. By default, `threshold` should be the same - shape as the DataFrame. - - >>> df.clip(lower=np.array([[3, 4], [2, 2], [6, 2]])) - A B - 0 3 4 - 1 3 4 - 2 6 6 - - Control how `threshold` is broadcast with `axis`. In this case - `threshold` should be the same length as the axis specified by - `axis`. - - >>> df.clip(lower=[3, 3, 5], axis='index') - A B - 0 3 3 - 1 3 4 - 2 5 6 - - >>> df.clip(lower=[4, 5], axis='columns') - A B - 0 4 5 - 1 4 5 - 2 5 6 - """ - warnings.warn( - "clip_lower(threshold) is deprecated, use clip(lower=threshold) instead", - FutureWarning, - stacklevel=2, - ) - return self._clip_with_one_bound( - threshold, method=self.ge, axis=axis, inplace=inplace - ) - def groupby( self, by=None, diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index c36dd9463c61d..d53fbe2e60e9a 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -79,7 +79,6 @@ class BlockManager(PandasObject): copy(deep=True) get_dtype_counts - get_ftype_counts get_dtypes get_ftypes @@ -246,9 +245,6 @@ def _get_counts(self, f): def get_dtype_counts(self): return self._get_counts(lambda b: b.dtype.name) - def get_ftype_counts(self): - return self._get_counts(lambda b: b.ftype) - def get_dtypes(self): dtypes = np.array([blk.dtype for blk in self.blocks]) return algos.take_1d(dtypes, self._blknos, allow_fill=False) @@ -1555,9 +1551,6 @@ def ftype(self): def get_dtype_counts(self): return {self.dtype.name: 1} - def get_ftype_counts(self): - return {self.ftype: 1} - def get_dtypes(self): return np.array([self._block.dtype]) diff --git a/pandas/core/series.py b/pandas/core/series.py index c10871d04ef3e..a950b4496baa7 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4615,26 +4615,6 @@ def dropna(self, axis=0, inplace=False, how=None): else: return self.copy() - def valid(self, inplace=False, **kwargs): - """ - Return Series without null values. - - .. deprecated:: 0.23.0 - Use :meth:`Series.dropna` instead. - - Returns - ------- - Series - Series without null values. - """ - warnings.warn( - "Method .valid will be removed in a future version. " - "Use .dropna instead.", - FutureWarning, - stacklevel=2, - ) - return self.dropna(inplace=inplace, **kwargs) - # ---------------------------------------------------------------------- # Time series-oriented methods diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 9cc9c5dc697b6..005ca8d95182e 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -2279,14 +2279,6 @@ def test_clip(self, float_frame): median = float_frame.median().median() original = float_frame.copy() - with tm.assert_produces_warning(FutureWarning): - capped = float_frame.clip_upper(median) - assert not (capped.values > median).any() - - with tm.assert_produces_warning(FutureWarning): - floored = float_frame.clip_lower(median) - assert not (floored.values < median).any() - double = float_frame.clip(upper=median, lower=median) assert not (double.values != median).any() @@ -2298,16 +2290,6 @@ def test_inplace_clip(self, float_frame): median = float_frame.median().median() frame_copy = float_frame.copy() - with tm.assert_produces_warning(FutureWarning): - frame_copy.clip_upper(median, inplace=True) - assert not (frame_copy.values > median).any() - frame_copy = float_frame.copy() - - with tm.assert_produces_warning(FutureWarning): - frame_copy.clip_lower(median, inplace=True) - assert not (frame_copy.values < median).any() - frame_copy = float_frame.copy() - frame_copy.clip(upper=median, lower=median, inplace=True) assert not (frame_copy.values != median).any() @@ -2759,8 +2741,7 @@ def test_series_broadcasting(self): s_nan = Series([np.nan, np.nan, 1]) with tm.assert_produces_warning(None): - with tm.assert_produces_warning(FutureWarning): - df_nan.clip_lower(s, axis=0) + df_nan.clip(lower=s, axis=0) for op in ["lt", "le", "gt", "ge", "eq", "ne"]: getattr(df, op)(s_nan, axis=0) diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index ae452e6faef01..096a5aa99bd80 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -243,11 +243,6 @@ def test_to_xarray(self): assert isinstance(result, DataArray) tm.assert_series_equal(result.to_series(), s) - def test_valid_deprecated(self): - # GH18800 - with tm.assert_produces_warning(FutureWarning): - pd.Series([]).valid() - @pytest.mark.parametrize( "s", [ diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 274b72b0561a9..6e26d407ab0ec 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -393,14 +393,3 @@ def test_cache_updating(self): tm.assert_frame_equal(df, expected) expected = Series([0, 0, 0, 2, 0], name="f") tm.assert_series_equal(df.f, expected) - - def test_deprecate_is_copy(self): - # GH18801 - df = DataFrame({"A": [1, 2, 3]}) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - # getter - df.is_copy - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - # setter - df.is_copy = "test deprecated is_copy" diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 79eaeaf051d2e..e25c4456147f7 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -655,11 +655,6 @@ def test_matmul(self): def test_clip(self, datetime_series): val = datetime_series.median() - with tm.assert_produces_warning(FutureWarning): - assert datetime_series.clip_lower(val).min() == val - with tm.assert_produces_warning(FutureWarning): - assert datetime_series.clip_upper(val).max() == val - assert datetime_series.clip(lower=val).min() == val assert datetime_series.clip(upper=val).max() == val @@ -678,10 +673,8 @@ def test_clip_types_and_nulls(self): for s in sers: thresh = s[2] - with tm.assert_produces_warning(FutureWarning): - lower = s.clip_lower(thresh) - with tm.assert_produces_warning(FutureWarning): - upper = s.clip_upper(thresh) + lower = s.clip(lower=thresh) + upper = s.clip(upper=thresh) assert lower[notna(lower)].min() == thresh assert upper[notna(upper)].max() == thresh assert list(isna(s)) == list(isna(lower)) @@ -703,12 +696,6 @@ def test_clip_against_series(self): # GH #6966 s = Series([1.0, 1.0, 4.0]) - threshold = Series([1.0, 2.0, 3.0]) - - with tm.assert_produces_warning(FutureWarning): - tm.assert_series_equal(s.clip_lower(threshold), Series([1.0, 2.0, 4.0])) - with tm.assert_produces_warning(FutureWarning): - tm.assert_series_equal(s.clip_upper(threshold), Series([1.0, 1.0, 3.0])) lower = Series([1.0, 2.0, 3.0]) upper = Series([1.5, 2.5, 3.5]) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index e1ace952f722d..ec0318b2af13a 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -56,11 +56,6 @@ def test_dtype(self, datetime_series): # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): assert datetime_series.ftypes == "float64:dense" - # GH18243 - Assert .get_ftype_counts is deprecated - with tm.assert_produces_warning(FutureWarning): - tm.assert_series_equal( - datetime_series.get_ftype_counts(), Series(1, ["float64:dense"]) - ) @pytest.mark.parametrize("value", [np.nan, np.inf]) @pytest.mark.parametrize("dtype", [np.int32, np.int64])
…cate, Series.clip_upper, Series.clip_lower
https://api.github.com/repos/pandas-dev/pandas/pulls/29724
2019-11-19T23:15:01Z
2019-11-21T13:29:12Z
2019-11-21T13:29:12Z
2019-11-21T15:50:36Z
DEPR: enforce deprecations in core.internals
diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml index e3ad1d8371623..ec4aff41f1967 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-36.yaml @@ -16,7 +16,7 @@ dependencies: # pandas dependencies - blosc - bottleneck - - fastparquet>=0.2.1 + - fastparquet>=0.3.2 - matplotlib=3.0.2 - numexpr - numpy=1.15.* diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml index 9148e0d4b29d9..81e5f6516fe69 100644 --- a/ci/deps/travis-36-cov.yaml +++ b/ci/deps/travis-36-cov.yaml @@ -18,7 +18,7 @@ dependencies: - botocore>=1.11 - cython>=0.29.13 - dask - - fastparquet>=0.2.1 + - fastparquet>=0.3.2 - gcsfs - geopandas - html5lib diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index 3199ee037bc0a..9058f25c9344d 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -16,7 +16,7 @@ dependencies: - beautifulsoup4 - blosc=1.14.3 - python-blosc - - fastparquet=0.2.1 + - fastparquet=0.3.2 - gcsfs=0.2.2 - html5lib - ipython diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 663948fd46cf6..a9e853c887636 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -250,7 +250,7 @@ SQLAlchemy 1.1.4 SQL support for databases other tha SciPy 0.19.0 Miscellaneous statistical functions XLsxWriter 0.9.8 Excel writing blosc Compression for msgpack -fastparquet 0.2.1 Parquet reading / writing +fastparquet 0.3.2 Parquet reading / writing gcsfs 0.2.2 Google Cloud Storage access html5lib HTML parser for read_html (see :ref:`note <optional_html>`) lxml 3.8.0 HTML parser for read_html (see :ref:`note <optional_html>`) diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..0d8f39755f2d6 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -235,6 +235,71 @@ The following methods now also correctly output values for unobserved categories df.groupby(["cat_1", "cat_2"], observed=False)["value"].count() +.. _whatsnew_1000.api_breaking.deps: + +Increased minimum versions for dependencies +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Some minimum supported versions of dependencies were updated (:issue:`29723`). +If installed, we now require: + ++-----------------+-----------------+----------+ +| Package | Minimum Version | Required | ++=================+=================+==========+ +| numpy | 1.13.3 | X | ++-----------------+-----------------+----------+ +| pytz | 2015.4 | X | ++-----------------+-----------------+----------+ +| python-dateutil | 2.6.1 | X | ++-----------------+-----------------+----------+ +| bottleneck | 1.2.1 | | ++-----------------+-----------------+----------+ +| numexpr | 2.6.2 | | ++-----------------+-----------------+----------+ +| pytest (dev) | 4.0.2 | | ++-----------------+-----------------+----------+ + +For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version. +The following table lists the lowest version per library that is currently being tested throughout the development of pandas. +Optional libraries below the lowest tested version may still work, but are not considered supported. + ++-----------------+-----------------+ +| Package | Minimum Version | ++=================+=================+ +| beautifulsoup4 | 4.6.0 | ++-----------------+-----------------+ +| fastparquet | 0.3.2 | ++-----------------+-----------------+ +| gcsfs | 0.2.2 | ++-----------------+-----------------+ +| lxml | 3.8.0 | ++-----------------+-----------------+ +| matplotlib | 2.2.2 | ++-----------------+-----------------+ +| openpyxl | 2.4.8 | ++-----------------+-----------------+ +| pyarrow | 0.9.0 | ++-----------------+-----------------+ +| pymysql | 0.7.1 | ++-----------------+-----------------+ +| pytables | 3.4.2 | ++-----------------+-----------------+ +| scipy | 0.19.0 | ++-----------------+-----------------+ +| sqlalchemy | 1.1.4 | ++-----------------+-----------------+ +| xarray | 0.8.2 | ++-----------------+-----------------+ +| xlrd | 1.1.0 | ++-----------------+-----------------+ +| xlsxwriter | 0.9.8 | ++-----------------+-----------------+ +| xlwt | 1.2.0 | ++-----------------+-----------------+ + +See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. + + .. _whatsnew_1000.api.other: Other API changes @@ -320,6 +385,8 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed :meth:`DataFrame.as_blocks`, :meth:`Series.as_blocks`, `DataFrame.blocks`, :meth:`Series.blocks` (:issue:`17656`) - :meth:`pandas.Series.str.cat` now defaults to aligning ``others``, using ``join='left'`` (:issue:`27611`) - :meth:`pandas.Series.str.cat` does not accept list-likes *within* list-likes anymore (:issue:`27611`) +- :func:`core.internals.blocks.make_block` no longer accepts the "fastpath" keyword(:issue:`19265`) +- :meth:`Block.make_block_same_class` no longer accepts the "dtype" keyword(:issue:`19434`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) - :func:`read_excel` removed support for "skip_footer" argument, use "skipfooter" instead (:issue:`18836`) - :meth:`DataFrame.to_records` no longer supports the argument "convert_datetime64" (:issue:`18902`) diff --git a/environment.yml b/environment.yml index 54c99f415165d..848825c37a160 100644 --- a/environment.yml +++ b/environment.yml @@ -75,7 +75,7 @@ dependencies: # optional for io - beautifulsoup4>=4.6.0 # pandas.read_html - - fastparquet>=0.2.1 # pandas.read_parquet, DataFrame.to_parquet + - fastparquet>=0.3.2 # pandas.read_parquet, DataFrame.to_parquet - html5lib # pandas.read_html - lxml # pandas.read_html - openpyxl # pandas.read_excel, DataFrame.to_excel, pandas.ExcelWriter, pandas.ExcelFile diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index fc66502710b0c..b0a7f243ca14c 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -8,7 +8,7 @@ VERSIONS = { "bs4": "4.6.0", "bottleneck": "1.2.1", - "fastparquet": "0.2.1", + "fastparquet": "0.3.2", "gcsfs": "0.2.2", "lxml.etree": "3.8.0", "matplotlib": "2.2.2", diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 5edb4d93e068a..2d6ffb7277742 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -251,21 +251,13 @@ def make_block(self, values, placement=None): return make_block(values, placement=placement, ndim=self.ndim) - def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): + def make_block_same_class(self, values, placement=None, ndim=None): """ Wrap given values in a block of same type as self. """ - if dtype is not None: - # issue 19431 fastparquet is passing this - warnings.warn( - "dtype argument is deprecated, will be removed in a future release.", - FutureWarning, - ) if placement is None: placement = self.mgr_locs if ndim is None: ndim = self.ndim - return make_block( - values, placement=placement, ndim=ndim, klass=self.__class__, dtype=dtype - ) + return make_block(values, placement=placement, ndim=ndim, klass=self.__class__) def __repr__(self) -> str: # don't want to print out all of the items here @@ -3001,7 +2993,7 @@ def get_block_type(values, dtype=None): return cls -def make_block(values, placement, klass=None, ndim=None, dtype=None, fastpath=None): +def make_block(values, placement, klass=None, ndim=None, dtype=None): # Ensure that we don't allow PandasArray / PandasDtype in internals. # For now, blocks should be backed by ndarrays when possible. if isinstance(values, ABCPandasArray): @@ -3012,12 +3004,6 @@ def make_block(values, placement, klass=None, ndim=None, dtype=None, fastpath=No if isinstance(dtype, PandasDtype): dtype = dtype.numpy_dtype - if fastpath is not None: - # GH#19265 pyarrow is passing this - warnings.warn( - "fastpath argument is deprecated, will be removed in a future release.", - FutureWarning, - ) if klass is None: dtype = dtype or values.dtype klass = get_block_type(values, dtype) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index c98bdab0df766..abe2ddf955ad8 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -308,12 +308,6 @@ def test_delete(self): with pytest.raises(Exception): newb.delete(3) - def test_make_block_same_class(self): - # issue 19431 - block = create_block("M8[ns, US/Eastern]", [3]) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - block.make_block_same_class(block.values, dtype=block.values.dtype) - class TestDatetimeBlock: def test_can_hold_element(self): @@ -1255,13 +1249,6 @@ def test_holder(typestr, holder): assert blk._holder is holder -def test_deprecated_fastpath(): - # GH#19265 - values = np.random.rand(3, 3) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - make_block(values, placement=np.arange(3), fastpath=True) - - def test_validate_ndim(): values = np.array([1.0, 2.0]) placement = slice(2) diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index bcbbee3b86769..3e687d185df84 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -531,7 +531,7 @@ def test_additional_extension_arrays(self, pa): class TestParquetFastParquet(Base): - @td.skip_if_no("fastparquet", min_version="0.2.1") + @td.skip_if_no("fastparquet", min_version="0.3.2") def test_basic(self, fp, df_full): df = df_full diff --git a/requirements-dev.txt b/requirements-dev.txt index 87b348c39a17b..4d0e7ee904294 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -48,7 +48,7 @@ matplotlib>=2.2.2 numexpr>=2.6.8 scipy>=1.1 beautifulsoup4>=4.6.0 -fastparquet>=0.2.1 +fastparquet>=0.3.2 html5lib lxml openpyxl
Not sure if the whatsnew is needed for this; IIRC it was mainly pyarrow/fastparquet that were using these keywords
https://api.github.com/repos/pandas-dev/pandas/pulls/29723
2019-11-19T22:21:34Z
2019-11-22T17:28:55Z
2019-11-22T17:28:55Z
2019-11-22T17:35:06Z
DEPR: remove encoding kwarg from read_stata, DataFrame.to_stata
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index f158c1158b54e..467aa663f770a 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -324,6 +324,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed support for nexted renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`29608`) - Removed previously deprecated "order" argument from :func:`factorize` (:issue:`19751`) - Removed previously deprecated "v" argument from :meth:`FrozenNDarray.searchsorted`, use "value" instead (:issue:`22672`) +- :func:`read_stata` and :meth:`DataFrame.to_stata` no longer supports the "encoding" argument (:issue:`21400`) - Removed previously deprecated "raise_conflict" argument from :meth:`DataFrame.update`, use "errors" instead (:issue:`23585`) - Removed previously deprecated keyword "n" from :meth:`DatetimeIndex.shift`, :meth:`TimedeltaIndex.shift`, :meth:`PeriodIndex.shift`, use "periods" instead (:issue:`22458`) - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5baba0bae1d45..4335388eb3b9d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -35,12 +35,7 @@ from pandas._libs import algos as libalgos, lib from pandas.compat.numpy import function as nv -from pandas.util._decorators import ( - Appender, - Substitution, - deprecate_kwarg, - rewrite_axis_style_signature, -) +from pandas.util._decorators import Appender, Substitution, rewrite_axis_style_signature from pandas.util._validators import ( validate_axis_style_args, validate_bool_kwarg, @@ -1972,13 +1967,11 @@ def _from_arrays(cls, arrays, columns, index, dtype=None): mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype) return cls(mgr) - @deprecate_kwarg(old_arg_name="encoding", new_arg_name=None) def to_stata( self, fname, convert_dates=None, write_index=True, - encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, @@ -2008,8 +2001,6 @@ def to_stata( 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. byteorder : str Can be ">", "<", "little", or "big". default is `sys.byteorder`. time_stamp : datetime diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 24539057a5db9..567eeb7f5cdc8 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -58,10 +58,6 @@ convert_categoricals : bool, default True Read value labels and convert columns to Categorical/Factor variables.""" -_encoding_params = """\ -encoding : str, None or encoding - Encoding used to parse the files. None defaults to latin-1.""" - _statafile_processing_params2 = """\ index_col : str, optional Column to set as index. @@ -108,7 +104,6 @@ %s %s %s -%s Returns ------- @@ -132,7 +127,6 @@ ... do_something(chunk) """ % ( _statafile_processing_params1, - _encoding_params, _statafile_processing_params2, _chunksize_params, _iterator_params, @@ -189,23 +183,19 @@ %s %s %s -%s """ % ( _statafile_processing_params1, _statafile_processing_params2, - _encoding_params, _chunksize_params, ) @Appender(_read_stata_doc) -@deprecate_kwarg(old_arg_name="encoding", new_arg_name=None) @deprecate_kwarg(old_arg_name="index", new_arg_name="index_col") def read_stata( filepath_or_buffer, convert_dates=True, convert_categoricals=True, - encoding=None, index_col=None, convert_missing=False, preserve_dtypes=True, @@ -1044,7 +1034,6 @@ def __init__(self): class StataReader(StataParser, BaseIterator): __doc__ = _stata_reader_doc - @deprecate_kwarg(old_arg_name="encoding", new_arg_name=None) @deprecate_kwarg(old_arg_name="index", new_arg_name="index_col") def __init__( self, @@ -1056,7 +1045,6 @@ def __init__( preserve_dtypes=True, columns=None, order_categoricals=True, - encoding=None, chunksize=None, ): super().__init__() @@ -2134,14 +2122,12 @@ class StataWriter(StataParser): _max_string_length = 244 - @deprecate_kwarg(old_arg_name="encoding", new_arg_name=None) def __init__( self, fname, data, convert_dates=None, write_index=True, - encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, @@ -2859,8 +2845,6 @@ class StataWriter117(StataWriter): 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 @@ -2912,14 +2896,12 @@ class StataWriter117(StataWriter): _max_string_length = 2045 - @deprecate_kwarg(old_arg_name="encoding", new_arg_name=None) def __init__( self, fname, data, convert_dates=None, write_index=True, - encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 7fa3b968278d9..2cc80a6e5565d 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -383,8 +383,7 @@ def test_encoding(self, version): # GH 4626, proper encoding handling raw = read_stata(self.dta_encoding) - with tm.assert_produces_warning(FutureWarning): - encoded = read_stata(self.dta_encoding, encoding="latin-1") + encoded = read_stata(self.dta_encoding) result = encoded.kreis1849[0] expected = raw.kreis1849[0] @@ -392,10 +391,7 @@ def test_encoding(self, version): assert isinstance(result, str) with tm.ensure_clean() as path: - with tm.assert_produces_warning(FutureWarning): - encoded.to_stata( - path, write_index=False, version=version, encoding="latin-1" - ) + encoded.to_stata(path, write_index=False, version=version) reread_encoded = read_stata(path) tm.assert_frame_equal(encoded, reread_encoded)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29722
2019-11-19T21:08:43Z
2019-11-20T21:07:00Z
2019-11-20T21:07:00Z
2019-11-20T21:12:26Z
DEPR: remove deprecated keywords in read_excel, to_records
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index f158c1158b54e..0e2b32c2c5d7c 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -315,6 +315,8 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - :meth:`pandas.Series.str.cat` now defaults to aligning ``others``, using ``join='left'`` (:issue:`27611`) - :meth:`pandas.Series.str.cat` does not accept list-likes *within* list-likes anymore (:issue:`27611`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) +- :func:`read_excel` removed support for "skip_footer" argument, use "skipfooter" instead (:issue:`18836`) +- :meth:`DataFrame.to_records` no longer supports the argument "convert_datetime64" (:issue:`18902`) - Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) - Changed the default value for the "keep_tz" argument in :meth:`DatetimeIndex.to_series` to ``True`` (:issue:`23739`) - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5baba0bae1d45..cb74fff51e7a3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -66,7 +66,6 @@ ensure_platform_int, infer_dtype_from_object, is_bool_dtype, - is_datetime64_any_dtype, is_dict_like, is_dtype_equal, is_extension_array_dtype, @@ -1685,9 +1684,7 @@ def from_records( return cls(mgr) - def to_records( - self, index=True, convert_datetime64=None, column_dtypes=None, index_dtypes=None - ): + def to_records(self, index=True, column_dtypes=None, index_dtypes=None): """ Convert DataFrame to a NumPy record array. @@ -1699,11 +1696,6 @@ def to_records( index : bool, default True Include index in resulting record array, stored in 'index' field or using the index label, if set. - convert_datetime64 : bool, default None - .. deprecated:: 0.23.0 - - Whether to convert the index to datetime.datetime if it is a - DatetimeIndex. column_dtypes : str, type, dict, default None .. versionadded:: 0.24.0 @@ -1778,24 +1770,12 @@ def to_records( dtype=[('I', 'S1'), ('A', '<i8'), ('B', '<f8')]) """ - if convert_datetime64 is not None: - warnings.warn( - "The 'convert_datetime64' parameter is " - "deprecated and will be removed in a future " - "version", - FutureWarning, - stacklevel=2, - ) - if index: - if is_datetime64_any_dtype(self.index) and convert_datetime64: - ix_vals = [self.index.to_pydatetime()] + if isinstance(self.index, ABCMultiIndex): + # array of tuples to numpy cols. copy copy copy + ix_vals = list(map(np.array, zip(*self.index.values))) else: - if isinstance(self.index, ABCMultiIndex): - # array of tuples to numpy cols. copy copy copy - ix_vals = list(map(np.array, zip(*self.index.values))) - else: - ix_vals = [self.index.values] + ix_vals = [self.index.values] arrays = ix_vals + [self[c]._internal_get_values() for c in self.columns] diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 7ad7c40917b9c..e615507b4199d 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -8,7 +8,7 @@ from pandas._config import config from pandas.errors import EmptyDataError -from pandas.util._decorators import Appender, deprecate_kwarg +from pandas.util._decorators import Appender from pandas.core.dtypes.common import is_bool, is_float, is_integer, is_list_like @@ -188,11 +188,6 @@ Comments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the comment string and the end of the current line is ignored. -skip_footer : int, default 0 - Alias of `skipfooter`. - - .. deprecated:: 0.23.0 - Use `skipfooter` instead. skipfooter : int, default 0 Rows at the end to skip (0-indexed). convert_float : bool, default True @@ -277,7 +272,6 @@ @Appender(_read_excel_doc) -@deprecate_kwarg("skip_footer", "skipfooter") def read_excel( io, sheet_name=0, @@ -300,7 +294,6 @@ def read_excel( date_parser=None, thousands=None, comment=None, - skip_footer=0, skipfooter=0, convert_float=True, mangle_dupe_cols=True, diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index e1dda1411edbd..63a98fda974a6 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -83,23 +83,10 @@ def test_to_records_dt64(self): index=date_range("2012-01-01", "2012-01-02"), ) - # convert_datetime64 defaults to None expected = df.index.values[0] result = df.to_records()["index"][0] assert expected == result - # check for FutureWarning if convert_datetime64=False is passed - with tm.assert_produces_warning(FutureWarning): - expected = df.index.values[0] - result = df.to_records(convert_datetime64=False)["index"][0] - assert expected == result - - # check for FutureWarning if convert_datetime64=True is passed - with tm.assert_produces_warning(FutureWarning): - expected = df.index[0] - result = df.to_records(convert_datetime64=True)["index"][0] - assert expected == result - def test_to_records_with_multindex(self): # GH3189 index = [ diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index d1611eebe2059..f6d94c4452076 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -917,14 +917,6 @@ def test_excel_table_sheet_by_index(self, read_ext, df_ref): df3 = pd.read_excel(excel, 0, index_col=0, skipfooter=1) tm.assert_frame_equal(df3, df1.iloc[:-1]) - with tm.assert_produces_warning( - FutureWarning, check_stacklevel=False, raise_on_extra_warnings=False - ): - with pd.ExcelFile("test1" + read_ext) as excel: - df4 = pd.read_excel(excel, 0, index_col=0, skip_footer=1) - - tm.assert_frame_equal(df3, df4) - with pd.ExcelFile("test1" + read_ext) as excel: df3 = excel.parse(0, index_col=0, skipfooter=1)
There are a handful of these PRs on the way and they're inevitably going to have whatsnew conflicts. I'm trying to group together related deprecations so as to have a single-digit number of PRs for these.
https://api.github.com/repos/pandas-dev/pandas/pulls/29721
2019-11-19T21:06:34Z
2019-11-20T16:43:03Z
2019-11-20T16:43:03Z
2021-11-20T23:21:56Z
DEPR: remove Series.from_array, DataFrame.from_items, as_matrix, asobject, as_blocks, blocks
diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index 4b5faed0f4d2d..37d27093efefd 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -351,7 +351,6 @@ Serialization / IO / conversion :toctree: api/ DataFrame.from_dict - DataFrame.from_items DataFrame.from_records DataFrame.info DataFrame.to_parquet diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index f158c1158b54e..50b80a6f7038a 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -312,6 +312,12 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed the previously deprecated :meth:`Series.get_value`, :meth:`Series.set_value`, :meth:`DataFrame.get_value`, :meth:`DataFrame.set_value` (:issue:`17739`) - Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to False (:issue:`27600`) +- Removed support for nested renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`18529`) +- Removed :meth:`Series.from_array` (:issue:`18258`) +- Removed :meth:`DataFrame.from_items` (:issue:`18458`) +- Removed :meth:`DataFrame.as_matrix`, :meth:`Series.as_matrix` (:issue:`18458`) +- Removed :meth:`Series.asobject` (:issue:`18477`) +- Removed :meth:`DataFrame.as_blocks`, :meth:`Series.as_blocks`, `DataFrame.blocks`, :meth:`Series.blocks` (:issue:`17656`) - :meth:`pandas.Series.str.cat` now defaults to aligning ``others``, using ``join='left'`` (:issue:`27611`) - :meth:`pandas.Series.str.cat` does not accept list-likes *within* list-likes anymore (:issue:`27611`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5baba0bae1d45..5c9dd8121733c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -77,7 +77,6 @@ is_iterator, is_list_like, is_named_tuple, - is_nested_list_like, is_object_dtype, is_scalar, is_sequence, @@ -343,8 +342,9 @@ class DataFrame(NDFrame): -------- DataFrame.from_records : Constructor from tuples, also record arrays. DataFrame.from_dict : From dicts of Series, arrays, or dicts. - DataFrame.from_items : From sequence of (key, value) pairs - read_csv, pandas.read_table, pandas.read_clipboard. + read_csv + read_table + read_clipboard Examples -------- @@ -388,9 +388,7 @@ def _constructor(self) -> Type["DataFrame"]: return DataFrame _constructor_sliced = Series # type: Type[Series] - _deprecations = NDFrame._deprecations | frozenset( - ["from_items"] - ) # type: FrozenSet[str] + _deprecations = NDFrame._deprecations | frozenset([]) # type: FrozenSet[str] _accessors = set() # type: Set[str] @property @@ -1870,103 +1868,6 @@ def to_records( return np.rec.fromarrays(arrays, dtype={"names": names, "formats": formats}) - @classmethod - def from_items(cls, items, columns=None, orient="columns"): - """ - Construct a DataFrame from a list of tuples. - - .. deprecated:: 0.23.0 - `from_items` is deprecated and will be removed in a future version. - Use :meth:`DataFrame.from_dict(dict(items)) <DataFrame.from_dict>` - instead. - :meth:`DataFrame.from_dict(OrderedDict(items)) <DataFrame.from_dict>` - may be used to preserve the key order. - - Convert (key, value) pairs to DataFrame. The keys will be the axis - index (usually the columns, but depends on the specified - orientation). The values should be arrays or Series. - - Parameters - ---------- - items : sequence of (key, value) pairs - Values should be arrays or Series. - columns : sequence of column labels, optional - Must be passed if orient='index'. - orient : {'columns', 'index'}, default 'columns' - The "orientation" of the data. If the keys of the - input correspond to column labels, pass 'columns' - (default). Otherwise if the keys correspond to the index, - pass 'index'. - - Returns - ------- - DataFrame - """ - - warnings.warn( - "from_items is deprecated. Please use " - "DataFrame.from_dict(dict(items), ...) instead. " - "DataFrame.from_dict(OrderedDict(items)) may be used to " - "preserve the key order.", - FutureWarning, - stacklevel=2, - ) - - keys, values = zip(*items) - - if orient == "columns": - if columns is not None: - columns = ensure_index(columns) - - idict = dict(items) - if len(idict) < len(items): - if not columns.equals(ensure_index(keys)): - raise ValueError( - "With non-unique item names, passed " - "columns must be identical" - ) - arrays = values - else: - arrays = [idict[k] for k in columns if k in idict] - else: - columns = ensure_index(keys) - arrays = values - - # GH 17312 - # Provide more informative error msg when scalar values passed - try: - return cls._from_arrays(arrays, columns, None) - - except ValueError: - if not is_nested_list_like(values): - raise ValueError( - "The value in each (key, value) pair " - "must be an array, Series, or dict" - ) - - elif orient == "index": - if columns is None: - raise TypeError("Must pass columns with orient='index'") - - keys = ensure_index(keys) - - # GH 17312 - # Provide more informative error msg when scalar values passed - try: - arr = np.array(values, dtype=object).T - data = [lib.maybe_convert_objects(v) for v in arr] - return cls._from_arrays(data, columns, keys) - - except TypeError: - if not is_nested_list_like(values): - raise ValueError( - "The value in each (key, value) pair " - "must be an array, Series, or dict" - ) - - else: # pragma: no cover - raise ValueError("'orient' must be either 'columns' or 'index'") - @classmethod def _from_arrays(cls, arrays, columns, index, dtype=None): mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 4f45a96d23941..6fbe95fa973cb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -173,9 +173,6 @@ class NDFrame(PandasObject, SelectionMixin): _accessors = set() # type: Set[str] _deprecations = frozenset( [ - "as_blocks", - "as_matrix", - "blocks", "clip_lower", "clip_upper", "get_dtype_counts", @@ -5409,54 +5406,6 @@ def _get_bool_data(self): # ---------------------------------------------------------------------- # Internal Interface Methods - def as_matrix(self, columns=None): - """ - Convert the frame to its Numpy-array representation. - - .. deprecated:: 0.23.0 - Use :meth:`DataFrame.values` instead. - - Parameters - ---------- - columns : list, optional, default:None - If None, return all columns, otherwise, returns specified columns. - - Returns - ------- - values : ndarray - If the caller is heterogeneous and contains booleans or objects, - the result will be of dtype=object. See Notes. - - See Also - -------- - DataFrame.values - - Notes - ----- - Return is NOT a Numpy-matrix, rather, a Numpy-array. - - The dtype will be a lower-common-denominator dtype (implicit - upcasting); that is to say if the dtypes (even of numeric types) - are mixed, the one that accommodates all will be chosen. Use this - with care if you are not dealing with the blocks. - - e.g. If the dtypes are float16 and float32, dtype will be upcast to - float32. If dtypes are int32 and uint8, dtype will be upcase to - int32. By numpy.find_common_type convention, mixing int64 and uint64 - will result in a float64 dtype. - - This method is provided for backwards compatibility. Generally, - it is recommended to use '.values'. - """ - warnings.warn( - "Method .as_matrix will be removed in a future version. " - "Use .values instead.", - FutureWarning, - stacklevel=2, - ) - self._consolidate_inplace() - return self._data.as_array(transpose=self._AXIS_REVERSED, items=columns) - @property def values(self): """ @@ -5774,40 +5723,6 @@ def ftypes(self): return Series(self._data.get_ftypes(), index=self._info_axis, dtype=np.object_) - def as_blocks(self, copy=True): - """ - Convert the frame to a dict of dtype -> Constructor Types. - - .. deprecated:: 0.21.0 - - NOTE: the dtypes of the blocks WILL BE PRESERVED HERE (unlike in - as_matrix) - - Parameters - ---------- - copy : bool, default True - - Returns - ------- - dict - Mapping dtype -> Constructor Types. - """ - warnings.warn( - "as_blocks is deprecated and will be removed in a future version", - FutureWarning, - stacklevel=2, - ) - return self._to_dict_of_blocks(copy=copy) - - @property - def blocks(self): - """ - Internal property, property synonym for as_blocks(). - - .. deprecated:: 0.21.0 - """ - return self.as_blocks() - def _to_dict_of_blocks(self, copy=True): """ Return a dict of dtype -> Constructor Types that diff --git a/pandas/core/series.py b/pandas/core/series.py index 3f69dd53491c1..8d15cad72d8fc 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -176,17 +176,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): base.IndexOpsMixin._deprecations | generic.NDFrame._deprecations | frozenset( - [ - "asobject", - "compress", - "valid", - "ftype", - "real", - "imag", - "put", - "ptp", - "nonzero", - ] + ["compress", "valid", "ftype", "real", "imag", "put", "ptp", "nonzero"] ) ) @@ -364,32 +354,6 @@ def _init_dict(self, data, index=None, dtype=None): s = s.reindex(index, copy=False) return s._data, s.index - @classmethod - def from_array( - cls, arr, index=None, name=None, dtype=None, copy=False, fastpath=False - ): - """ - Construct Series from array. - - .. deprecated:: 0.23.0 - Use pd.Series(..) constructor instead. - - Returns - ------- - Series - Constructed Series. - """ - warnings.warn( - "'from_array' is deprecated and will be removed in a " - "future version. Please use the pd.Series(..) " - "constructor instead.", - FutureWarning, - stacklevel=2, - ) - return cls( - arr, index=index, name=name, dtype=dtype, copy=copy, fastpath=fastpath - ) - # ---------------------------------------------------------------------- @property @@ -579,24 +543,6 @@ def get_values(self): def _internal_get_values(self): return self._data.get_values() - @property - def asobject(self): - """ - Return object Series which contains boxed values. - - .. deprecated:: 0.23.0 - - Use ``astype(object)`` instead. - - *this is an internal non-public method* - """ - warnings.warn( - "'asobject' is deprecated. Use 'astype(object)' instead", - FutureWarning, - stacklevel=2, - ) - return self.astype(object).values - # ops def ravel(self, order="C"): """ diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 50b1dec21c549..a86e1dfe8353c 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -476,14 +476,6 @@ def test_values(self, float_frame): float_frame.values[:, 0] = 5.0 assert (float_frame.values[:, 0] == 5).all() - def test_as_matrix_deprecated(self, float_frame): - # GH 18458 - with tm.assert_produces_warning(FutureWarning): - cols = float_frame.columns.tolist() - result = float_frame.as_matrix(columns=cols) - expected = float_frame.values - tm.assert_numpy_array_equal(result, expected) - def test_deepcopy(self, float_frame): cp = deepcopy(float_frame) series = cp["A"] diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index b45c074f179a0..d491e9f25c897 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -313,10 +313,7 @@ def test_copy_blocks(self, float_frame): column = df.columns[0] # use the default copy=True, change a column - - # deprecated 0.21.0 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - blocks = df.as_blocks() + blocks = df._to_dict_of_blocks(copy=True) for dtype, _df in blocks.items(): if column in _df: _df.loc[:, column] = _df[column] + 1 @@ -330,10 +327,7 @@ def test_no_copy_blocks(self, float_frame): column = df.columns[0] # use the copy=False, change a column - - # deprecated 0.21.0 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - blocks = df.as_blocks(copy=False) + blocks = df._to_dict_of_blocks(copy=False) for dtype, _df in blocks.items(): if column in _df: _df.loc[:, column] = _df[column] + 1 diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index cc2e37c14bdf0..ce0ebdbe56354 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -10,7 +10,6 @@ from pandas.compat import is_platform_little_endian -from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.common import is_integer_dtype import pandas as pd @@ -1508,92 +1507,6 @@ def test_constructor_manager_resize(self, float_frame): tm.assert_index_equal(result.index, Index(index)) tm.assert_index_equal(result.columns, Index(columns)) - def test_constructor_from_items(self, float_frame, float_string_frame): - items = [(c, float_frame[c]) for c in float_frame.columns] - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - recons = DataFrame.from_items(items) - tm.assert_frame_equal(recons, float_frame) - - # pass some columns - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - recons = DataFrame.from_items(items, columns=["C", "B", "A"]) - tm.assert_frame_equal(recons, float_frame.loc[:, ["C", "B", "A"]]) - - # orient='index' - - row_items = [ - (idx, float_string_frame.xs(idx)) for idx in float_string_frame.index - ] - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - recons = DataFrame.from_items( - row_items, columns=float_string_frame.columns, orient="index" - ) - tm.assert_frame_equal(recons, float_string_frame) - assert recons["A"].dtype == np.float64 - - msg = "Must pass columns with orient='index'" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - DataFrame.from_items(row_items, orient="index") - - # orient='index', but thar be tuples - arr = construct_1d_object_array_from_listlike( - [("bar", "baz")] * len(float_string_frame) - ) - float_string_frame["foo"] = arr - row_items = [ - (idx, list(float_string_frame.xs(idx))) for idx in float_string_frame.index - ] - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - recons = DataFrame.from_items( - row_items, columns=float_string_frame.columns, orient="index" - ) - tm.assert_frame_equal(recons, float_string_frame) - assert isinstance(recons["foo"][0], tuple) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - rs = DataFrame.from_items( - [("A", [1, 2, 3]), ("B", [4, 5, 6])], - orient="index", - columns=["one", "two", "three"], - ) - xp = DataFrame( - [[1, 2, 3], [4, 5, 6]], index=["A", "B"], columns=["one", "two", "three"] - ) - tm.assert_frame_equal(rs, xp) - - def test_constructor_from_items_scalars(self): - # GH 17312 - msg = ( - r"The value in each \(key, value\) " - "pair must be an array, Series, or dict" - ) - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - DataFrame.from_items([("A", 1), ("B", 4)]) - - msg = ( - r"The value in each \(key, value\) " - "pair must be an array, Series, or dict" - ) - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - DataFrame.from_items( - [("A", 1), ("B", 2)], columns=["col1"], orient="index" - ) - - def test_from_items_deprecation(self): - # GH 17320 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - DataFrame.from_items([("A", [1, 2, 3]), ("B", [4, 5, 6])]) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - DataFrame.from_items( - [("A", [1, 2, 3]), ("B", [4, 5, 6])], - columns=["col1", "col2", "col3"], - orient="index", - ) - def test_constructor_mix_series_nonseries(self, float_frame): df = DataFrame( {"A": float_frame["A"], "B": list(float_frame["B"])}, columns=["A", "B"] diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 00c66c8a13bd9..1e4757ffecb5d 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -199,11 +199,6 @@ def test_constructor_dict_timedelta_index(self): ) self._assert_series_equal(result, expected) - def test_from_array_deprecated(self): - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=True): - self.series_klass.from_array([1, 2, 3]) - def test_sparse_accessor_updates_on_inplace(self): s = pd.Series([1, 1, 2, 3], dtype="Sparse[int]") s.drop([0, 1], inplace=True) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index 4b03115c11cb3..e1ace952f722d 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -44,12 +44,6 @@ def test_astype(self, dtype): assert as_typed.dtype == dtype assert as_typed.name == s.name - def test_asobject_deprecated(self): - s = Series(np.random.randn(5), name="foo") - with tm.assert_produces_warning(FutureWarning): - o = s.asobject - assert isinstance(o, np.ndarray) - def test_dtype(self, datetime_series): assert datetime_series.dtype == np.dtype("float64") diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index cf06a9a7c8415..1587ae5eb7d07 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -1040,10 +1040,6 @@ def test_from_M8_structured(self): assert isinstance(s[0], Timestamp) assert s[0] == dates[0][0] - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - s = Series.from_array(arr["Date"], Index([0])) - assert s[0] == dates[0][0] - def test_get_level_values_box(self): from pandas import MultiIndex
https://api.github.com/repos/pandas-dev/pandas/pulls/29720
2019-11-19T20:53:22Z
2019-11-20T17:15:10Z
2019-11-20T17:15:10Z
2019-11-20T17:38:29Z
Improve return description in `droplevel` docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 982a57a6f725e..4f45a96d23941 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -807,7 +807,8 @@ def droplevel(self, level, axis=0): Returns ------- - DataFrame.droplevel() + DataFrame + DataFrame with requested index / column level(s) removed. Examples --------
Use https://pandas-docs.github.io/pandas-docs-travis/reference/api/pandas.DataFrame.dropna.html#pandas.DataFrame.dropna docstring as a\ template. MINOR DOCUMENTATION CHANGE ONLY (ignored below) - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29717
2019-11-19T19:41:10Z
2019-11-19T20:54:14Z
2019-11-19T20:54:14Z
2020-03-26T06:44:04Z
TST: Silence lzma output
diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index d68b6a1effaa0..9bcdda2039458 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -140,7 +140,7 @@ def test_with_missing_lzma(): import pandas """ ) - subprocess.check_output([sys.executable, "-c", code]) + subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE) def test_with_missing_lzma_runtime(): @@ -157,4 +157,4 @@ def test_with_missing_lzma_runtime(): df.to_csv('foo.csv', compression='xz') """ ) - subprocess.check_output([sys.executable, "-c", code]) + subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE)
This was leaking to stdout when the pytest `-s` flag was used.
https://api.github.com/repos/pandas-dev/pandas/pulls/29713
2019-11-19T16:55:18Z
2019-11-20T12:36:07Z
2019-11-20T12:36:06Z
2019-11-20T12:36:09Z
CI: Fix clipboard problems
diff --git a/.travis.yml b/.travis.yml index a11cd469e9b9c..b5897e3526327 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,19 +31,19 @@ matrix: include: - env: - - JOB="3.8" ENV_FILE="ci/deps/travis-38.yaml" PATTERN="(not slow and not network)" + - JOB="3.8" ENV_FILE="ci/deps/travis-38.yaml" PATTERN="(not slow and not network and not clipboard)" - env: - - JOB="3.7" ENV_FILE="ci/deps/travis-37.yaml" PATTERN="(not slow and not network)" + - JOB="3.7" ENV_FILE="ci/deps/travis-37.yaml" PATTERN="(not slow and not network and not clipboard)" - env: - - JOB="3.6, locale" ENV_FILE="ci/deps/travis-36-locale.yaml" PATTERN="((not slow and not network) or (single and db))" LOCALE_OVERRIDE="zh_CN.UTF-8" SQL="1" + - JOB="3.6, locale" ENV_FILE="ci/deps/travis-36-locale.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" LOCALE_OVERRIDE="zh_CN.UTF-8" SQL="1" services: - mysql - postgresql - env: - - JOB="3.6, coverage" ENV_FILE="ci/deps/travis-36-cov.yaml" PATTERN="((not slow and not network) or (single and db))" PANDAS_TESTING_MODE="deprecate" COVERAGE=true SQL="1" + - JOB="3.6, coverage" ENV_FILE="ci/deps/travis-36-cov.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" PANDAS_TESTING_MODE="deprecate" COVERAGE=true SQL="1" services: - mysql - postgresql diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index 55e8e839f4fae..c9a2e4eefd19d 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -18,7 +18,7 @@ jobs: py36_minimum_versions: ENV_FILE: ci/deps/azure-36-minimum_versions.yaml CONDA_PY: "36" - PATTERN: "not slow and not network" + PATTERN: "not slow and not network and not clipboard" py36_locale_slow_old_np: ENV_FILE: ci/deps/azure-36-locale_slow.yaml @@ -36,12 +36,12 @@ jobs: PATTERN: "not slow and not network" LANG: "it_IT.utf8" LC_ALL: "it_IT.utf8" - EXTRA_APT: "language-pack-it" + EXTRA_APT: "language-pack-it xsel" py36_32bit: ENV_FILE: ci/deps/azure-36-32bit.yaml CONDA_PY: "36" - PATTERN: "not slow and not network" + PATTERN: "not slow and not network and not clipboard" BITS32: "yes" py37_locale: @@ -50,7 +50,7 @@ jobs: PATTERN: "not slow and not network" LANG: "zh_CN.utf8" LC_ALL: "zh_CN.utf8" - EXTRA_APT: "language-pack-zh-hans" + EXTRA_APT: "language-pack-zh-hans xsel" py37_np_dev: ENV_FILE: ci/deps/azure-37-numpydev.yaml diff --git a/ci/run_tests.sh b/ci/run_tests.sh index 8020680d617d7..0cb1f4aabf352 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -14,14 +14,14 @@ if [ "$COVERAGE" ]; then COVERAGE="-s --cov=pandas --cov-report=xml:$COVERAGE_FNAME" fi -PYTEST_CMD="pytest -m \"$PATTERN\" -n auto --dist=loadfile -s --strict --durations=10 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas" - -# Travis does not have have an X server -if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then - DISPLAY=DISPLAY=:99.0 - PYTEST_CMD="xvfb-run -e /dev/stdout $PYTEST_CMD" +# If no X server is found, we use xvfb to emulate it +if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then + export DISPLAY=":0" + XVFB="xvfb-run " fi +PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n auto --dist=loadfile -s --strict --durations=10 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas" + echo $PYTEST_CMD sh -c "$PYTEST_CMD" diff --git a/ci/setup_env.sh b/ci/setup_env.sh index db28eaea8956e..e5bee09fe2f79 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -114,6 +114,11 @@ echo "remove postgres if has been installed with conda" echo "we use the one from the CI" conda remove postgresql -y --force || true +echo +echo "remove qt" +echo "causes problems with the clipboard, we use xsel for that" +conda remove qt -y --force || true + echo echo "conda list pandas" conda list pandas diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index a69e5556f3e85..652cacaf14ffb 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -8,13 +8,7 @@ from pandas import DataFrame, get_option, read_clipboard import pandas._testing as tm -from pandas.io.clipboard import PyperclipException, clipboard_get, clipboard_set - -try: - DataFrame({"A": [1, 2]}).to_clipboard() - _DEPS_INSTALLED = 1 -except (PyperclipException, RuntimeError): - _DEPS_INSTALLED = 0 +from pandas.io.clipboard import clipboard_get, clipboard_set def build_kwargs(sep, excel): @@ -148,7 +142,6 @@ def test_mock_clipboard(mock_clipboard): @pytest.mark.single @pytest.mark.clipboard -@pytest.mark.skipif(not _DEPS_INSTALLED, reason="clipboard primitives not installed") @pytest.mark.usefixtures("mock_clipboard") class TestClipboard: def check_round_trip_frame(self, data, excel=None, sep=None, encoding=None): @@ -256,9 +249,7 @@ def test_round_trip_valid_encodings(self, enc, df): @pytest.mark.single @pytest.mark.clipboard -@pytest.mark.skipif(not _DEPS_INSTALLED, reason="clipboard primitives not installed") @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑´...", "abcd..."]) -@pytest.mark.xfail(reason="flaky in CI", strict=False) def test_raw_roundtrip(data): # PR #25040 wide unicode wasn't copied correctly on PY3 on windows clipboard_set(data)
- [X] closes #29676 Fixes the clipboard problems in the CI. With this PR we're sure they are being run, and they work as expected.
https://api.github.com/repos/pandas-dev/pandas/pulls/29712
2019-11-19T16:39:20Z
2020-01-15T13:40:35Z
2020-01-15T13:40:35Z
2020-07-01T16:06:59Z
Assorted io extension cleanups
diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c index aecd4e03664e6..1e3295fcb6fc7 100644 --- a/pandas/_libs/src/parser/io.c +++ b/pandas/_libs/src/parser/io.c @@ -9,7 +9,6 @@ The full license is in the LICENSE file, distributed with this software. #include "io.h" -#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c index 83869a1d9c342..578f72112d02d 100644 --- a/pandas/_libs/src/parser/tokenizer.c +++ b/pandas/_libs/src/parser/tokenizer.c @@ -25,19 +25,6 @@ GitHub. See Python Software Foundation License and BSD licenses for these. #include "../headers/portable.h" -static void *safe_realloc(void *buffer, size_t size) { - void *result; - // OSX is weird. - // http://stackoverflow.com/questions/9560609/ - // different-realloc-behaviour-in-linux-and-osx - - result = realloc(buffer, size); - TRACE(("safe_realloc: buffer = %p, size = %zu, result = %p\n", buffer, size, - result)) - - return result; -} - void coliter_setup(coliter_t *self, parser_t *parser, int i, int start) { // column i, starting at 0 self->words = parser->words; @@ -45,18 +32,6 @@ void coliter_setup(coliter_t *self, parser_t *parser, int i, int start) { self->line_start = parser->line_start + start; } -coliter_t *coliter_new(parser_t *self, int i) { - // column i, starting at 0 - coliter_t *iter = (coliter_t *)malloc(sizeof(coliter_t)); - - if (NULL == iter) { - return NULL; - } - - coliter_setup(iter, self, i, 0); - return iter; -} - static void free_if_not_null(void **ptr) { TRACE(("free_if_not_null %p\n", *ptr)) if (*ptr != NULL) { @@ -80,7 +55,7 @@ static void *grow_buffer(void *buffer, uint64_t length, uint64_t *capacity, while ((length + space >= cap) && (newbuffer != NULL)) { cap = cap ? cap << 1 : 2; buffer = newbuffer; - newbuffer = safe_realloc(newbuffer, elsize * cap); + newbuffer = realloc(newbuffer, elsize * cap); } if (newbuffer == NULL) { @@ -321,8 +296,8 @@ static int make_stream_space(parser_t *self, size_t nbytes) { ("make_stream_space: cap != self->words_cap, nbytes = %d, " "self->words_cap=%d\n", nbytes, self->words_cap)) - newptr = safe_realloc((void *)self->word_starts, - sizeof(int64_t) * self->words_cap); + newptr = realloc((void *)self->word_starts, + sizeof(int64_t) * self->words_cap); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { @@ -349,8 +324,8 @@ static int make_stream_space(parser_t *self, size_t nbytes) { if (cap != self->lines_cap) { TRACE(("make_stream_space: cap != self->lines_cap, nbytes = %d\n", nbytes)) - newptr = safe_realloc((void *)self->line_fields, - sizeof(int64_t) * self->lines_cap); + newptr = realloc((void *)self->line_fields, + sizeof(int64_t) * self->lines_cap); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { @@ -427,7 +402,7 @@ static void append_warning(parser_t *self, const char *msg) { snprintf(self->warn_msg, length + 1, "%s", msg); } else { ex_length = strlen(self->warn_msg); - newptr = safe_realloc(self->warn_msg, ex_length + length + 1); + newptr = realloc(self->warn_msg, ex_length + length + 1); if (newptr != NULL) { self->warn_msg = (char *)newptr; snprintf(self->warn_msg + ex_length, length + 1, "%s", msg); @@ -1290,13 +1265,13 @@ int parser_trim_buffers(parser_t *self) { new_cap = _next_pow2(self->words_len) + 1; if (new_cap < self->words_cap) { TRACE(("parser_trim_buffers: new_cap < self->words_cap\n")); - newptr = safe_realloc((void *)self->words, new_cap * sizeof(char *)); + newptr = realloc((void *)self->words, new_cap * sizeof(char *)); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { self->words = (char **)newptr; } - newptr = safe_realloc((void *)self->word_starts, + newptr = realloc((void *)self->word_starts, new_cap * sizeof(int64_t)); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; @@ -1315,13 +1290,13 @@ int parser_trim_buffers(parser_t *self) { if (new_cap < self->stream_cap) { TRACE( ("parser_trim_buffers: new_cap < self->stream_cap, calling " - "safe_realloc\n")); - newptr = safe_realloc((void *)self->stream, new_cap); + "realloc\n")); + newptr = realloc((void *)self->stream, new_cap); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { // Update the pointers in the self->words array (char **) if - // `safe_realloc` + // `realloc` // moved the `self->stream` buffer. This block mirrors a similar // block in // `make_stream_space`. @@ -1342,14 +1317,14 @@ int parser_trim_buffers(parser_t *self) { new_cap = _next_pow2(self->lines) + 1; if (new_cap < self->lines_cap) { TRACE(("parser_trim_buffers: new_cap < self->lines_cap\n")); - newptr = safe_realloc((void *)self->line_start, + newptr = realloc((void *)self->line_start, new_cap * sizeof(int64_t)); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { self->line_start = (int64_t *)newptr; } - newptr = safe_realloc((void *)self->line_fields, + newptr = realloc((void *)self->line_fields, new_cap * sizeof(int64_t)); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; diff --git a/pandas/_libs/src/parser/tokenizer.h b/pandas/_libs/src/parser/tokenizer.h index 4903e936dc348..b37de47662feb 100644 --- a/pandas/_libs/src/parser/tokenizer.h +++ b/pandas/_libs/src/parser/tokenizer.h @@ -15,7 +15,6 @@ See LICENSE for the license #define PY_SSIZE_T_CLEAN #include <Python.h> -#define ERROR_OK 0 #define ERROR_NO_DIGITS 1 #define ERROR_OVERFLOW 2 #define ERROR_INVALID_CHARS 3 @@ -32,10 +31,6 @@ See LICENSE for the license #define CALLING_READ_FAILED 2 -#if defined(_MSC_VER) -#define strtoll _strtoi64 -#endif // _MSC_VER - /* C flat file parsing low level code for pandas / NumPy @@ -180,7 +175,6 @@ typedef struct coliter_t { } coliter_t; void coliter_setup(coliter_t *self, parser_t *parser, int i, int start); -coliter_t *coliter_new(parser_t *self, int i); #define COLITER_NEXT(iter, word) \ do { \
Just giving these a look seem to be a lot of unused definitions / functions
https://api.github.com/repos/pandas-dev/pandas/pulls/29704
2019-11-19T06:16:01Z
2019-11-20T12:58:14Z
2019-11-20T12:58:14Z
2020-01-16T00:35:18Z
TYP: more annotations for io.pytables
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 193b8f5053d65..9589832095474 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -520,16 +520,16 @@ def root(self): def filename(self): return self._path - def __getitem__(self, key): + def __getitem__(self, key: str): return self.get(key) - def __setitem__(self, key, value): + def __setitem__(self, key: str, value): self.put(key, value) - def __delitem__(self, key): + def __delitem__(self, key: str): return self.remove(key) - def __getattr__(self, name): + def __getattr__(self, name: str): """ allow attribute access to get stores """ try: return self.get(name) @@ -791,7 +791,12 @@ def func(_start, _stop, _where): return it.get_result() def select_as_coordinates( - self, key: str, where=None, start=None, stop=None, **kwargs + self, + key: str, + where=None, + start: Optional[int] = None, + stop: Optional[int] = None, + **kwargs, ): """ return the selection as an Index @@ -943,13 +948,13 @@ def func(_start, _stop, _where): return it.get_result(coordinates=True) - def put(self, key, value, format=None, append=False, **kwargs): + def put(self, key: str, value, format=None, append=False, **kwargs): """ Store object in HDFStore. Parameters ---------- - key : object + key : str value : {Series, DataFrame} format : 'fixed(f)|table(t)', default is 'fixed' fixed(f) : Fixed format @@ -1028,7 +1033,14 @@ def remove(self, key: str, where=None, start=None, stop=None): return s.delete(where=where, start=start, stop=stop) def append( - self, key, value, format=None, append=True, columns=None, dropna=None, **kwargs + self, + key: str, + value, + format=None, + append=True, + columns=None, + dropna=None, + **kwargs, ): """ Append to Table in file. Node must already exist and be Table @@ -1036,7 +1048,7 @@ def append( Parameters ---------- - key : object + key : str value : {Series, DataFrame} format : 'table' is the default table(t) : table format @@ -1077,7 +1089,14 @@ def append( self._write_to_group(key, value, append=append, dropna=dropna, **kwargs) def append_to_multiple( - self, d, value, selector, data_columns=None, axes=None, dropna=False, **kwargs + self, + d: Dict, + value, + selector, + data_columns=None, + axes=None, + dropna=False, + **kwargs, ): """ Append to multiple tables @@ -1123,7 +1142,7 @@ def append_to_multiple( # figure out how to split the value remain_key = None - remain_values = [] + remain_values: List = [] for k, v in d.items(): if v is None: if remain_key is not None: @@ -1871,7 +1890,7 @@ def validate(self, handler, append): def validate_names(self): pass - def validate_and_set(self, handler, append): + def validate_and_set(self, handler: "AppendableTable", append: bool): self.set_table(handler.table) self.validate_col() self.validate_attr(append) @@ -1901,7 +1920,7 @@ def validate_col(self, itemsize=None): return None - def validate_attr(self, append): + def validate_attr(self, append: bool): # check for backwards incompatibility if append: existing_kind = getattr(self.attrs, self.kind_attr, None) @@ -1967,7 +1986,7 @@ def read_metadata(self, handler): """ retrieve the metadata for this columns """ self.metadata = handler.read_metadata(self.cname) - def validate_metadata(self, handler): + def validate_metadata(self, handler: "AppendableTable"): """ validate that kind=category does not change the categories """ if self.meta == "category": new_metadata = self.metadata @@ -1982,7 +2001,7 @@ def validate_metadata(self, handler): "different categories to the existing" ) - def write_metadata(self, handler): + def write_metadata(self, handler: "AppendableTable"): """ set the meta data """ if self.metadata is not None: handler.write_metadata(self.cname, self.metadata) @@ -1995,7 +2014,15 @@ class GenericIndexCol(IndexCol): def is_indexed(self) -> bool: return False - def convert(self, values, nan_rep, encoding, errors, start=None, stop=None): + def convert( + self, + values, + nan_rep, + encoding, + errors, + start: Optional[int] = None, + stop: Optional[int] = None, + ): """ set the values from this selection: take = take ownership Parameters @@ -2012,9 +2039,9 @@ def convert(self, values, nan_rep, encoding, errors, start=None, stop=None): the underlying table's row count are normalized to that. """ - start = start if start is not None else 0 - stop = min(stop, self.table.nrows) if stop is not None else self.table.nrows - self.values = Int64Index(np.arange(stop - start)) + _start = start if start is not None else 0 + _stop = min(stop, self.table.nrows) if stop is not None else self.table.nrows + self.values = Int64Index(np.arange(_stop - _start)) return self @@ -2749,7 +2776,9 @@ def get_attrs(self): def write(self, obj, **kwargs): self.set_attrs() - def read_array(self, key: str, start=None, stop=None): + def read_array( + self, key: str, start: Optional[int] = None, stop: Optional[int] = None + ): """ read an array for the specified node (off of group """ import tables @@ -2836,7 +2865,7 @@ def write_block_index(self, key, index): self.write_array("{key}_blengths".format(key=key), index.blengths) setattr(self.attrs, "{key}_length".format(key=key), index.length) - def read_block_index(self, key, **kwargs): + def read_block_index(self, key, **kwargs) -> BlockIndex: length = getattr(self.attrs, "{key}_length".format(key=key)) blocs = self.read_array("{key}_blocs".format(key=key), **kwargs) blengths = self.read_array("{key}_blengths".format(key=key), **kwargs) @@ -2846,7 +2875,7 @@ def write_sparse_intindex(self, key, index): self.write_array("{key}_indices".format(key=key), index.indices) setattr(self.attrs, "{key}_length".format(key=key), index.length) - def read_sparse_intindex(self, key, **kwargs): + def read_sparse_intindex(self, key, **kwargs) -> IntIndex: length = getattr(self.attrs, "{key}_length".format(key=key)) indices = self.read_array("{key}_indices".format(key=key), **kwargs) return IntIndex(length, indices) @@ -2878,7 +2907,7 @@ def write_multi_index(self, key, index): label_key = "{key}_label{idx}".format(key=key, idx=i) self.write_array(label_key, level_codes) - def read_multi_index(self, key, **kwargs): + def read_multi_index(self, key, **kwargs) -> MultiIndex: nlevels = getattr(self.attrs, "{key}_nlevels".format(key=key)) levels = [] @@ -2898,7 +2927,9 @@ def read_multi_index(self, key, **kwargs): levels=levels, codes=codes, names=names, verify_integrity=True ) - def read_index_node(self, node, start=None, stop=None): + def read_index_node( + self, node, start: Optional[int] = None, stop: Optional[int] = None + ): data = node[start:stop] # If the index was an empty array write_array_empty() will # have written a sentinel. Here we relace it with the original. @@ -2953,7 +2984,7 @@ def read_index_node(self, node, start=None, stop=None): return name, index - def write_array_empty(self, key, value): + def write_array_empty(self, key: str, value): """ write a 0-len array """ # ugly hack for length 0 axes @@ -2966,7 +2997,7 @@ def _is_empty_array(self, shape) -> bool: """Returns true if any axis is zero length.""" return any(x == 0 for x in shape) - def write_array(self, key, value, items=None): + def write_array(self, key: str, value, items=None): if key in self.group: self._handle.remove_node(self.group, key) @@ -3052,7 +3083,9 @@ def write_array(self, key, value, items=None): class LegacyFixed(GenericFixed): - def read_index_legacy(self, key, start=None, stop=None): + def read_index_legacy( + self, key: str, start: Optional[int] = None, stop: Optional[int] = None + ): node = getattr(self.group, key) data = node[start:stop] kind = node._v_attrs.kind @@ -3237,7 +3270,7 @@ def __init__(self, *args, **kwargs): self.selection = None @property - def table_type_short(self): + def table_type_short(self) -> str: return self.table_type.split("_")[0] @property @@ -3311,7 +3344,7 @@ def validate(self, other): ) @property - def is_multi_index(self): + def is_multi_index(self) -> bool: """the levels attribute is 1 or a list in the case of a multi-index""" return isinstance(self.levels, list) @@ -3335,7 +3368,7 @@ def validate_multiindex(self, obj): ) @property - def nrows_expected(self): + def nrows_expected(self) -> int: """ based on our axes, compute the expected nrows """ return np.prod([i.cvalues.shape[0] for i in self.index_axes]) @@ -3691,7 +3724,7 @@ def create_axes( self, axes, obj, - validate=True, + validate: bool = True, nan_rep=None, data_columns=None, min_itemsize=None, @@ -4000,7 +4033,13 @@ def create_description( return d - def read_coordinates(self, where=None, start=None, stop=None, **kwargs): + def read_coordinates( + self, + where=None, + start: Optional[int] = None, + stop: Optional[int] = None, + **kwargs, + ): """select coordinates (row numbers) from a table; return the coordinates object """ @@ -4013,7 +4052,7 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs): return False # create the selection - self.selection = Selection(self, where=where, start=start, stop=stop, **kwargs) + self.selection = Selection(self, where=where, start=start, stop=stop) coords = self.selection.select_coords() if self.selection.filter is not None: for field, op, filt in self.selection.filter.format(): @@ -4024,7 +4063,13 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs): return Index(coords) - def read_column(self, column: str, where=None, start=None, stop=None): + def read_column( + self, + column: str, + where=None, + start: Optional[int] = None, + stop: Optional[int] = None, + ): """return a single column from the table, generally only indexables are interesting """ @@ -4302,7 +4347,13 @@ def write_data_chunk(self, rows, indexes, mask, values): "tables cannot write this data -> {detail}".format(detail=detail) ) - def delete(self, where=None, start=None, stop=None, **kwargs): + def delete( + self, + where=None, + start: Optional[int] = None, + stop: Optional[int] = None, + **kwargs, + ): # delete all rows (and return the nrows) if where is None or not len(where): @@ -4323,7 +4374,7 @@ def delete(self, where=None, start=None, stop=None, **kwargs): # create the selection table = self.table - self.selection = Selection(self, where, start=start, stop=stop, **kwargs) + self.selection = Selection(self, where, start=start, stop=stop) values = self.selection.select_coords() # delete the rows in reverse order @@ -4913,7 +4964,13 @@ class Selection: """ - def __init__(self, table, where=None, start=None, stop=None): + def __init__( + self, + table: Table, + where=None, + start: Optional[int] = None, + stop: Optional[int] = None, + ): self.table = table self.where = where self.start = start
should be orthogonal to #29692.
https://api.github.com/repos/pandas-dev/pandas/pulls/29703
2019-11-19T02:12:24Z
2019-11-20T13:12:12Z
2019-11-20T13:12:12Z
2019-11-20T15:16:57Z
REF: use _extract_result in Reducer.get_result
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index f5521b94b6c33..ea54b00cf5be4 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -135,9 +135,8 @@ cdef class Reducer: else: res = self.f(chunk) - if (not _is_sparse_array(res) and hasattr(res, 'values') - and util.is_array(res.values)): - res = res.values + # TODO: reason for not squeezing here? + res = _extract_result(res, squeeze=False) if i == 0: # On the first pass, we check the output shape to see # if this looks like a reduction. @@ -402,18 +401,17 @@ cdef class SeriesGrouper(_BaseGrouper): return result, counts -cdef inline _extract_result(object res): +cdef inline _extract_result(object res, bint squeeze=True): """ extract the result object, it might be a 0-dim ndarray or a len-1 0-dim, or a scalar """ if (not _is_sparse_array(res) and hasattr(res, 'values') and util.is_array(res.values)): res = res.values - if not np.isscalar(res): - if util.is_array(res): - if res.ndim == 0: - res = res.item() - elif res.ndim == 1 and len(res) == 1: - res = res[0] + if util.is_array(res): + if res.ndim == 0: + res = res.item() + elif squeeze and res.ndim == 1 and len(res) == 1: + res = res[0] return res
Working towards ironing out the small differences between several places that do roughly the same extraction. Getting the pure-python versions will be appreciably harder, kept separate. This avoids an unnecessary `np.isscalar` call.
https://api.github.com/repos/pandas-dev/pandas/pulls/29702
2019-11-19T01:33:24Z
2019-11-19T13:20:14Z
2019-11-19T13:20:14Z
2019-11-19T15:19:50Z
format replaced with f-strings
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 31563e4bccbb7..a3e2266184e2a 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -303,8 +303,7 @@ def _aggregate_multiple_funcs(self, arg, _level): obj = self if name in results: raise SpecificationError( - "Function names must be unique, found multiple named " - "{name}".format(name=name) + f"Function names must be unique, found multiple named {name}" ) # reset the cache so that we @@ -528,7 +527,7 @@ def nunique(self, dropna: bool = True) -> Series: try: sorter = np.lexsort((val, ids)) except TypeError: # catches object dtypes - msg = "val.dtype must be object, got {}".format(val.dtype) + msg = f"val.dtype must be object, got {val.dtype}" assert val.dtype == object, msg val, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((val, ids)) @@ -1502,8 +1501,8 @@ def filter(self, func, dropna=True, *args, **kwargs): else: # non scalars aren't allowed raise TypeError( - "filter function returned a {typ}, " - "but expected a scalar bool".format(typ=type(res).__name__) + f"filter function returned a {type(res).__name__}, " + "but expected a scalar bool" ) return self._apply_filter(indices, dropna) @@ -1865,7 +1864,7 @@ def _managle_lambda_list(aggfuncs: Sequence[Any]) -> Sequence[Any]: for aggfunc in aggfuncs: if com.get_callable_name(aggfunc) == "<lambda>": aggfunc = partial(aggfunc) - aggfunc.__name__ = "<lambda_{}>".format(i) + aggfunc.__name__ = f"<lambda_{i}>" i += 1 mangled_aggfuncs.append(aggfunc) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 99a4942df4f7f..d4c39200dc0af 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -556,9 +556,7 @@ def __getattr__(self, attr): return self[attr] raise AttributeError( - "'{typ}' object has no attribute '{attr}'".format( - typ=type(self).__name__, attr=attr - ) + f"'{type(self).__name__}' object has no attribute '{attr}'" ) @Substitution( @@ -1751,7 +1749,7 @@ def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFra raise ValueError( "For a DataFrame groupby, dropna must be " "either None, 'any' or 'all', " - "(was passed {dropna}).".format(dropna=dropna) + f"(was passed {dropna})." ) # old behaviour, but with all and any support for DataFrames. @@ -2488,7 +2486,7 @@ def get_groupby( klass = DataFrameGroupBy else: - raise TypeError("invalid type: {obj}".format(obj=obj)) + raise TypeError(f"invalid type: {obj}") return klass( obj=obj, diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index c37617b1f1f7f..2b946d1ff0a7a 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -173,9 +173,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): ax = self._grouper.take(obj.index) else: if key not in obj._info_axis: - raise KeyError( - "The grouper name {key} is not found".format(key=key) - ) + raise KeyError(f"The grouper name {key} is not found") ax = Index(obj[key], name=key) else: @@ -191,9 +189,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): else: if level not in (0, ax.name): - raise ValueError( - "The level {level} is not valid".format(level=level) - ) + raise ValueError(f"The level {level} is not valid") # possibly sort if (self.sort or sort) and not ax.is_monotonic: @@ -212,13 +208,13 @@ def groups(self): def __repr__(self) -> str: attrs_list = ( - "{name}={val!r}".format(name=attr_name, val=getattr(self, attr_name)) + f"{attr_name}={getattr(self, attr_name)!r}" for attr_name in self._attributes if getattr(self, attr_name) is not None ) attrs = ", ".join(attrs_list) cls_name = self.__class__.__name__ - return "{cls}({attrs})".format(cls=cls_name, attrs=attrs) + return f"{cls_name}({attrs})" class Grouping: @@ -280,9 +276,7 @@ def __init__( if level is not None: if not isinstance(level, int): if level not in index.names: - raise AssertionError( - "Level {level} not in index".format(level=level) - ) + raise AssertionError(f"Level {level} not in index") level = index.names.index(level) if self.name is None: @@ -350,17 +344,16 @@ def __init__( ): if getattr(self.grouper, "ndim", 1) != 1: t = self.name or str(type(self.grouper)) - raise ValueError("Grouper for '{t}' not 1-dimensional".format(t=t)) + raise ValueError(f"Grouper for '{t}' not 1-dimensional") self.grouper = self.index.map(self.grouper) if not ( hasattr(self.grouper, "__len__") and len(self.grouper) == len(self.index) ): + grper = pprint_thing(self.grouper) errmsg = ( "Grouper result violates len(labels) == " - "len(data)\nresult: {grper}".format( - grper=pprint_thing(self.grouper) - ) + f"len(data)\nresult: {grper}" ) self.grouper = None # Try for sanity raise AssertionError(errmsg) @@ -375,7 +368,7 @@ def __init__( self.grouper = self.grouper.astype("timedelta64[ns]") def __repr__(self) -> str: - return "Grouping({name})".format(name=self.name) + return f"Grouping({self.name})" def __iter__(self): return iter(self.indices) @@ -500,11 +493,7 @@ def get_grouper( if isinstance(level, str): if obj.index.name != level: - raise ValueError( - "level name {level} is not the name of the index".format( - level=level - ) - ) + raise ValueError(f"level name {level} is not the name of the index") elif level > 0 or level < -1: raise ValueError("level > 0 or level < -1 only valid with MultiIndex") @@ -636,12 +625,8 @@ def is_in_obj(gpr) -> bool: if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]: raise ValueError( - ( - "Length of grouper ({len_gpr}) and axis ({len_axis})" - " must be same length".format( - len_gpr=len(gpr), len_axis=obj.shape[axis] - ) - ) + f"Length of grouper ({len(gpr)}) and axis ({obj.shape[axis]})" + " must be same length" ) # create the Grouping diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 47ca2b2190ecf..e01b210c4d9a3 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -445,18 +445,16 @@ def _cython_operation( # categoricals are only 1d, so we # are not setup for dim transforming if is_categorical_dtype(values) or is_sparse(values): - raise NotImplementedError( - "{dtype} dtype not supported".format(dtype=values.dtype) - ) + raise NotImplementedError(f"{values.dtype} dtype not supported") elif is_datetime64_any_dtype(values): if how in ["add", "prod", "cumsum", "cumprod"]: raise NotImplementedError( - "datetime64 type does not support {how} operations".format(how=how) + f"datetime64 type does not support {how} operations" ) elif is_timedelta64_dtype(values): if how in ["prod", "cumprod"]: raise NotImplementedError( - "timedelta64 type does not support {how} operations".format(how=how) + f"timedelta64 type does not support {how} operations" ) if is_datetime64tz_dtype(values.dtype): @@ -509,9 +507,7 @@ def _cython_operation( out_dtype = "float" else: if is_numeric: - out_dtype = "{kind}{itemsize}".format( - kind=values.dtype.kind, itemsize=values.dtype.itemsize - ) + out_dtype = f"{values.dtype.kind}{values.dtype.itemsize}" else: out_dtype = "object"
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` ref #29547
https://api.github.com/repos/pandas-dev/pandas/pulls/29701
2019-11-18T23:57:08Z
2019-11-21T13:04:13Z
2019-11-21T13:04:13Z
2019-11-21T13:04:17Z
BUG: Index.get_loc raising incorrect error, closes #29189
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 54640ff576338..76aecf8a27a2a 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -453,7 +453,7 @@ Indexing - Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`) - :meth:`Index.union` could fail when the left contained duplicates (:issue:`28257`) - :meth:`Index.get_indexer_non_unique` could fail with `TypeError` in some cases, such as when searching for ints in a string index (:issue:`28257`) -- +- Bug in :meth:`Float64Index.get_loc` incorrectly raising ``TypeError`` instead of ``KeyError`` (:issue:`29189`) Missing ^^^^^^^ diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 92937ae56817c..2c69d6aaaf950 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -141,8 +141,12 @@ cdef class IndexEngine: if self.is_monotonic_increasing: values = self._get_index_values() - left = values.searchsorted(val, side='left') - right = values.searchsorted(val, side='right') + try: + left = values.searchsorted(val, side='left') + right = values.searchsorted(val, side='right') + except TypeError: + # e.g. GH#29189 get_loc(None) with a Float64Index + raise KeyError(val) diff = right - left if diff == 0: diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index b848e9caad9be..9ae07cb6645bb 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1953,6 +1953,16 @@ def test_groupby_only_none_group(): tm.assert_series_equal(actual, expected) +def test_groupby_duplicate_index(): + # GH#29189 the groupby call here used to raise + ser = pd.Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0]) + gb = ser.groupby(level=0) + + result = gb.mean() + expected = pd.Series([2, 5.5, 8], index=[2.0, 4.0, 5.0]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("bool_agg_func", ["any", "all"]) def test_bool_aggs_dup_column_labels(bool_agg_func): # 21668 diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index fc5753ec2955c..ea9bc91a13111 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -1209,3 +1209,16 @@ def test_1tuple_without_multiindex(): result = ser[key] expected = ser[key[0]] tm.assert_series_equal(result, expected) + + +def test_duplicate_index_mistyped_key_raises_keyerror(): + # GH#29189 float_index.get_loc(None) should raise KeyError, not TypeError + ser = pd.Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0]) + with pytest.raises(KeyError): + ser[None] + + with pytest.raises(KeyError): + ser.index.get_loc(None) + + with pytest.raises(KeyError): + ser.index._engine.get_loc(None)
- [x] closes #29189 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry cc @WillAyd
https://api.github.com/repos/pandas-dev/pandas/pulls/29700
2019-11-18T23:54:09Z
2019-11-25T23:45:28Z
2019-11-25T23:45:27Z
2019-11-25T23:49:23Z
REF: dont _try_cast for user-defined functions
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3b87150f544cf..db24be628dd67 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -511,6 +511,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` losing column name information when grouping by a categorical column (:issue:`28787`) - Bug in :meth:`DataFrameGroupBy.rolling().quantile()` ignoring ``interpolation`` keyword argument (:issue:`28779`) - Bug in :meth:`DataFrame.groupby` where ``any``, ``all``, ``nunique`` and transform functions would incorrectly handle duplicate column labels (:issue:`21668`) +- Reshaping ^^^^^^^^^ diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 071cd116ea982..34a8ed1fa7a83 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -226,6 +226,8 @@ def apply_raw(self): if "Function does not reduce" not in str(err): # catch only ValueError raised intentionally in libreduction raise + # We expect np.apply_along_axis to give a two-dimensional result, or + # also raise. result = np.apply_along_axis(self.f, self.axis, self.values) # TODO: mixed type case diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 7d3bf3d3dcd2f..40737a8137beb 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1110,12 +1110,12 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: if axis != obj._info_axis_number: for name, data in self: fres = func(data, *args, **kwargs) - result[name] = self._try_cast(fres, data) + result[name] = fres else: for name in self.indices: data = self.get_group(name, obj=obj) fres = func(data, *args, **kwargs) - result[name] = self._try_cast(fres, data) + result[name] = fres return self._wrap_frame_output(result, obj) @@ -1425,6 +1425,8 @@ def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame: output = [] for i, _ in enumerate(result.columns): res = algorithms.take_1d(result.iloc[:, i].values, ids) + # TODO: we have no test cases that get here with EA dtypes; + # try_cast may not be needed if EAs never get here if cast: res = self._try_cast(res, obj.iloc[:, i]) output.append(res)
Also add a whatsnew note for #29641 and a comment in core.apply that ive been meaning to get in
https://api.github.com/repos/pandas-dev/pandas/pulls/29698
2019-11-18T23:05:21Z
2019-11-21T13:07:58Z
2019-11-21T13:07:58Z
2019-11-21T16:02:06Z
CI: Use conda for 3.8 build
diff --git a/.travis.yml b/.travis.yml index 048736e4bf1d0..0acd386eea9ed 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,11 +30,9 @@ matrix: - python: 3.5 include: - - dist: bionic - # 18.04 - python: 3.8.0 + - dist: trusty env: - - JOB="3.8-dev" PATTERN="(not slow and not network)" + - JOB="3.8" ENV_FILE="ci/deps/travis-38.yaml" PATTERN="(not slow and not network)" - dist: trusty env: @@ -88,7 +86,7 @@ install: script: - echo "script start" - echo "$JOB" - - if [ "$JOB" != "3.8-dev" ]; then source activate pandas-dev; fi + - source activate pandas-dev - ci/run_tests.sh after_script: diff --git a/ci/build38.sh b/ci/build38.sh deleted file mode 100644 index 66eb5cad38475..0000000000000 --- a/ci/build38.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash -e -# Special build for python3.8 until numpy puts its own wheels up - -sudo apt-get install build-essential gcc xvfb -pip install --no-deps -U pip wheel setuptools -pip install python-dateutil pytz cython pytest pytest-xdist hypothesis - -# Possible alternative for getting numpy: -pip install --pre -f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com/ numpy - -python setup.py build_ext -inplace -python -m pip install -v --no-build-isolation -e . - -python -c "import sys; print(sys.version_info)" -python -c "import pandas as pd" -python -c "import hypothesis" - -# TODO: Is there anything else in setup_env that we really want to do? -# ci/setup_env.sh diff --git a/ci/deps/travis-38.yaml b/ci/deps/travis-38.yaml new file mode 100644 index 0000000000000..bd62ffa9248fe --- /dev/null +++ b/ci/deps/travis-38.yaml @@ -0,0 +1,16 @@ +name: pandas-dev +channels: + - defaults + - conda-forge +dependencies: + - python=3.8.* + - cython>=0.29.13 + - numpy + - python-dateutil + - nomkl + - pytz + # universal + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 + - hypothesis>=3.58.0 + - pip diff --git a/ci/setup_env.sh b/ci/setup_env.sh index 0e8d6fb7cd35a..3d79c0cfd7000 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -1,10 +1,5 @@ #!/bin/bash -e -if [ "$JOB" == "3.8-dev" ]; then - /bin/bash ci/build38.sh - exit 0 -fi - # edit the locale file if needed if [ -n "$LOCALE_OVERRIDE" ]; then echo "Adding locale to the first line of pandas/__init__.py"
Closes https://github.com/pandas-dev/pandas/issues/29001
https://api.github.com/repos/pandas-dev/pandas/pulls/29696
2019-11-18T19:01:52Z
2019-11-19T13:19:16Z
2019-11-19T13:19:16Z
2019-11-19T14:48:51Z
TST: Split pandas/tests/frame/test_indexing into a directory (#29544)
diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py new file mode 100644 index 0000000000000..b595e48797d41 --- /dev/null +++ b/pandas/tests/frame/indexing/test_categorical.py @@ -0,0 +1,388 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas as pd +from pandas import Categorical, DataFrame, Index, Series +import pandas.util.testing as tm + + +class TestDataFrameIndexingCategorical: + def test_assignment(self): + # assignment + df = DataFrame( + {"value": np.array(np.random.randint(0, 10000, 100), dtype="int32")} + ) + labels = Categorical( + ["{0} - {1}".format(i, i + 499) for i in range(0, 10000, 500)] + ) + + df = df.sort_values(by=["value"], ascending=True) + s = pd.cut(df.value, range(0, 10500, 500), right=False, labels=labels) + d = s.values + df["D"] = d + str(df) + + result = df.dtypes + expected = Series( + [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], + index=["value", "D"], + ) + tm.assert_series_equal(result, expected) + + df["E"] = s + str(df) + + result = df.dtypes + expected = Series( + [ + np.dtype("int32"), + CategoricalDtype(categories=labels, ordered=False), + CategoricalDtype(categories=labels, ordered=False), + ], + index=["value", "D", "E"], + ) + tm.assert_series_equal(result, expected) + + result1 = df["D"] + result2 = df["E"] + tm.assert_categorical_equal(result1._data._block.values, d) + + # sorting + s.name = "E" + tm.assert_series_equal(result2.sort_index(), s.sort_index()) + + cat = Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) + df = DataFrame(Series(cat)) + + def test_assigning_ops(self): + # systematically test the assigning operations: + # for all slicing ops: + # for value in categories and value not in categories: + + # - assign a single value -> exp_single_cats_value + + # - assign a complete row (mixed values) -> exp_single_row + + # assign multiple rows (mixed values) (-> array) -> exp_multi_row + + # assign a part of a column with dtype == categorical -> + # exp_parts_cats_col + + # assign a part of a column with dtype != categorical -> + # exp_parts_cats_col + + cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) + idx = Index(["h", "i", "j", "k", "l", "m", "n"]) + values = [1, 1, 1, 1, 1, 1, 1] + orig = DataFrame({"cats": cats, "values": values}, index=idx) + + # the expected values + # changed single row + cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) + idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values1 = [1, 1, 2, 1, 1, 1, 1] + exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1) + + # changed multiple rows + cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) + idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values2 = [1, 1, 2, 2, 1, 1, 1] + exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) + + # changed part of the cats column + cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) + idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values3 = [1, 1, 1, 1, 1, 1, 1] + exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3) + + # changed single value in cats col + cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) + idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values4 = [1, 1, 1, 1, 1, 1, 1] + exp_single_cats_value = DataFrame( + {"cats": cats4, "values": values4}, index=idx4 + ) + + # iloc + # ############### + # - assign a single value -> exp_single_cats_value + df = orig.copy() + df.iloc[2, 0] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + df = orig.copy() + df.iloc[df.index == "j", 0] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + # - assign a single value not in the current categories set + with pytest.raises(ValueError): + df = orig.copy() + df.iloc[2, 0] = "c" + + # - assign a complete row (mixed values) -> exp_single_row + df = orig.copy() + df.iloc[2, :] = ["b", 2] + tm.assert_frame_equal(df, exp_single_row) + + # - assign a complete row (mixed values) not in categories set + with pytest.raises(ValueError): + df = orig.copy() + df.iloc[2, :] = ["c", 2] + + # - assign multiple rows (mixed values) -> exp_multi_row + df = orig.copy() + df.iloc[2:4, :] = [["b", 2], ["b", 2]] + tm.assert_frame_equal(df, exp_multi_row) + + with pytest.raises(ValueError): + df = orig.copy() + df.iloc[2:4, :] = [["c", 2], ["c", 2]] + + # assign a part of a column with dtype == categorical -> + # exp_parts_cats_col + df = orig.copy() + df.iloc[2:4, 0] = Categorical(["b", "b"], categories=["a", "b"]) + tm.assert_frame_equal(df, exp_parts_cats_col) + + with pytest.raises(ValueError): + # different categories -> not sure if this should fail or pass + df = orig.copy() + df.iloc[2:4, 0] = Categorical(list("bb"), categories=list("abc")) + + with pytest.raises(ValueError): + # different values + df = orig.copy() + df.iloc[2:4, 0] = Categorical(list("cc"), categories=list("abc")) + + # assign a part of a column with dtype != categorical -> + # exp_parts_cats_col + df = orig.copy() + df.iloc[2:4, 0] = ["b", "b"] + tm.assert_frame_equal(df, exp_parts_cats_col) + + with pytest.raises(ValueError): + df.iloc[2:4, 0] = ["c", "c"] + + # loc + # ############## + # - assign a single value -> exp_single_cats_value + df = orig.copy() + df.loc["j", "cats"] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + df = orig.copy() + df.loc[df.index == "j", "cats"] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + # - assign a single value not in the current categories set + with pytest.raises(ValueError): + df = orig.copy() + df.loc["j", "cats"] = "c" + + # - assign a complete row (mixed values) -> exp_single_row + df = orig.copy() + df.loc["j", :] = ["b", 2] + tm.assert_frame_equal(df, exp_single_row) + + # - assign a complete row (mixed values) not in categories set + with pytest.raises(ValueError): + df = orig.copy() + df.loc["j", :] = ["c", 2] + + # - assign multiple rows (mixed values) -> exp_multi_row + df = orig.copy() + df.loc["j":"k", :] = [["b", 2], ["b", 2]] + tm.assert_frame_equal(df, exp_multi_row) + + with pytest.raises(ValueError): + df = orig.copy() + df.loc["j":"k", :] = [["c", 2], ["c", 2]] + + # assign a part of a column with dtype == categorical -> + # exp_parts_cats_col + df = orig.copy() + df.loc["j":"k", "cats"] = Categorical(["b", "b"], categories=["a", "b"]) + tm.assert_frame_equal(df, exp_parts_cats_col) + + with pytest.raises(ValueError): + # different categories -> not sure if this should fail or pass + df = orig.copy() + df.loc["j":"k", "cats"] = Categorical( + ["b", "b"], categories=["a", "b", "c"] + ) + + with pytest.raises(ValueError): + # different values + df = orig.copy() + df.loc["j":"k", "cats"] = Categorical( + ["c", "c"], categories=["a", "b", "c"] + ) + + # assign a part of a column with dtype != categorical -> + # exp_parts_cats_col + df = orig.copy() + df.loc["j":"k", "cats"] = ["b", "b"] + tm.assert_frame_equal(df, exp_parts_cats_col) + + with pytest.raises(ValueError): + df.loc["j":"k", "cats"] = ["c", "c"] + + # loc + # ############## + # - assign a single value -> exp_single_cats_value + df = orig.copy() + df.loc["j", df.columns[0]] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + df = orig.copy() + df.loc[df.index == "j", df.columns[0]] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + # - assign a single value not in the current categories set + with pytest.raises(ValueError): + df = orig.copy() + df.loc["j", df.columns[0]] = "c" + + # - assign a complete row (mixed values) -> exp_single_row + df = orig.copy() + df.loc["j", :] = ["b", 2] + tm.assert_frame_equal(df, exp_single_row) + + # - assign a complete row (mixed values) not in categories set + with pytest.raises(ValueError): + df = orig.copy() + df.loc["j", :] = ["c", 2] + + # - assign multiple rows (mixed values) -> exp_multi_row + df = orig.copy() + df.loc["j":"k", :] = [["b", 2], ["b", 2]] + tm.assert_frame_equal(df, exp_multi_row) + + with pytest.raises(ValueError): + df = orig.copy() + df.loc["j":"k", :] = [["c", 2], ["c", 2]] + + # assign a part of a column with dtype == categorical -> + # exp_parts_cats_col + df = orig.copy() + df.loc["j":"k", df.columns[0]] = Categorical(["b", "b"], categories=["a", "b"]) + tm.assert_frame_equal(df, exp_parts_cats_col) + + with pytest.raises(ValueError): + # different categories -> not sure if this should fail or pass + df = orig.copy() + df.loc["j":"k", df.columns[0]] = Categorical( + ["b", "b"], categories=["a", "b", "c"] + ) + + with pytest.raises(ValueError): + # different values + df = orig.copy() + df.loc["j":"k", df.columns[0]] = Categorical( + ["c", "c"], categories=["a", "b", "c"] + ) + + # assign a part of a column with dtype != categorical -> + # exp_parts_cats_col + df = orig.copy() + df.loc["j":"k", df.columns[0]] = ["b", "b"] + tm.assert_frame_equal(df, exp_parts_cats_col) + + with pytest.raises(ValueError): + df.loc["j":"k", df.columns[0]] = ["c", "c"] + + # iat + df = orig.copy() + df.iat[2, 0] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + # - assign a single value not in the current categories set + with pytest.raises(ValueError): + df = orig.copy() + df.iat[2, 0] = "c" + + # at + # - assign a single value -> exp_single_cats_value + df = orig.copy() + df.at["j", "cats"] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + # - assign a single value not in the current categories set + with pytest.raises(ValueError): + df = orig.copy() + df.at["j", "cats"] = "c" + + # fancy indexing + catsf = Categorical( + ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] + ) + idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) + valuesf = [1, 1, 3, 3, 1, 1, 1] + df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) + + exp_fancy = exp_multi_row.copy() + exp_fancy["cats"].cat.set_categories(["a", "b", "c"], inplace=True) + + df[df["cats"] == "c"] = ["b", 2] + # category c is kept in .categories + tm.assert_frame_equal(df, exp_fancy) + + # set_value + df = orig.copy() + df.at["j", "cats"] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + with pytest.raises(ValueError): + df = orig.copy() + df.at["j", "cats"] = "c" + + # Assigning a Category to parts of a int/... column uses the values of + # the Categorical + df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) + exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")}) + df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"]) + df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"]) + tm.assert_frame_equal(df, exp) + + def test_functions_no_warnings(self): + df = DataFrame({"value": np.random.randint(0, 100, 20)}) + labels = ["{0} - {1}".format(i, i + 9) for i in range(0, 100, 10)] + with tm.assert_produces_warning(False): + df["group"] = pd.cut( + df.value, range(0, 105, 10), right=False, labels=labels + ) + + def test_loc_indexing_preserves_index_category_dtype(self): + # GH 15166 + df = DataFrame( + data=np.arange(2, 22, 2), + index=pd.MultiIndex( + levels=[pd.CategoricalIndex(["a", "b"]), range(10)], + codes=[[0] * 5 + [1] * 5, range(10)], + names=["Index1", "Index2"], + ), + ) + + expected = pd.CategoricalIndex( + ["a", "b"], + categories=["a", "b"], + ordered=False, + name="Index1", + dtype="category", + ) + + result = df.index.levels[0] + tm.assert_index_equal(result, expected) + + result = df.loc[["a"]].index.levels[0] + tm.assert_index_equal(result, expected) + + def test_wrong_length_cat_dtype_raises(self): + # GH29523 + cat = pd.Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) + df = pd.DataFrame({"bar": range(10)}) + err = "Length of values does not match length of index" + with pytest.raises(ValueError, match=err): + df["foo"] = cat diff --git a/pandas/tests/frame/indexing/test_datetime.py b/pandas/tests/frame/indexing/test_datetime.py new file mode 100644 index 0000000000000..bde35c04acf4f --- /dev/null +++ b/pandas/tests/frame/indexing/test_datetime.py @@ -0,0 +1,62 @@ +import pandas as pd +from pandas import DataFrame, Index, Series, date_range, notna +import pandas.util.testing as tm + + +class TestDataFrameIndexingDatetimeWithTZ: + def test_setitem(self, timezone_frame): + + df = timezone_frame + idx = df["B"].rename("foo") + + # setitem + df["C"] = idx + tm.assert_series_equal(df["C"], Series(idx, name="C")) + + df["D"] = "foo" + df["D"] = idx + tm.assert_series_equal(df["D"], Series(idx, name="D")) + del df["D"] + + # assert that A & C are not sharing the same base (e.g. they + # are copies) + b1 = df._data.blocks[1] + b2 = df._data.blocks[2] + tm.assert_extension_array_equal(b1.values, b2.values) + assert id(b1.values._data.base) != id(b2.values._data.base) + + # with nan + df2 = df.copy() + df2.iloc[1, 1] = pd.NaT + df2.iloc[1, 2] = pd.NaT + result = df2["B"] + tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) + tm.assert_series_equal(df2.dtypes, df.dtypes) + + def test_set_reset(self): + + idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") + + # set/reset + df = DataFrame({"A": [0, 1, 2]}, index=idx) + result = df.reset_index() + assert result["foo"].dtype, "M8[ns, US/Eastern" + + df = result.set_index("foo") + tm.assert_index_equal(df.index, idx) + + def test_transpose(self, timezone_frame): + + result = timezone_frame.T + expected = DataFrame(timezone_frame.values.T) + expected.index = ["A", "B", "C"] + tm.assert_frame_equal(result, expected) + + def test_scalar_assignment(self): + # issue #19843 + df = pd.DataFrame(index=(0, 1, 2)) + df["now"] = pd.Timestamp("20130101", tz="UTC") + expected = pd.DataFrame( + {"now": pd.Timestamp("20130101", tz="UTC")}, index=[0, 1, 2] + ) + tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py similarity index 73% rename from pandas/tests/frame/test_indexing.py rename to pandas/tests/frame/indexing/test_indexing.py index e37f734c6235e..24a431fe42cf8 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -7,12 +7,10 @@ from pandas._libs.tslib import iNaT -from pandas.core.dtypes.common import is_float_dtype, is_integer, is_scalar -from pandas.core.dtypes.dtypes import CategoricalDtype +from pandas.core.dtypes.common import is_float_dtype, is_integer import pandas as pd from pandas import ( - Categorical, DataFrame, DatetimeIndex, Index, @@ -2695,576 +2693,6 @@ def test_boolean_indexing_mixed(self): with pytest.raises(TypeError, match=msg): df[df > 0.3] = 1 - def test_where(self, float_string_frame, mixed_float_frame, mixed_int_frame): - default_frame = DataFrame(np.random.randn(5, 3), columns=["A", "B", "C"]) - - def _safe_add(df): - # only add to the numeric items - def is_ok(s): - return ( - issubclass(s.dtype.type, (np.integer, np.floating)) - and s.dtype != "uint8" - ) - - return DataFrame( - dict((c, s + 1) if is_ok(s) else (c, s) for c, s in df.items()) - ) - - def _check_get(df, cond, check_dtypes=True): - other1 = _safe_add(df) - rs = df.where(cond, other1) - rs2 = df.where(cond.values, other1) - for k, v in rs.items(): - exp = Series(np.where(cond[k], df[k], other1[k]), index=v.index) - tm.assert_series_equal(v, exp, check_names=False) - tm.assert_frame_equal(rs, rs2) - - # dtypes - if check_dtypes: - assert (rs.dtypes == df.dtypes).all() - - # check getting - for df in [ - default_frame, - float_string_frame, - mixed_float_frame, - mixed_int_frame, - ]: - if df is float_string_frame: - with pytest.raises(TypeError): - df > 0 - continue - cond = df > 0 - _check_get(df, cond) - - # upcasting case (GH # 2794) - df = DataFrame( - { - c: Series([1] * 3, dtype=c) - for c in ["float32", "float64", "int32", "int64"] - } - ) - df.iloc[1, :] = 0 - result = df.dtypes - expected = Series( - [ - np.dtype("float32"), - np.dtype("float64"), - np.dtype("int32"), - np.dtype("int64"), - ], - index=["float32", "float64", "int32", "int64"], - ) - - # when we don't preserve boolean casts - # - # expected = Series({ 'float32' : 1, 'float64' : 3 }) - - tm.assert_series_equal(result, expected) - - # aligning - def _check_align(df, cond, other, check_dtypes=True): - rs = df.where(cond, other) - for i, k in enumerate(rs.columns): - result = rs[k] - d = df[k].values - c = cond[k].reindex(df[k].index).fillna(False).values - - if is_scalar(other): - o = other - else: - if isinstance(other, np.ndarray): - o = Series(other[:, i], index=result.index).values - else: - o = other[k].values - - new_values = d if c.all() else np.where(c, d, o) - expected = Series(new_values, index=result.index, name=k) - - # since we can't always have the correct numpy dtype - # as numpy doesn't know how to downcast, don't check - tm.assert_series_equal(result, expected, check_dtype=False) - - # dtypes - # can't check dtype when other is an ndarray - - if check_dtypes and not isinstance(other, np.ndarray): - assert (rs.dtypes == df.dtypes).all() - - for df in [float_string_frame, mixed_float_frame, mixed_int_frame]: - if df is float_string_frame: - with pytest.raises(TypeError): - df > 0 - continue - - # other is a frame - cond = (df > 0)[1:] - _check_align(df, cond, _safe_add(df)) - - # check other is ndarray - cond = df > 0 - _check_align(df, cond, (_safe_add(df).values)) - - # integers are upcast, so don't check the dtypes - cond = df > 0 - check_dtypes = all(not issubclass(s.type, np.integer) for s in df.dtypes) - _check_align(df, cond, np.nan, check_dtypes=check_dtypes) - - # invalid conditions - df = default_frame - err1 = (df + 1).values[0:2, :] - msg = "other must be the same shape as self when an ndarray" - with pytest.raises(ValueError, match=msg): - df.where(cond, err1) - - err2 = cond.iloc[:2, :].values - other1 = _safe_add(df) - msg = "Array conditional must be same shape as self" - with pytest.raises(ValueError, match=msg): - df.where(err2, other1) - - with pytest.raises(ValueError, match=msg): - df.mask(True) - with pytest.raises(ValueError, match=msg): - df.mask(0) - - # where inplace - def _check_set(df, cond, check_dtypes=True): - dfi = df.copy() - econd = cond.reindex_like(df).fillna(True) - expected = dfi.mask(~econd) - - dfi.where(cond, np.nan, inplace=True) - tm.assert_frame_equal(dfi, expected) - - # dtypes (and confirm upcasts)x - if check_dtypes: - for k, v in df.dtypes.items(): - if issubclass(v.type, np.integer) and not cond[k].all(): - v = np.dtype("float64") - assert dfi[k].dtype == v - - for df in [ - default_frame, - float_string_frame, - mixed_float_frame, - mixed_int_frame, - ]: - if df is float_string_frame: - with pytest.raises(TypeError): - df > 0 - continue - - cond = df > 0 - _check_set(df, cond) - - cond = df >= 0 - _check_set(df, cond) - - # aligning - cond = (df >= 0)[1:] - _check_set(df, cond) - - # GH 10218 - # test DataFrame.where with Series slicing - df = DataFrame({"a": range(3), "b": range(4, 7)}) - result = df.where(df["a"] == 1) - expected = df[df["a"] == 1].reindex(df.index) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("klass", [list, tuple, np.array]) - def test_where_array_like(self, klass): - # see gh-15414 - df = DataFrame({"a": [1, 2, 3]}) - cond = [[False], [True], [True]] - expected = DataFrame({"a": [np.nan, 2, 3]}) - - result = df.where(klass(cond)) - tm.assert_frame_equal(result, expected) - - df["b"] = 2 - expected["b"] = [2, np.nan, 2] - cond = [[False, True], [True, False], [True, True]] - - result = df.where(klass(cond)) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "cond", - [ - [[1], [0], [1]], - Series([[2], [5], [7]]), - DataFrame({"a": [2, 5, 7]}), - [["True"], ["False"], ["True"]], - [[Timestamp("2017-01-01")], [pd.NaT], [Timestamp("2017-01-02")]], - ], - ) - def test_where_invalid_input_single(self, cond): - # see gh-15414: only boolean arrays accepted - df = DataFrame({"a": [1, 2, 3]}) - msg = "Boolean array expected for the condition" - - with pytest.raises(ValueError, match=msg): - df.where(cond) - - @pytest.mark.parametrize( - "cond", - [ - [[0, 1], [1, 0], [1, 1]], - Series([[0, 2], [5, 0], [4, 7]]), - [["False", "True"], ["True", "False"], ["True", "True"]], - DataFrame({"a": [2, 5, 7], "b": [4, 8, 9]}), - [ - [pd.NaT, Timestamp("2017-01-01")], - [Timestamp("2017-01-02"), pd.NaT], - [Timestamp("2017-01-03"), Timestamp("2017-01-03")], - ], - ], - ) - def test_where_invalid_input_multiple(self, cond): - # see gh-15414: only boolean arrays accepted - df = DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]}) - msg = "Boolean array expected for the condition" - - with pytest.raises(ValueError, match=msg): - df.where(cond) - - def test_where_dataframe_col_match(self): - df = DataFrame([[1, 2, 3], [4, 5, 6]]) - cond = DataFrame([[True, False, True], [False, False, True]]) - - result = df.where(cond) - expected = DataFrame([[1.0, np.nan, 3], [np.nan, np.nan, 6]]) - tm.assert_frame_equal(result, expected) - - # this *does* align, though has no matching columns - cond.columns = ["a", "b", "c"] - result = df.where(cond) - expected = DataFrame(np.nan, index=df.index, columns=df.columns) - tm.assert_frame_equal(result, expected) - - def test_where_ndframe_align(self): - msg = "Array conditional must be same shape as self" - df = DataFrame([[1, 2, 3], [4, 5, 6]]) - - cond = [True] - with pytest.raises(ValueError, match=msg): - df.where(cond) - - expected = DataFrame([[1, 2, 3], [np.nan, np.nan, np.nan]]) - - out = df.where(Series(cond)) - tm.assert_frame_equal(out, expected) - - cond = np.array([False, True, False, True]) - with pytest.raises(ValueError, match=msg): - df.where(cond) - - expected = DataFrame([[np.nan, np.nan, np.nan], [4, 5, 6]]) - - out = df.where(Series(cond)) - tm.assert_frame_equal(out, expected) - - def test_where_bug(self): - # see gh-2793 - df = DataFrame( - {"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]}, dtype="float64" - ) - expected = DataFrame( - {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]}, - dtype="float64", - ) - result = df.where(df > 2, np.nan) - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(result > 2, np.nan, inplace=True) - tm.assert_frame_equal(result, expected) - - def test_where_bug_mixed(self, sint_dtype): - # see gh-2793 - df = DataFrame( - { - "a": np.array([1, 2, 3, 4], dtype=sint_dtype), - "b": np.array([4.0, 3.0, 2.0, 1.0], dtype="float64"), - } - ) - - expected = DataFrame( - {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]}, - dtype="float64", - ) - - result = df.where(df > 2, np.nan) - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(result > 2, np.nan, inplace=True) - tm.assert_frame_equal(result, expected) - - def test_where_bug_transposition(self): - # see gh-7506 - a = DataFrame({0: [1, 2], 1: [3, 4], 2: [5, 6]}) - b = DataFrame({0: [np.nan, 8], 1: [9, np.nan], 2: [np.nan, np.nan]}) - do_not_replace = b.isna() | (a > b) - - expected = a.copy() - expected[~do_not_replace] = b - - result = a.where(do_not_replace, b) - tm.assert_frame_equal(result, expected) - - a = DataFrame({0: [4, 6], 1: [1, 0]}) - b = DataFrame({0: [np.nan, 3], 1: [3, np.nan]}) - do_not_replace = b.isna() | (a > b) - - expected = a.copy() - expected[~do_not_replace] = b - - result = a.where(do_not_replace, b) - tm.assert_frame_equal(result, expected) - - def test_where_datetime(self): - - # GH 3311 - df = DataFrame( - dict( - A=date_range("20130102", periods=5), - B=date_range("20130104", periods=5), - C=np.random.randn(5), - ) - ) - - stamp = datetime(2013, 1, 3) - with pytest.raises(TypeError): - df > stamp - - result = df[df.iloc[:, :-1] > stamp] - - expected = df.copy() - expected.loc[[0, 1], "A"] = np.nan - expected.loc[:, "C"] = np.nan - tm.assert_frame_equal(result, expected) - - def test_where_none(self): - # GH 4667 - # setting with None changes dtype - df = DataFrame({"series": Series(range(10))}).astype(float) - df[df > 7] = None - expected = DataFrame( - {"series": Series([0, 1, 2, 3, 4, 5, 6, 7, np.nan, np.nan])} - ) - tm.assert_frame_equal(df, expected) - - # GH 7656 - df = DataFrame( - [ - {"A": 1, "B": np.nan, "C": "Test"}, - {"A": np.nan, "B": "Test", "C": np.nan}, - ] - ) - msg = "boolean setting on mixed-type" - - with pytest.raises(TypeError, match=msg): - df.where(~isna(df), None, inplace=True) - - def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self): - # see gh-21947 - df = pd.DataFrame(columns=["a"]) - cond = df.applymap(lambda x: x > 0) - - result = df.where(cond) - tm.assert_frame_equal(result, df) - - def test_where_align(self): - def create(): - df = DataFrame(np.random.randn(10, 3)) - df.iloc[3:5, 0] = np.nan - df.iloc[4:6, 1] = np.nan - df.iloc[5:8, 2] = np.nan - return df - - # series - df = create() - expected = df.fillna(df.mean()) - result = df.where(pd.notna(df), df.mean(), axis="columns") - tm.assert_frame_equal(result, expected) - - df.where(pd.notna(df), df.mean(), inplace=True, axis="columns") - tm.assert_frame_equal(df, expected) - - df = create().fillna(0) - expected = df.apply(lambda x, y: x.where(x > 0, y), y=df[0]) - result = df.where(df > 0, df[0], axis="index") - tm.assert_frame_equal(result, expected) - result = df.where(df > 0, df[0], axis="rows") - tm.assert_frame_equal(result, expected) - - # frame - df = create() - expected = df.fillna(1) - result = df.where( - pd.notna(df), DataFrame(1, index=df.index, columns=df.columns) - ) - tm.assert_frame_equal(result, expected) - - def test_where_complex(self): - # GH 6345 - expected = DataFrame([[1 + 1j, 2], [np.nan, 4 + 1j]], columns=["a", "b"]) - df = DataFrame([[1 + 1j, 2], [5 + 1j, 4 + 1j]], columns=["a", "b"]) - df[df.abs() >= 5] = np.nan - tm.assert_frame_equal(df, expected) - - def test_where_axis(self): - # GH 9736 - df = DataFrame(np.random.randn(2, 2)) - mask = DataFrame([[False, False], [False, False]]) - s = Series([0, 1]) - - expected = DataFrame([[0, 0], [1, 1]], dtype="float64") - result = df.where(mask, s, axis="index") - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(mask, s, axis="index", inplace=True) - tm.assert_frame_equal(result, expected) - - expected = DataFrame([[0, 1], [0, 1]], dtype="float64") - result = df.where(mask, s, axis="columns") - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(mask, s, axis="columns", inplace=True) - tm.assert_frame_equal(result, expected) - - # Upcast needed - df = DataFrame([[1, 2], [3, 4]], dtype="int64") - mask = DataFrame([[False, False], [False, False]]) - s = Series([0, np.nan]) - - expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64") - result = df.where(mask, s, axis="index") - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(mask, s, axis="index", inplace=True) - tm.assert_frame_equal(result, expected) - - expected = DataFrame([[0, np.nan], [0, np.nan]]) - result = df.where(mask, s, axis="columns") - tm.assert_frame_equal(result, expected) - - expected = DataFrame( - { - 0: np.array([0, 0], dtype="int64"), - 1: np.array([np.nan, np.nan], dtype="float64"), - } - ) - result = df.copy() - result.where(mask, s, axis="columns", inplace=True) - tm.assert_frame_equal(result, expected) - - # Multiple dtypes (=> multiple Blocks) - df = pd.concat( - [ - DataFrame(np.random.randn(10, 2)), - DataFrame(np.random.randint(0, 10, size=(10, 2)), dtype="int64"), - ], - ignore_index=True, - axis=1, - ) - mask = DataFrame(False, columns=df.columns, index=df.index) - s1 = Series(1, index=df.columns) - s2 = Series(2, index=df.index) - - result = df.where(mask, s1, axis="columns") - expected = DataFrame(1.0, columns=df.columns, index=df.index) - expected[2] = expected[2].astype("int64") - expected[3] = expected[3].astype("int64") - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(mask, s1, axis="columns", inplace=True) - tm.assert_frame_equal(result, expected) - - result = df.where(mask, s2, axis="index") - expected = DataFrame(2.0, columns=df.columns, index=df.index) - expected[2] = expected[2].astype("int64") - expected[3] = expected[3].astype("int64") - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.where(mask, s2, axis="index", inplace=True) - tm.assert_frame_equal(result, expected) - - # DataFrame vs DataFrame - d1 = df.copy().drop(1, axis=0) - expected = df.copy() - expected.loc[1, :] = np.nan - - result = df.where(mask, d1) - tm.assert_frame_equal(result, expected) - result = df.where(mask, d1, axis="index") - tm.assert_frame_equal(result, expected) - result = df.copy() - result.where(mask, d1, inplace=True) - tm.assert_frame_equal(result, expected) - result = df.copy() - result.where(mask, d1, inplace=True, axis="index") - tm.assert_frame_equal(result, expected) - - d2 = df.copy().drop(1, axis=1) - expected = df.copy() - expected.loc[:, 1] = np.nan - - result = df.where(mask, d2) - tm.assert_frame_equal(result, expected) - result = df.where(mask, d2, axis="columns") - tm.assert_frame_equal(result, expected) - result = df.copy() - result.where(mask, d2, inplace=True) - tm.assert_frame_equal(result, expected) - result = df.copy() - result.where(mask, d2, inplace=True, axis="columns") - tm.assert_frame_equal(result, expected) - - def test_where_callable(self): - # GH 12533 - df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) - result = df.where(lambda x: x > 4, lambda x: x + 1) - exp = DataFrame([[2, 3, 4], [5, 5, 6], [7, 8, 9]]) - tm.assert_frame_equal(result, exp) - tm.assert_frame_equal(result, df.where(df > 4, df + 1)) - - # return ndarray and scalar - result = df.where(lambda x: (x % 2 == 0).values, lambda x: 99) - exp = DataFrame([[99, 2, 99], [4, 99, 6], [99, 8, 99]]) - tm.assert_frame_equal(result, exp) - tm.assert_frame_equal(result, df.where(df % 2 == 0, 99)) - - # chain - result = (df + 2).where(lambda x: x > 8, lambda x: x + 10) - exp = DataFrame([[13, 14, 15], [16, 17, 18], [9, 10, 11]]) - tm.assert_frame_equal(result, exp) - tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10)) - - def test_where_tz_values(self, tz_naive_fixture): - df1 = DataFrame( - DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture), - columns=["date"], - ) - df2 = DataFrame( - DatetimeIndex(["20150103", "20150104", "20150105"], tz=tz_naive_fixture), - columns=["date"], - ) - mask = DataFrame([True, True, False], columns=["date"]) - exp = DataFrame( - DatetimeIndex(["20150101", "20150102", "20150105"], tz=tz_naive_fixture), - columns=["date"], - ) - result = df1.where(mask, df2) - tm.assert_frame_equal(exp, result) - def test_mask(self): df = DataFrame(np.random.randn(5, 3)) cond = df > 0 @@ -3402,65 +2830,6 @@ def test_interval_index(self): tm.assert_series_equal(result, expected) -class TestDataFrameIndexingDatetimeWithTZ: - def test_setitem(self, timezone_frame): - - df = timezone_frame - idx = df["B"].rename("foo") - - # setitem - df["C"] = idx - tm.assert_series_equal(df["C"], Series(idx, name="C")) - - df["D"] = "foo" - df["D"] = idx - tm.assert_series_equal(df["D"], Series(idx, name="D")) - del df["D"] - - # assert that A & C are not sharing the same base (e.g. they - # are copies) - b1 = df._data.blocks[1] - b2 = df._data.blocks[2] - tm.assert_extension_array_equal(b1.values, b2.values) - assert id(b1.values._data.base) != id(b2.values._data.base) - - # with nan - df2 = df.copy() - df2.iloc[1, 1] = pd.NaT - df2.iloc[1, 2] = pd.NaT - result = df2["B"] - tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) - tm.assert_series_equal(df2.dtypes, df.dtypes) - - def test_set_reset(self): - - idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") - - # set/reset - df = DataFrame({"A": [0, 1, 2]}, index=idx) - result = df.reset_index() - assert result["foo"].dtype, "M8[ns, US/Eastern" - - df = result.set_index("foo") - tm.assert_index_equal(df.index, idx) - - def test_transpose(self, timezone_frame): - - result = timezone_frame.T - expected = DataFrame(timezone_frame.values.T) - expected.index = ["A", "B", "C"] - tm.assert_frame_equal(result, expected) - - def test_scalar_assignment(self): - # issue #19843 - df = pd.DataFrame(index=(0, 1, 2)) - df["now"] = pd.Timestamp("20130101", tz="UTC") - expected = pd.DataFrame( - {"now": pd.Timestamp("20130101", tz="UTC")}, index=[0, 1, 2] - ) - tm.assert_frame_equal(df, expected) - - class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame): @@ -3509,383 +2878,3 @@ def test_transpose(self, uint64_frame): expected = DataFrame(uint64_frame.values.T) expected.index = ["A", "B"] tm.assert_frame_equal(result, expected) - - -class TestDataFrameIndexingCategorical: - def test_assignment(self): - # assignment - df = DataFrame( - {"value": np.array(np.random.randint(0, 10000, 100), dtype="int32")} - ) - labels = Categorical( - ["{0} - {1}".format(i, i + 499) for i in range(0, 10000, 500)] - ) - - df = df.sort_values(by=["value"], ascending=True) - s = pd.cut(df.value, range(0, 10500, 500), right=False, labels=labels) - d = s.values - df["D"] = d - str(df) - - result = df.dtypes - expected = Series( - [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], - index=["value", "D"], - ) - tm.assert_series_equal(result, expected) - - df["E"] = s - str(df) - - result = df.dtypes - expected = Series( - [ - np.dtype("int32"), - CategoricalDtype(categories=labels, ordered=False), - CategoricalDtype(categories=labels, ordered=False), - ], - index=["value", "D", "E"], - ) - tm.assert_series_equal(result, expected) - - result1 = df["D"] - result2 = df["E"] - tm.assert_categorical_equal(result1._data._block.values, d) - - # sorting - s.name = "E" - tm.assert_series_equal(result2.sort_index(), s.sort_index()) - - cat = Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) - df = DataFrame(Series(cat)) - - def test_assigning_ops(self): - # systematically test the assigning operations: - # for all slicing ops: - # for value in categories and value not in categories: - - # - assign a single value -> exp_single_cats_value - - # - assign a complete row (mixed values) -> exp_single_row - - # assign multiple rows (mixed values) (-> array) -> exp_multi_row - - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - - cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) - idx = Index(["h", "i", "j", "k", "l", "m", "n"]) - values = [1, 1, 1, 1, 1, 1, 1] - orig = DataFrame({"cats": cats, "values": values}, index=idx) - - # the expected values - # changed single row - cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) - idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values1 = [1, 1, 2, 1, 1, 1, 1] - exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1) - - # changed multiple rows - cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) - idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values2 = [1, 1, 2, 2, 1, 1, 1] - exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) - - # changed part of the cats column - cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) - idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values3 = [1, 1, 1, 1, 1, 1, 1] - exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3) - - # changed single value in cats col - cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) - idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values4 = [1, 1, 1, 1, 1, 1, 1] - exp_single_cats_value = DataFrame( - {"cats": cats4, "values": values4}, index=idx4 - ) - - # iloc - # ############### - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.iloc[2, 0] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - df = orig.copy() - df.iloc[df.index == "j", 0] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - with pytest.raises(ValueError): - df = orig.copy() - df.iloc[2, 0] = "c" - - # - assign a complete row (mixed values) -> exp_single_row - df = orig.copy() - df.iloc[2, :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - - # - assign a complete row (mixed values) not in categories set - with pytest.raises(ValueError): - df = orig.copy() - df.iloc[2, :] = ["c", 2] - - # - assign multiple rows (mixed values) -> exp_multi_row - df = orig.copy() - df.iloc[2:4, :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) - - with pytest.raises(ValueError): - df = orig.copy() - df.iloc[2:4, :] = [["c", 2], ["c", 2]] - - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - df = orig.copy() - df.iloc[2:4, 0] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError): - # different categories -> not sure if this should fail or pass - df = orig.copy() - df.iloc[2:4, 0] = Categorical(list("bb"), categories=list("abc")) - - with pytest.raises(ValueError): - # different values - df = orig.copy() - df.iloc[2:4, 0] = Categorical(list("cc"), categories=list("abc")) - - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - df = orig.copy() - df.iloc[2:4, 0] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError): - df.iloc[2:4, 0] = ["c", "c"] - - # loc - # ############## - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.loc["j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - df = orig.copy() - df.loc[df.index == "j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - with pytest.raises(ValueError): - df = orig.copy() - df.loc["j", "cats"] = "c" - - # - assign a complete row (mixed values) -> exp_single_row - df = orig.copy() - df.loc["j", :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - - # - assign a complete row (mixed values) not in categories set - with pytest.raises(ValueError): - df = orig.copy() - df.loc["j", :] = ["c", 2] - - # - assign multiple rows (mixed values) -> exp_multi_row - df = orig.copy() - df.loc["j":"k", :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) - - with pytest.raises(ValueError): - df = orig.copy() - df.loc["j":"k", :] = [["c", 2], ["c", 2]] - - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - df = orig.copy() - df.loc["j":"k", "cats"] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError): - # different categories -> not sure if this should fail or pass - df = orig.copy() - df.loc["j":"k", "cats"] = Categorical( - ["b", "b"], categories=["a", "b", "c"] - ) - - with pytest.raises(ValueError): - # different values - df = orig.copy() - df.loc["j":"k", "cats"] = Categorical( - ["c", "c"], categories=["a", "b", "c"] - ) - - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - df = orig.copy() - df.loc["j":"k", "cats"] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError): - df.loc["j":"k", "cats"] = ["c", "c"] - - # loc - # ############## - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.loc["j", df.columns[0]] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - df = orig.copy() - df.loc[df.index == "j", df.columns[0]] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - with pytest.raises(ValueError): - df = orig.copy() - df.loc["j", df.columns[0]] = "c" - - # - assign a complete row (mixed values) -> exp_single_row - df = orig.copy() - df.loc["j", :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - - # - assign a complete row (mixed values) not in categories set - with pytest.raises(ValueError): - df = orig.copy() - df.loc["j", :] = ["c", 2] - - # - assign multiple rows (mixed values) -> exp_multi_row - df = orig.copy() - df.loc["j":"k", :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) - - with pytest.raises(ValueError): - df = orig.copy() - df.loc["j":"k", :] = [["c", 2], ["c", 2]] - - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - df = orig.copy() - df.loc["j":"k", df.columns[0]] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError): - # different categories -> not sure if this should fail or pass - df = orig.copy() - df.loc["j":"k", df.columns[0]] = Categorical( - ["b", "b"], categories=["a", "b", "c"] - ) - - with pytest.raises(ValueError): - # different values - df = orig.copy() - df.loc["j":"k", df.columns[0]] = Categorical( - ["c", "c"], categories=["a", "b", "c"] - ) - - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - df = orig.copy() - df.loc["j":"k", df.columns[0]] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError): - df.loc["j":"k", df.columns[0]] = ["c", "c"] - - # iat - df = orig.copy() - df.iat[2, 0] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - with pytest.raises(ValueError): - df = orig.copy() - df.iat[2, 0] = "c" - - # at - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.at["j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - with pytest.raises(ValueError): - df = orig.copy() - df.at["j", "cats"] = "c" - - # fancy indexing - catsf = Categorical( - ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] - ) - idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) - valuesf = [1, 1, 3, 3, 1, 1, 1] - df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) - - exp_fancy = exp_multi_row.copy() - exp_fancy["cats"].cat.set_categories(["a", "b", "c"], inplace=True) - - df[df["cats"] == "c"] = ["b", 2] - # category c is kept in .categories - tm.assert_frame_equal(df, exp_fancy) - - # set_value - df = orig.copy() - df.at["j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - with pytest.raises(ValueError): - df = orig.copy() - df.at["j", "cats"] = "c" - - # Assigning a Category to parts of a int/... column uses the values of - # the Categorical - df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) - exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")}) - df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"]) - df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp) - - def test_functions_no_warnings(self): - df = DataFrame({"value": np.random.randint(0, 100, 20)}) - labels = ["{0} - {1}".format(i, i + 9) for i in range(0, 100, 10)] - with tm.assert_produces_warning(False): - df["group"] = pd.cut( - df.value, range(0, 105, 10), right=False, labels=labels - ) - - def test_loc_indexing_preserves_index_category_dtype(self): - # GH 15166 - df = DataFrame( - data=np.arange(2, 22, 2), - index=pd.MultiIndex( - levels=[pd.CategoricalIndex(["a", "b"]), range(10)], - codes=[[0] * 5 + [1] * 5, range(10)], - names=["Index1", "Index2"], - ), - ) - - expected = pd.CategoricalIndex( - ["a", "b"], - categories=["a", "b"], - ordered=False, - name="Index1", - dtype="category", - ) - - result = df.index.levels[0] - tm.assert_index_equal(result, expected) - - result = df.loc[["a"]].index.levels[0] - tm.assert_index_equal(result, expected) - - def test_wrong_length_cat_dtype_raises(self): - # GH29523 - cat = pd.Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) - df = pd.DataFrame({"bar": range(10)}) - err = "Length of values does not match length of index" - with pytest.raises(ValueError, match=err): - df["foo"] = cat diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py new file mode 100644 index 0000000000000..4fea190f28d7b --- /dev/null +++ b/pandas/tests/frame/indexing/test_where.py @@ -0,0 +1,582 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_scalar + +import pandas as pd +from pandas import DataFrame, DatetimeIndex, Series, Timestamp, date_range, isna +import pandas.util.testing as tm + + +class TestDataFrameIndexingWhere: + def test_where(self, float_string_frame, mixed_float_frame, mixed_int_frame): + default_frame = DataFrame(np.random.randn(5, 3), columns=["A", "B", "C"]) + + def _safe_add(df): + # only add to the numeric items + def is_ok(s): + return ( + issubclass(s.dtype.type, (np.integer, np.floating)) + and s.dtype != "uint8" + ) + + return DataFrame( + dict((c, s + 1) if is_ok(s) else (c, s) for c, s in df.items()) + ) + + def _check_get(df, cond, check_dtypes=True): + other1 = _safe_add(df) + rs = df.where(cond, other1) + rs2 = df.where(cond.values, other1) + for k, v in rs.items(): + exp = Series(np.where(cond[k], df[k], other1[k]), index=v.index) + tm.assert_series_equal(v, exp, check_names=False) + tm.assert_frame_equal(rs, rs2) + + # dtypes + if check_dtypes: + assert (rs.dtypes == df.dtypes).all() + + # check getting + for df in [ + default_frame, + float_string_frame, + mixed_float_frame, + mixed_int_frame, + ]: + if df is float_string_frame: + with pytest.raises(TypeError): + df > 0 + continue + cond = df > 0 + _check_get(df, cond) + + # upcasting case (GH # 2794) + df = DataFrame( + { + c: Series([1] * 3, dtype=c) + for c in ["float32", "float64", "int32", "int64"] + } + ) + df.iloc[1, :] = 0 + result = df.dtypes + expected = Series( + [ + np.dtype("float32"), + np.dtype("float64"), + np.dtype("int32"), + np.dtype("int64"), + ], + index=["float32", "float64", "int32", "int64"], + ) + + # when we don't preserve boolean casts + # + # expected = Series({ 'float32' : 1, 'float64' : 3 }) + + tm.assert_series_equal(result, expected) + + # aligning + def _check_align(df, cond, other, check_dtypes=True): + rs = df.where(cond, other) + for i, k in enumerate(rs.columns): + result = rs[k] + d = df[k].values + c = cond[k].reindex(df[k].index).fillna(False).values + + if is_scalar(other): + o = other + else: + if isinstance(other, np.ndarray): + o = Series(other[:, i], index=result.index).values + else: + o = other[k].values + + new_values = d if c.all() else np.where(c, d, o) + expected = Series(new_values, index=result.index, name=k) + + # since we can't always have the correct numpy dtype + # as numpy doesn't know how to downcast, don't check + tm.assert_series_equal(result, expected, check_dtype=False) + + # dtypes + # can't check dtype when other is an ndarray + + if check_dtypes and not isinstance(other, np.ndarray): + assert (rs.dtypes == df.dtypes).all() + + for df in [float_string_frame, mixed_float_frame, mixed_int_frame]: + if df is float_string_frame: + with pytest.raises(TypeError): + df > 0 + continue + + # other is a frame + cond = (df > 0)[1:] + _check_align(df, cond, _safe_add(df)) + + # check other is ndarray + cond = df > 0 + _check_align(df, cond, (_safe_add(df).values)) + + # integers are upcast, so don't check the dtypes + cond = df > 0 + check_dtypes = all(not issubclass(s.type, np.integer) for s in df.dtypes) + _check_align(df, cond, np.nan, check_dtypes=check_dtypes) + + # invalid conditions + df = default_frame + err1 = (df + 1).values[0:2, :] + msg = "other must be the same shape as self when an ndarray" + with pytest.raises(ValueError, match=msg): + df.where(cond, err1) + + err2 = cond.iloc[:2, :].values + other1 = _safe_add(df) + msg = "Array conditional must be same shape as self" + with pytest.raises(ValueError, match=msg): + df.where(err2, other1) + + with pytest.raises(ValueError, match=msg): + df.mask(True) + with pytest.raises(ValueError, match=msg): + df.mask(0) + + # where inplace + def _check_set(df, cond, check_dtypes=True): + dfi = df.copy() + econd = cond.reindex_like(df).fillna(True) + expected = dfi.mask(~econd) + + dfi.where(cond, np.nan, inplace=True) + tm.assert_frame_equal(dfi, expected) + + # dtypes (and confirm upcasts)x + if check_dtypes: + for k, v in df.dtypes.items(): + if issubclass(v.type, np.integer) and not cond[k].all(): + v = np.dtype("float64") + assert dfi[k].dtype == v + + for df in [ + default_frame, + float_string_frame, + mixed_float_frame, + mixed_int_frame, + ]: + if df is float_string_frame: + with pytest.raises(TypeError): + df > 0 + continue + + cond = df > 0 + _check_set(df, cond) + + cond = df >= 0 + _check_set(df, cond) + + # aligning + cond = (df >= 0)[1:] + _check_set(df, cond) + + # GH 10218 + # test DataFrame.where with Series slicing + df = DataFrame({"a": range(3), "b": range(4, 7)}) + result = df.where(df["a"] == 1) + expected = df[df["a"] == 1].reindex(df.index) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("klass", [list, tuple, np.array]) + def test_where_array_like(self, klass): + # see gh-15414 + df = DataFrame({"a": [1, 2, 3]}) + cond = [[False], [True], [True]] + expected = DataFrame({"a": [np.nan, 2, 3]}) + + result = df.where(klass(cond)) + tm.assert_frame_equal(result, expected) + + df["b"] = 2 + expected["b"] = [2, np.nan, 2] + cond = [[False, True], [True, False], [True, True]] + + result = df.where(klass(cond)) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "cond", + [ + [[1], [0], [1]], + Series([[2], [5], [7]]), + DataFrame({"a": [2, 5, 7]}), + [["True"], ["False"], ["True"]], + [[Timestamp("2017-01-01")], [pd.NaT], [Timestamp("2017-01-02")]], + ], + ) + def test_where_invalid_input_single(self, cond): + # see gh-15414: only boolean arrays accepted + df = DataFrame({"a": [1, 2, 3]}) + msg = "Boolean array expected for the condition" + + with pytest.raises(ValueError, match=msg): + df.where(cond) + + @pytest.mark.parametrize( + "cond", + [ + [[0, 1], [1, 0], [1, 1]], + Series([[0, 2], [5, 0], [4, 7]]), + [["False", "True"], ["True", "False"], ["True", "True"]], + DataFrame({"a": [2, 5, 7], "b": [4, 8, 9]}), + [ + [pd.NaT, Timestamp("2017-01-01")], + [Timestamp("2017-01-02"), pd.NaT], + [Timestamp("2017-01-03"), Timestamp("2017-01-03")], + ], + ], + ) + def test_where_invalid_input_multiple(self, cond): + # see gh-15414: only boolean arrays accepted + df = DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]}) + msg = "Boolean array expected for the condition" + + with pytest.raises(ValueError, match=msg): + df.where(cond) + + def test_where_dataframe_col_match(self): + df = DataFrame([[1, 2, 3], [4, 5, 6]]) + cond = DataFrame([[True, False, True], [False, False, True]]) + + result = df.where(cond) + expected = DataFrame([[1.0, np.nan, 3], [np.nan, np.nan, 6]]) + tm.assert_frame_equal(result, expected) + + # this *does* align, though has no matching columns + cond.columns = ["a", "b", "c"] + result = df.where(cond) + expected = DataFrame(np.nan, index=df.index, columns=df.columns) + tm.assert_frame_equal(result, expected) + + def test_where_ndframe_align(self): + msg = "Array conditional must be same shape as self" + df = DataFrame([[1, 2, 3], [4, 5, 6]]) + + cond = [True] + with pytest.raises(ValueError, match=msg): + df.where(cond) + + expected = DataFrame([[1, 2, 3], [np.nan, np.nan, np.nan]]) + + out = df.where(Series(cond)) + tm.assert_frame_equal(out, expected) + + cond = np.array([False, True, False, True]) + with pytest.raises(ValueError, match=msg): + df.where(cond) + + expected = DataFrame([[np.nan, np.nan, np.nan], [4, 5, 6]]) + + out = df.where(Series(cond)) + tm.assert_frame_equal(out, expected) + + def test_where_bug(self): + # see gh-2793 + df = DataFrame( + {"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]}, dtype="float64" + ) + expected = DataFrame( + {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]}, + dtype="float64", + ) + result = df.where(df > 2, np.nan) + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(result > 2, np.nan, inplace=True) + tm.assert_frame_equal(result, expected) + + def test_where_bug_mixed(self, sint_dtype): + # see gh-2793 + df = DataFrame( + { + "a": np.array([1, 2, 3, 4], dtype=sint_dtype), + "b": np.array([4.0, 3.0, 2.0, 1.0], dtype="float64"), + } + ) + + expected = DataFrame( + {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]}, + dtype="float64", + ) + + result = df.where(df > 2, np.nan) + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(result > 2, np.nan, inplace=True) + tm.assert_frame_equal(result, expected) + + def test_where_bug_transposition(self): + # see gh-7506 + a = DataFrame({0: [1, 2], 1: [3, 4], 2: [5, 6]}) + b = DataFrame({0: [np.nan, 8], 1: [9, np.nan], 2: [np.nan, np.nan]}) + do_not_replace = b.isna() | (a > b) + + expected = a.copy() + expected[~do_not_replace] = b + + result = a.where(do_not_replace, b) + tm.assert_frame_equal(result, expected) + + a = DataFrame({0: [4, 6], 1: [1, 0]}) + b = DataFrame({0: [np.nan, 3], 1: [3, np.nan]}) + do_not_replace = b.isna() | (a > b) + + expected = a.copy() + expected[~do_not_replace] = b + + result = a.where(do_not_replace, b) + tm.assert_frame_equal(result, expected) + + def test_where_datetime(self): + + # GH 3311 + df = DataFrame( + dict( + A=date_range("20130102", periods=5), + B=date_range("20130104", periods=5), + C=np.random.randn(5), + ) + ) + + stamp = datetime(2013, 1, 3) + with pytest.raises(TypeError): + df > stamp + + result = df[df.iloc[:, :-1] > stamp] + + expected = df.copy() + expected.loc[[0, 1], "A"] = np.nan + expected.loc[:, "C"] = np.nan + tm.assert_frame_equal(result, expected) + + def test_where_none(self): + # GH 4667 + # setting with None changes dtype + df = DataFrame({"series": Series(range(10))}).astype(float) + df[df > 7] = None + expected = DataFrame( + {"series": Series([0, 1, 2, 3, 4, 5, 6, 7, np.nan, np.nan])} + ) + tm.assert_frame_equal(df, expected) + + # GH 7656 + df = DataFrame( + [ + {"A": 1, "B": np.nan, "C": "Test"}, + {"A": np.nan, "B": "Test", "C": np.nan}, + ] + ) + msg = "boolean setting on mixed-type" + + with pytest.raises(TypeError, match=msg): + df.where(~isna(df), None, inplace=True) + + def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self): + # see gh-21947 + df = pd.DataFrame(columns=["a"]) + cond = df.applymap(lambda x: x > 0) + + result = df.where(cond) + tm.assert_frame_equal(result, df) + + def test_where_align(self): + def create(): + df = DataFrame(np.random.randn(10, 3)) + df.iloc[3:5, 0] = np.nan + df.iloc[4:6, 1] = np.nan + df.iloc[5:8, 2] = np.nan + return df + + # series + df = create() + expected = df.fillna(df.mean()) + result = df.where(pd.notna(df), df.mean(), axis="columns") + tm.assert_frame_equal(result, expected) + + df.where(pd.notna(df), df.mean(), inplace=True, axis="columns") + tm.assert_frame_equal(df, expected) + + df = create().fillna(0) + expected = df.apply(lambda x, y: x.where(x > 0, y), y=df[0]) + result = df.where(df > 0, df[0], axis="index") + tm.assert_frame_equal(result, expected) + result = df.where(df > 0, df[0], axis="rows") + tm.assert_frame_equal(result, expected) + + # frame + df = create() + expected = df.fillna(1) + result = df.where( + pd.notna(df), DataFrame(1, index=df.index, columns=df.columns) + ) + tm.assert_frame_equal(result, expected) + + def test_where_complex(self): + # GH 6345 + expected = DataFrame([[1 + 1j, 2], [np.nan, 4 + 1j]], columns=["a", "b"]) + df = DataFrame([[1 + 1j, 2], [5 + 1j, 4 + 1j]], columns=["a", "b"]) + df[df.abs() >= 5] = np.nan + tm.assert_frame_equal(df, expected) + + def test_where_axis(self): + # GH 9736 + df = DataFrame(np.random.randn(2, 2)) + mask = DataFrame([[False, False], [False, False]]) + s = Series([0, 1]) + + expected = DataFrame([[0, 0], [1, 1]], dtype="float64") + result = df.where(mask, s, axis="index") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(mask, s, axis="index", inplace=True) + tm.assert_frame_equal(result, expected) + + expected = DataFrame([[0, 1], [0, 1]], dtype="float64") + result = df.where(mask, s, axis="columns") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(mask, s, axis="columns", inplace=True) + tm.assert_frame_equal(result, expected) + + # Upcast needed + df = DataFrame([[1, 2], [3, 4]], dtype="int64") + mask = DataFrame([[False, False], [False, False]]) + s = Series([0, np.nan]) + + expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64") + result = df.where(mask, s, axis="index") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(mask, s, axis="index", inplace=True) + tm.assert_frame_equal(result, expected) + + expected = DataFrame([[0, np.nan], [0, np.nan]]) + result = df.where(mask, s, axis="columns") + tm.assert_frame_equal(result, expected) + + expected = DataFrame( + { + 0: np.array([0, 0], dtype="int64"), + 1: np.array([np.nan, np.nan], dtype="float64"), + } + ) + result = df.copy() + result.where(mask, s, axis="columns", inplace=True) + tm.assert_frame_equal(result, expected) + + # Multiple dtypes (=> multiple Blocks) + df = pd.concat( + [ + DataFrame(np.random.randn(10, 2)), + DataFrame(np.random.randint(0, 10, size=(10, 2)), dtype="int64"), + ], + ignore_index=True, + axis=1, + ) + mask = DataFrame(False, columns=df.columns, index=df.index) + s1 = Series(1, index=df.columns) + s2 = Series(2, index=df.index) + + result = df.where(mask, s1, axis="columns") + expected = DataFrame(1.0, columns=df.columns, index=df.index) + expected[2] = expected[2].astype("int64") + expected[3] = expected[3].astype("int64") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(mask, s1, axis="columns", inplace=True) + tm.assert_frame_equal(result, expected) + + result = df.where(mask, s2, axis="index") + expected = DataFrame(2.0, columns=df.columns, index=df.index) + expected[2] = expected[2].astype("int64") + expected[3] = expected[3].astype("int64") + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.where(mask, s2, axis="index", inplace=True) + tm.assert_frame_equal(result, expected) + + # DataFrame vs DataFrame + d1 = df.copy().drop(1, axis=0) + expected = df.copy() + expected.loc[1, :] = np.nan + + result = df.where(mask, d1) + tm.assert_frame_equal(result, expected) + result = df.where(mask, d1, axis="index") + tm.assert_frame_equal(result, expected) + result = df.copy() + result.where(mask, d1, inplace=True) + tm.assert_frame_equal(result, expected) + result = df.copy() + result.where(mask, d1, inplace=True, axis="index") + tm.assert_frame_equal(result, expected) + + d2 = df.copy().drop(1, axis=1) + expected = df.copy() + expected.loc[:, 1] = np.nan + + result = df.where(mask, d2) + tm.assert_frame_equal(result, expected) + result = df.where(mask, d2, axis="columns") + tm.assert_frame_equal(result, expected) + result = df.copy() + result.where(mask, d2, inplace=True) + tm.assert_frame_equal(result, expected) + result = df.copy() + result.where(mask, d2, inplace=True, axis="columns") + tm.assert_frame_equal(result, expected) + + def test_where_callable(self): + # GH 12533 + df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + result = df.where(lambda x: x > 4, lambda x: x + 1) + exp = DataFrame([[2, 3, 4], [5, 5, 6], [7, 8, 9]]) + tm.assert_frame_equal(result, exp) + tm.assert_frame_equal(result, df.where(df > 4, df + 1)) + + # return ndarray and scalar + result = df.where(lambda x: (x % 2 == 0).values, lambda x: 99) + exp = DataFrame([[99, 2, 99], [4, 99, 6], [99, 8, 99]]) + tm.assert_frame_equal(result, exp) + tm.assert_frame_equal(result, df.where(df % 2 == 0, 99)) + + # chain + result = (df + 2).where(lambda x: x > 8, lambda x: x + 10) + exp = DataFrame([[13, 14, 15], [16, 17, 18], [9, 10, 11]]) + tm.assert_frame_equal(result, exp) + tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10)) + + def test_where_tz_values(self, tz_naive_fixture): + df1 = DataFrame( + DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture), + columns=["date"], + ) + df2 = DataFrame( + DatetimeIndex(["20150103", "20150104", "20150105"], tz=tz_naive_fixture), + columns=["date"], + ) + mask = DataFrame([True, True, False], columns=["date"]) + exp = DataFrame( + DatetimeIndex(["20150101", "20150102", "20150105"], tz=tz_naive_fixture), + columns=["date"], + ) + result = df1.where(mask, df2) + tm.assert_frame_equal(exp, result)
- [x] closes #29544 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Split test cases in pandas/tests/frame/test_indexing into a sub directory (like pandas/tests/indexing). Still main file is pretty huge. Will update this PR with after suggestions and will fix style in a separate commit.
https://api.github.com/repos/pandas-dev/pandas/pulls/29694
2019-11-18T17:45:11Z
2019-11-19T15:07:02Z
2019-11-19T15:07:02Z
2019-11-19T15:07:06Z
Removed compat_helper.h
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index 8e61a772912af..ba108c4524b9c 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -1,7 +1,7 @@ import cython from cython import Py_ssize_t -from cpython.object cimport PyObject +from cpython.slice cimport PySlice_GetIndicesEx cdef extern from "Python.h": Py_ssize_t PY_SSIZE_T_MAX @@ -9,13 +9,6 @@ cdef extern from "Python.h": import numpy as np from numpy cimport int64_t -cdef extern from "compat_helper.h": - cdef int slice_get_indices(PyObject* s, Py_ssize_t length, - Py_ssize_t *start, Py_ssize_t *stop, - Py_ssize_t *step, - Py_ssize_t *slicelength) except -1 - - from pandas._libs.algos import ensure_int64 @@ -258,8 +251,8 @@ cpdef Py_ssize_t slice_len( if slc is None: raise TypeError("slc must be slice") - slice_get_indices(<PyObject *>slc, objlen, - &start, &stop, &step, &length) + PySlice_GetIndicesEx(slc, objlen, + &start, &stop, &step, &length) return length @@ -278,8 +271,8 @@ cdef slice_get_indices_ex(slice slc, Py_ssize_t objlen=PY_SSIZE_T_MAX): if slc is None: raise TypeError("slc should be a slice") - slice_get_indices(<PyObject *>slc, objlen, - &start, &stop, &step, &length) + PySlice_GetIndicesEx(slc, objlen, + &start, &stop, &step, &length) return start, stop, step, length diff --git a/pandas/_libs/src/compat_helper.h b/pandas/_libs/src/compat_helper.h deleted file mode 100644 index 01d5b843d1bb6..0000000000000 --- a/pandas/_libs/src/compat_helper.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright (c) 2016, PyData Development Team -All rights reserved. - -Distributed under the terms of the BSD Simplified License. - -The full license is in the LICENSE file, distributed with this software. -*/ - -#ifndef PANDAS__LIBS_SRC_COMPAT_HELPER_H_ -#define PANDAS__LIBS_SRC_COMPAT_HELPER_H_ - -#include "Python.h" -#include "inline_helper.h" - -/* -PySlice_GetIndicesEx changes signature in PY3 -but 3.6.1 in particular changes the behavior of this function slightly -https://bugs.python.org/issue27867 - - -In 3.6.1 PySlice_GetIndicesEx was changed to a macro -inadvertently breaking ABI compat. For now, undefing -the macro, which restores compat. -https://github.com/pandas-dev/pandas/issues/15961 -https://bugs.python.org/issue29943 -*/ - -#ifndef PYPY_VERSION -# if PY_VERSION_HEX < 0x03070000 && defined(PySlice_GetIndicesEx) -# undef PySlice_GetIndicesEx -# endif // PY_VERSION_HEX -#endif // PYPY_VERSION - -PANDAS_INLINE int slice_get_indices(PyObject *s, - Py_ssize_t length, - Py_ssize_t *start, - Py_ssize_t *stop, - Py_ssize_t *step, - Py_ssize_t *slicelength) { - return PySlice_GetIndicesEx(s, length, start, stop, - step, slicelength); -} - -#endif // PANDAS__LIBS_SRC_COMPAT_HELPER_H_ diff --git a/setup.py b/setup.py index a7bc7a333cdd6..545765ecb114d 100755 --- a/setup.py +++ b/setup.py @@ -83,10 +83,7 @@ def is_platform_mac(): _pxi_dep_template = { - "algos": [ - "_libs/algos_common_helper.pxi.in", - "_libs/algos_take_helper.pxi.in", - ], + "algos": ["_libs/algos_common_helper.pxi.in", "_libs/algos_take_helper.pxi.in"], "hashtable": [ "_libs/hashtable_class_helper.pxi.in", "_libs/hashtable_func_helper.pxi.in", @@ -544,7 +541,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): ts_include = ["pandas/_libs/tslibs/src", "pandas/_libs/tslibs"] -lib_depends = ["pandas/_libs/src/parse_helper.h", "pandas/_libs/src/compat_helper.h"] +lib_depends = ["pandas/_libs/src/parse_helper.h"] np_datetime_headers = [ "pandas/_libs/tslibs/src/datetime/np_datetime.h", @@ -823,5 +820,5 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): entry_points={ "pandas_plotting_backends": ["matplotlib = pandas:plotting._matplotlib"] }, - **setuptools_kwargs + **setuptools_kwargs, )
ref #29666 and comments from @jbrockmendel and @gfyoung looks like the compat header can now be removed, now that we are on 3.6.1 as a minimum
https://api.github.com/repos/pandas-dev/pandas/pulls/29693
2019-11-18T17:41:11Z
2019-11-19T13:26:59Z
2019-11-19T13:26:59Z
2020-01-16T00:35:17Z
REF: ensure name and cname are always str
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 193b8f5053d65..1e2583ffab1dc 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1691,29 +1691,37 @@ class IndexCol: is_data_indexable = True _info_fields = ["freq", "tz", "index_name"] + name: str + cname: str + kind_attr: str + def __init__( self, + name: str, values=None, kind=None, typ=None, - cname=None, + cname: Optional[str] = None, itemsize=None, - name=None, axis=None, - kind_attr=None, + kind_attr: Optional[str] = None, pos=None, freq=None, tz=None, index_name=None, **kwargs, ): + + if not isinstance(name, str): + raise ValueError("`name` must be a str.") + self.values = values self.kind = kind self.typ = typ self.itemsize = itemsize self.name = name - self.cname = cname - self.kind_attr = kind_attr + self.cname = cname or name + self.kind_attr = kind_attr or f"{name}_kind" self.axis = axis self.pos = pos self.freq = freq @@ -1723,19 +1731,14 @@ def __init__( self.meta = None self.metadata = None - if name is not None: - self.set_name(name, kind_attr) if pos is not None: self.set_pos(pos) - def set_name(self, name, kind_attr=None): - """ set the name of this indexer """ - self.name = name - self.kind_attr = kind_attr or "{name}_kind".format(name=name) - if self.cname is None: - self.cname = name - - return self + # These are ensured as long as the passed arguments match the + # constructor annotations. + assert isinstance(self.name, str) + assert isinstance(self.cname, str) + assert isinstance(self.kind_attr, str) def set_axis(self, axis: int): """ set the axis over which I index """ @@ -1752,7 +1755,6 @@ def set_pos(self, pos: int): def set_table(self, table): self.table = table - return self def __repr__(self) -> str: temp = tuple( @@ -1778,10 +1780,13 @@ def __ne__(self, other) -> bool: @property def is_indexed(self) -> bool: """ return whether I am an indexed column """ - try: - return getattr(self.table.cols, self.cname).is_indexed - except AttributeError: + if not hasattr(self.table, "cols"): + # e.g. if self.set_table hasn't been called yet, self.table + # will be None. return False + # GH#29692 mypy doesn't recognize self.table as having a "cols" attribute + # 'error: "None" has no attribute "cols"' + return getattr(self.table.cols, self.cname).is_indexed # type: ignore def copy(self): new_self = copy.copy(self) @@ -2481,6 +2486,7 @@ class DataIndexableCol(DataCol): def validate_names(self): if not Index(self.values).is_object(): + # TODO: should the message here be more specifically non-str? raise ValueError("cannot have non-object label DataIndexableCol") def get_atom_string(self, block, itemsize): @@ -2813,8 +2819,8 @@ def write_index(self, key, index): else: setattr(self.attrs, "{key}_variety".format(key=key), "regular") converted = _convert_index( - index, self.encoding, self.errors, self.format_type - ).set_name("index") + "index", index, self.encoding, self.errors, self.format_type + ) self.write_array(key, converted.values) @@ -2864,8 +2870,8 @@ def write_multi_index(self, key, index): ) level_key = "{key}_level{idx}".format(key=key, idx=i) conv_level = _convert_index( - lev, self.encoding, self.errors, self.format_type - ).set_name(level_key) + level_key, lev, self.encoding, self.errors, self.format_type + ) self.write_array(level_key, conv_level.values) node = getattr(self.group, level_key) node._v_attrs.kind = conv_level.kind @@ -3403,9 +3409,10 @@ def queryables(self): def index_cols(self): """ return a list of my index cols """ + # Note: each `i.cname` below is assured to be a str. return [(i.axis, i.cname) for i in self.index_axes] - def values_cols(self): + def values_cols(self) -> List[str]: """ return a list of my values cols """ return [i.cname for i in self.values_axes] @@ -3507,6 +3514,8 @@ def indexables(self): self._indexables = [] + # Note: each of the `name` kwargs below are str, ensured + # by the definition in index_cols. # index columns self._indexables.extend( [ @@ -3520,6 +3529,7 @@ def indexables(self): base_pos = len(self._indexables) def f(i, c): + assert isinstance(c, str) klass = DataCol if c in dc: klass = DataIndexableCol @@ -3527,6 +3537,8 @@ def f(i, c): i=i, name=c, pos=base_pos + i, version=self.version ) + # Note: the definition of `values_cols` ensures that each + # `c` below is a str. self._indexables.extend( [f(i, c) for i, c in enumerate(self.attrs.values_cols)] ) @@ -3764,11 +3776,9 @@ def create_axes( if i in axes: name = obj._AXIS_NAMES[i] - index_axes_map[i] = ( - _convert_index(a, self.encoding, self.errors, self.format_type) - .set_name(name) - .set_axis(i) - ) + index_axes_map[i] = _convert_index( + name, a, self.encoding, self.errors, self.format_type + ).set_axis(i) else: # we might be able to change the axes on the appending data if @@ -3867,6 +3877,9 @@ def get_blk_items(mgr, blocks): if data_columns and len(b_items) == 1 and b_items[0] in data_columns: klass = DataIndexableCol name = b_items[0] + if not (name is None or isinstance(name, str)): + # TODO: should the message here be more specifically non-str? + raise ValueError("cannot have non-object label DataIndexableCol") self.data_columns.append(name) # make sure that we match up the existing columns @@ -4531,6 +4544,7 @@ def indexables(self): self._indexables = [GenericIndexCol(name="index", axis=0)] for i, n in enumerate(d._v_names): + assert isinstance(n, str) dc = GenericDataIndexableCol( name=n, pos=i, values=[n], version=self.version @@ -4649,12 +4663,15 @@ def _set_tz(values, tz, preserve_UTC: bool = False, coerce: bool = False): return values -def _convert_index(index, encoding=None, errors="strict", format_type=None): +def _convert_index(name: str, index, encoding=None, errors="strict", format_type=None): + assert isinstance(name, str) + index_name = getattr(index, "name", None) if isinstance(index, DatetimeIndex): converted = index.asi8 return IndexCol( + name, converted, "datetime64", _tables().Int64Col(), @@ -4665,6 +4682,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): elif isinstance(index, TimedeltaIndex): converted = index.asi8 return IndexCol( + name, converted, "timedelta64", _tables().Int64Col(), @@ -4675,6 +4693,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): atom = _tables().Int64Col() # avoid to store ndarray of Period objects return IndexCol( + name, index._ndarray_values, "integer", atom, @@ -4692,6 +4711,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): if inferred_type == "datetime64": converted = values.view("i8") return IndexCol( + name, converted, "datetime64", _tables().Int64Col(), @@ -4702,6 +4722,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): elif inferred_type == "timedelta64": converted = values.view("i8") return IndexCol( + name, converted, "timedelta64", _tables().Int64Col(), @@ -4714,11 +4735,13 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): dtype=np.float64, ) return IndexCol( - converted, "datetime", _tables().Time64Col(), index_name=index_name + name, converted, "datetime", _tables().Time64Col(), index_name=index_name ) elif inferred_type == "date": converted = np.asarray([v.toordinal() for v in values], dtype=np.int32) - return IndexCol(converted, "date", _tables().Time32Col(), index_name=index_name) + return IndexCol( + name, converted, "date", _tables().Time32Col(), index_name=index_name, + ) elif inferred_type == "string": # atom = _tables().ObjectAtom() # return np.asarray(values, dtype='O'), 'object', atom @@ -4726,6 +4749,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): converted = _convert_string_array(values, encoding, errors) itemsize = converted.dtype.itemsize return IndexCol( + name, converted, "string", _tables().StringCol(itemsize), @@ -4736,7 +4760,11 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): if format_type == "fixed": atom = _tables().ObjectAtom() return IndexCol( - np.asarray(values, dtype="O"), "object", atom, index_name=index_name + name, + np.asarray(values, dtype="O"), + "object", + atom, + index_name=index_name, ) raise TypeError( "[unicode] is not supported as a in index type for [{0}] formats".format( @@ -4748,17 +4776,25 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): # take a guess for now, hope the values fit atom = _tables().Int64Col() return IndexCol( - np.asarray(values, dtype=np.int64), "integer", atom, index_name=index_name + name, + np.asarray(values, dtype=np.int64), + "integer", + atom, + index_name=index_name, ) elif inferred_type == "floating": atom = _tables().Float64Col() return IndexCol( - np.asarray(values, dtype=np.float64), "float", atom, index_name=index_name + name, + np.asarray(values, dtype=np.float64), + "float", + atom, + index_name=index_name, ) else: # pragma: no cover atom = _tables().ObjectAtom() return IndexCol( - np.asarray(values, dtype="O"), "object", atom, index_name=index_name + name, np.asarray(values, dtype="O"), "object", atom, index_name=index_name, )
Once this is assured, there are a lot of other things (including in core.computation!) that we can infer in follow-ups.
https://api.github.com/repos/pandas-dev/pandas/pulls/29692
2019-11-18T16:12:06Z
2019-11-20T17:15:59Z
2019-11-20T17:15:59Z
2019-11-20T17:47:34Z
BUG: Series groupby does not include nan counts for all categorical labels (#17605)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index cb68bd0e762c4..75d47938f983a 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -183,6 +183,47 @@ New repr for :class:`pandas.core.arrays.IntervalArray` pd.arrays.IntervalArray.from_tuples([(0, 1), (2, 3)]) + +All :class:`SeriesGroupBy` aggregation methods now respect the ``observed`` keyword +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The following methods now also correctly output values for unobserved categories when called through ``groupby(..., observed=False)`` (:issue:`17605`) + +- :meth:`SeriesGroupBy.count` +- :meth:`SeriesGroupBy.size` +- :meth:`SeriesGroupBy.nunique` +- :meth:`SeriesGroupBy.nth` + +.. ipython:: python + + df = pd.DataFrame({ + "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), + "cat_2": pd.Categorical(list("AB") * 2, categories=list("ABC")), + "value": [0.1] * 4, + }) + df + + +*pandas 0.25.x* + +.. code-block:: ipython + + In [2]: df.groupby(["cat_1", "cat_2"], observed=False)["value"].count() + Out[2]: + cat_1 cat_2 + A A 1 + B 1 + B A 1 + B 1 + Name: value, dtype: int64 + + +*pandas 1.0.0* + +.. ipython:: python + + df.groupby(["cat_1", "cat_2"], observed=False)["value"].count() + + .. _whatsnew_1000.api.other: Other API changes diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 6376dbefcf435..f5ec763db390f 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -569,7 +569,8 @@ def nunique(self, dropna: bool = True) -> Series: res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out - return Series(res, index=ri, name=self._selection_name) + result = Series(res, index=ri, name=self._selection_name) + return self._reindex_output(result, fill_value=0) @Appender(Series.describe.__doc__) def describe(self, **kwargs): @@ -721,12 +722,13 @@ def count(self) -> Series: minlength = ngroups or 0 out = np.bincount(ids[mask], minlength=minlength) - return Series( + result = Series( out, index=self.grouper.result_index, name=self._selection_name, dtype="int64", ) + return self._reindex_output(result, fill_value=0) def _apply_to_column_groupbys(self, func): """ return a pass thru """ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 236df4b3854a4..62bbb151f793e 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -39,6 +39,7 @@ class providing the base-class of operations. ) from pandas.core.dtypes.missing import isna, notna +from pandas._typing import FrameOrSeries, Scalar from pandas.core import nanops import pandas.core.algorithms as algorithms from pandas.core.arrays import Categorical, try_cast_to_ea @@ -1296,7 +1297,7 @@ def size(self): if isinstance(self.obj, Series): result.name = self.obj.name - return result + return self._reindex_output(result, fill_value=0) @classmethod def _add_numeric_operations(cls): @@ -1743,6 +1744,7 @@ def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFra if not self.observed and isinstance(result_index, CategoricalIndex): out = out.reindex(result_index) + out = self._reindex_output(out) return out.sort_index() if self.sort else out # dropna is truthy @@ -2383,7 +2385,9 @@ def tail(self, n=5): mask = self._cumcount_array(ascending=False) < n return self._selected_obj[mask] - def _reindex_output(self, output): + def _reindex_output( + self, output: FrameOrSeries, fill_value: Scalar = np.NaN + ) -> FrameOrSeries: """ If we have categorical groupers, then we might want to make sure that we have a fully re-indexed output to the levels. This means expanding @@ -2397,8 +2401,10 @@ def _reindex_output(self, output): Parameters ---------- - output: Series or DataFrame + output : Series or DataFrame Object resulting from grouping and applying an operation. + fill_value : scalar, default np.NaN + Value to use for unobserved categories if self.observed is False. Returns ------- @@ -2429,7 +2435,11 @@ def _reindex_output(self, output): ).sortlevel() if self.as_index: - d = {self.obj._get_axis_name(self.axis): index, "copy": False} + d = { + self.obj._get_axis_name(self.axis): index, + "copy": False, + "fill_value": fill_value, + } return output.reindex(**d) # GH 13204 @@ -2451,7 +2461,9 @@ def _reindex_output(self, output): output = output.drop(labels=list(g_names), axis=1) # Set a temp index and reindex (possibly expanding) - output = output.set_index(self.grouper.result_index).reindex(index, copy=False) + output = output.set_index(self.grouper.result_index).reindex( + index, copy=False, fill_value=fill_value + ) # Reset in-axis grouper columns # (using level numbers `g_nums` because level names may not be unique) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 663e03aa1bc81..5f78e4860f1e9 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1252,3 +1252,82 @@ def test_get_nonexistent_category(): {"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]} ) ) + + +def test_series_groupby_on_2_categoricals_unobserved( + reduction_func: str, observed: bool +): + # GH 17605 + + if reduction_func == "ngroup": + pytest.skip("ngroup is not truly a reduction") + + df = pd.DataFrame( + { + "cat_1": pd.Categorical(list("AABB"), categories=list("ABCD")), + "cat_2": pd.Categorical(list("AB") * 2, categories=list("ABCD")), + "value": [0.1] * 4, + } + ) + args = {"nth": [0]}.get(reduction_func, []) + + expected_length = 4 if observed else 16 + + series_groupby = df.groupby(["cat_1", "cat_2"], observed=observed)["value"] + agg = getattr(series_groupby, reduction_func) + result = agg(*args) + + assert len(result) == expected_length + + +@pytest.mark.parametrize( + "func, zero_or_nan", + [ + ("all", np.NaN), + ("any", np.NaN), + ("count", 0), + ("first", np.NaN), + ("idxmax", np.NaN), + ("idxmin", np.NaN), + ("last", np.NaN), + ("mad", np.NaN), + ("max", np.NaN), + ("mean", np.NaN), + ("median", np.NaN), + ("min", np.NaN), + ("nth", np.NaN), + ("nunique", 0), + ("prod", np.NaN), + ("quantile", np.NaN), + ("sem", np.NaN), + ("size", 0), + ("skew", np.NaN), + ("std", np.NaN), + ("sum", np.NaN), + ("var", np.NaN), + ], +) +def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans(func, zero_or_nan): + # GH 17605 + # Tests whether the unobserved categories in the result contain 0 or NaN + df = pd.DataFrame( + { + "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), + "cat_2": pd.Categorical(list("AB") * 2, categories=list("ABC")), + "value": [0.1] * 4, + } + ) + unobserved = [tuple("AC"), tuple("BC"), tuple("CA"), tuple("CB"), tuple("CC")] + args = {"nth": [0]}.get(func, []) + + series_groupby = df.groupby(["cat_1", "cat_2"], observed=False)["value"] + agg = getattr(series_groupby, func) + result = agg(*args) + + for idx in unobserved: + val = result.loc[idx] + assert (pd.isna(zero_or_nan) and pd.isna(val)) or (val == zero_or_nan) + + # If we expect unobserved values to be zero, we also expect the dtype to be int + if zero_or_nan == 0: + assert np.issubdtype(result.dtype, np.integer)
- [x] closes #17605 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This is a simple, low-impact fix for #17605.
https://api.github.com/repos/pandas-dev/pandas/pulls/29690
2019-11-18T16:02:26Z
2019-11-20T12:46:19Z
2019-11-20T12:46:18Z
2019-11-20T12:46:24Z
CI: Fixing error in code checks in GitHub actions
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index d5566c522ac64..edd8fcd418c47 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -190,9 +190,9 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include="*.rst" ".. ipython ::" doc/source RET=$(($RET + $?)) ; echo $MSG "DONE" -    MSG='Check for extra blank lines after the class definition' ; echo $MSG -    invgrep -R --include="*.py" --include="*.pyx" -E 'class.*:\n\n( )+"""' . -    RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for extra blank lines after the class definition' ; echo $MSG + invgrep -R --include="*.py" --include="*.pyx" -E 'class.*:\n\n( )+"""' . + RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Check that no file in the repo contains trailing whitespaces' ; echo $MSG set -o pipefail
xref https://github.com/pandas-dev/pandas/pull/29546#issuecomment-554807243 Looks like the code in one of the checks in `ci/code_checks.sh` uses another encoding for spaces and other characters. I guess it was generated from Windows, Azure-pipelines is not sensitive to the different encoding, but GitHub actions is. Probably worth doing some more research and adding a check that makes sure this new encoding is not introduced anymore. CC: @gfyoung @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/29683
2019-11-18T02:50:06Z
2019-11-18T04:41:16Z
2019-11-18T04:41:16Z
2019-11-18T04:41:16Z
TYP: add string annotations in io.pytables
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index f41c767d0b13a..193b8f5053d65 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -9,7 +9,7 @@ import os import re import time -from typing import List, Optional, Type, Union +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union import warnings import numpy as np @@ -55,6 +55,10 @@ from pandas.io.common import _stringify_path from pandas.io.formats.printing import adjoin, pprint_thing +if TYPE_CHECKING: + from tables import File # noqa:F401 + + # versioning attribute _version = "0.15.2" @@ -465,6 +469,8 @@ class HDFStore: >>> store.close() """ + _handle: Optional["File"] + def __init__( self, path, @@ -535,7 +541,7 @@ def __getattr__(self, name): ) ) - def __contains__(self, key): + def __contains__(self, key: str): """ check for existence of this key can match the exact pathname or the pathnm w/o the leading '/' """ @@ -560,7 +566,7 @@ def __enter__(self): def __exit__(self, exc_type, exc_value, traceback): self.close() - def keys(self): + def keys(self) -> List[str]: """ Return a list of keys corresponding to objects stored in HDFStore. @@ -698,13 +704,13 @@ def flush(self, fsync: bool = False): except OSError: pass - def get(self, key): + def get(self, key: str): """ Retrieve pandas object stored in file. Parameters ---------- - key : object + key : str Returns ------- @@ -718,7 +724,7 @@ def get(self, key): def select( self, - key, + key: str, where=None, start=None, stop=None, @@ -733,7 +739,7 @@ def select( Parameters ---------- - key : object + key : str Object being retrieved from file. where : list, default None List of Term (or convertible) objects, optional. @@ -784,13 +790,15 @@ def func(_start, _stop, _where): return it.get_result() - def select_as_coordinates(self, key, where=None, start=None, stop=None, **kwargs): + def select_as_coordinates( + self, key: str, where=None, start=None, stop=None, **kwargs + ): """ return the selection as an Index Parameters ---------- - key : object + key : str where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection @@ -800,15 +808,16 @@ def select_as_coordinates(self, key, where=None, start=None, stop=None, **kwargs where=where, start=start, stop=stop, **kwargs ) - def select_column(self, key, column, **kwargs): + def select_column(self, key: str, column: str, **kwargs): """ return a single column from the table. This is generally only useful to select an indexable Parameters ---------- - key : object - column: the column of interest + key : str + column: str + The column of interest. Raises ------ @@ -966,7 +975,7 @@ def put(self, key, value, format=None, append=False, **kwargs): kwargs = self._validate_format(format, kwargs) self._write_to_group(key, value, append=append, **kwargs) - def remove(self, key, where=None, start=None, stop=None): + def remove(self, key: str, where=None, start=None, stop=None): """ Remove pandas object partially by specifying the where condition @@ -1152,16 +1161,17 @@ def append_to_multiple( self.append(k, val, data_columns=dc, **kwargs) - def create_table_index(self, key, **kwargs): - """ Create a pytables index on the table + def create_table_index(self, key: str, **kwargs): + """ + Create a pytables index on the table. + Parameters ---------- - key : object (the node to index) + key : str Raises ------ - raises if the node is not a table - + TypeError: raises if the node is not a table """ # version requirements @@ -1247,17 +1257,19 @@ def walk(self, where="/"): yield (g._v_pathname.rstrip("/"), groups, leaves) - def get_node(self, key): + def get_node(self, key: str): """ return the node with the key or None if it does not exist """ self._check_if_open() + if not key.startswith("/"): + key = "/" + key + + assert self._handle is not None try: - if not key.startswith("/"): - key = "/" + key return self._handle.get_node(self.root, key) - except _table_mod.exceptions.NoSuchNodeError: + except _table_mod.exceptions.NoSuchNodeError: # type: ignore return None - def get_storer(self, key): + def get_storer(self, key: str): """ return the storer object for a key, raise if not in the file """ group = self.get_node(key) if group is None: @@ -1481,7 +1493,7 @@ def error(t): def _write_to_group( self, - key, + key: str, value, format, index=True, @@ -1492,6 +1504,10 @@ def _write_to_group( ): group = self.get_node(key) + # we make this assertion for mypy; the get_node call will already + # have raised if this is incorrect + assert self._handle is not None + # remove the node if we are not appending if group is not None and not append: self._handle.remove_node(group, recursive=True) @@ -2691,7 +2707,7 @@ def f(values, freq=None, tz=None): return klass - def validate_read(self, kwargs): + def validate_read(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """ remove table keywords from kwargs and return raise if any keywords are passed which are not-None @@ -2733,7 +2749,7 @@ def get_attrs(self): def write(self, obj, **kwargs): self.set_attrs() - def read_array(self, key, start=None, stop=None): + def read_array(self, key: str, start=None, stop=None): """ read an array for the specified node (off of group """ import tables @@ -4008,7 +4024,7 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs): return Index(coords) - def read_column(self, column, where=None, start=None, stop=None): + def read_column(self, column: str, where=None, start=None, stop=None): """return a single column from the table, generally only indexables are interesting """ @@ -4642,8 +4658,8 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): converted, "datetime64", _tables().Int64Col(), - freq=getattr(index, "freq", None), - tz=getattr(index, "tz", None), + freq=index.freq, + tz=index.tz, index_name=index_name, ) elif isinstance(index, TimedeltaIndex): @@ -4652,7 +4668,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None): converted, "timedelta64", _tables().Int64Col(), - freq=getattr(index, "freq", None), + freq=index.freq, index_name=index_name, ) elif isinstance(index, (Int64Index, PeriodIndex)):
This file is pretty tough, so for now this just goes through and adds `str` annotations in places where it is unambiguous (e.g. the variable is passed to `getattr`) and places that can be directly reasoned about from there.
https://api.github.com/repos/pandas-dev/pandas/pulls/29682
2019-11-17T23:42:21Z
2019-11-18T00:34:45Z
2019-11-18T00:34:45Z
2019-11-18T01:28:47Z
BUG: IndexError in __repr__
diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 13a4814068d6a..4eb39898214c5 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -2,7 +2,7 @@ import ast from functools import partial -from typing import Optional +from typing import Any, Optional, Tuple import numpy as np @@ -72,7 +72,6 @@ def __init__(self, op, lhs, rhs, queryables, encoding): super().__init__(op, lhs, rhs) self.queryables = queryables self.encoding = encoding - self.filter = None self.condition = None def _disallow_scalar_only_bool_ops(self): @@ -230,7 +229,11 @@ def convert_values(self): class FilterBinOp(BinOp): + filter: Optional[Tuple[Any, Any, pd.Index]] = None + def __repr__(self) -> str: + if self.filter is None: + return "Filter: Not Initialized" return pprint_thing( "[Filter : [{lhs}] -> [{op}]".format(lhs=self.filter[0], op=self.filter[1]) ) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 7c7b78720d46d..f41c767d0b13a 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3868,30 +3868,21 @@ def get_blk_items(mgr, blocks): else: existing_col = None - try: - col = klass.create_for_block(i=i, name=name, version=self.version) - col.set_atom( - block=b, - block_items=b_items, - existing_col=existing_col, - min_itemsize=min_itemsize, - nan_rep=nan_rep, - encoding=self.encoding, - errors=self.errors, - info=self.info, - ) - col.set_pos(j) + col = klass.create_for_block(i=i, name=name, version=self.version) + col.set_atom( + block=b, + block_items=b_items, + existing_col=existing_col, + min_itemsize=min_itemsize, + nan_rep=nan_rep, + encoding=self.encoding, + errors=self.errors, + info=self.info, + ) + col.set_pos(j) + + self.values_axes.append(col) - self.values_axes.append(col) - except (NotImplementedError, ValueError, TypeError) as e: - raise e - except Exception as detail: - raise Exception( - "cannot find the correct atom type -> " - "[dtype->{name},items->{items}] {detail!s}".format( - name=b.dtype.name, items=b_items, detail=detail - ) - ) j += 1 # validate our min_itemsize
By avoiding that `IndexError`, we can get rid of an `except Exception` in `io.pytables`
https://api.github.com/repos/pandas-dev/pandas/pulls/29681
2019-11-17T22:08:29Z
2019-11-17T23:01:50Z
2019-11-17T23:01:50Z
2019-11-17T23:15:28Z
Bug fix GH 29624: calling str.isalpha on empty series returns object …
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index c91ced1014dd1..58d1fef9ef5bf 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -354,7 +354,7 @@ Conversion Strings ^^^^^^^ -- +- Calling :meth:`Series.str.isalnum` (and other "ismethods") on an empty Series would return an object dtype instead of bool (:issue:`29624`) - diff --git a/pandas/core/strings.py b/pandas/core/strings.py index a6e0c12526d8a..55ce44d736864 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -3401,59 +3401,69 @@ def rindex(self, sub, start=0, end=None): _doc_args["istitle"] = dict(type="titlecase", method="istitle") _doc_args["isnumeric"] = dict(type="numeric", method="isnumeric") _doc_args["isdecimal"] = dict(type="decimal", method="isdecimal") + # force _noarg_wrapper return type with dtype=bool (GH 29624) isalnum = _noarg_wrapper( lambda x: x.isalnum(), name="isalnum", docstring=_shared_docs["ismethods"] % _doc_args["isalnum"], returns_string=False, + dtype=bool, ) isalpha = _noarg_wrapper( lambda x: x.isalpha(), name="isalpha", docstring=_shared_docs["ismethods"] % _doc_args["isalpha"], returns_string=False, + dtype=bool, ) isdigit = _noarg_wrapper( lambda x: x.isdigit(), name="isdigit", docstring=_shared_docs["ismethods"] % _doc_args["isdigit"], returns_string=False, + dtype=bool, ) isspace = _noarg_wrapper( lambda x: x.isspace(), name="isspace", docstring=_shared_docs["ismethods"] % _doc_args["isspace"], returns_string=False, + dtype=bool, ) islower = _noarg_wrapper( lambda x: x.islower(), name="islower", docstring=_shared_docs["ismethods"] % _doc_args["islower"], returns_string=False, + dtype=bool, ) isupper = _noarg_wrapper( lambda x: x.isupper(), name="isupper", docstring=_shared_docs["ismethods"] % _doc_args["isupper"], returns_string=False, + dtype=bool, ) istitle = _noarg_wrapper( lambda x: x.istitle(), name="istitle", docstring=_shared_docs["ismethods"] % _doc_args["istitle"], returns_string=False, + dtype=bool, ) isnumeric = _noarg_wrapper( lambda x: x.isnumeric(), name="isnumeric", docstring=_shared_docs["ismethods"] % _doc_args["isnumeric"], returns_string=False, + dtype=bool, ) isdecimal = _noarg_wrapper( lambda x: x.isdecimal(), name="isdecimal", docstring=_shared_docs["ismethods"] % _doc_args["isdecimal"], returns_string=False, + dtype=bool, ) @classmethod diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index f5d28ec82d1d4..f68541b620efa 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -1853,15 +1853,16 @@ def test_empty_str_methods(self): tm.assert_series_equal(empty_str, empty.str.get(0)) tm.assert_series_equal(empty_str, empty_bytes.str.decode("ascii")) tm.assert_series_equal(empty_bytes, empty.str.encode("ascii")) - tm.assert_series_equal(empty_str, empty.str.isalnum()) - tm.assert_series_equal(empty_str, empty.str.isalpha()) - tm.assert_series_equal(empty_str, empty.str.isdigit()) - tm.assert_series_equal(empty_str, empty.str.isspace()) - tm.assert_series_equal(empty_str, empty.str.islower()) - tm.assert_series_equal(empty_str, empty.str.isupper()) - tm.assert_series_equal(empty_str, empty.str.istitle()) - tm.assert_series_equal(empty_str, empty.str.isnumeric()) - tm.assert_series_equal(empty_str, empty.str.isdecimal()) + # ismethods should always return boolean (GH 29624) + tm.assert_series_equal(empty_bool, empty.str.isalnum()) + tm.assert_series_equal(empty_bool, empty.str.isalpha()) + tm.assert_series_equal(empty_bool, empty.str.isdigit()) + tm.assert_series_equal(empty_bool, empty.str.isspace()) + tm.assert_series_equal(empty_bool, empty.str.islower()) + tm.assert_series_equal(empty_bool, empty.str.isupper()) + tm.assert_series_equal(empty_bool, empty.str.istitle()) + tm.assert_series_equal(empty_bool, empty.str.isnumeric()) + tm.assert_series_equal(empty_bool, empty.str.isdecimal()) tm.assert_series_equal(empty_str, empty.str.capitalize()) tm.assert_series_equal(empty_str, empty.str.swapcase()) tm.assert_series_equal(empty_str, empty.str.normalize("NFC"))
…dtype, not bool Added dtype=bool argument to make _noarg_wrapper() return a bool Series - [x] closes #29624 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29680
2019-11-17T21:32:41Z
2019-11-17T23:06:35Z
2019-11-17T23:06:34Z
2019-11-18T04:55:50Z
CLN: Simplify black command in Makefile
diff --git a/Makefile b/Makefile index 27a2c3682de9c..f26689ab65ba5 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ lint-diff: git diff upstream/master --name-only -- "*.py" | xargs flake8 black: - black . --exclude '(asv_bench/env|\.egg|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|_build|buck-out|build|dist|setup.py)' + black . develop: build python -m pip install --no-build-isolation -e .
Follow up to #29607 where `exclude` was added to `pyproject.toml`, so it no longer needs to be explicitly specified. Missed this reference; checked for additional missed references but didn't find any.
https://api.github.com/repos/pandas-dev/pandas/pulls/29679
2019-11-17T21:10:33Z
2019-11-17T22:47:52Z
2019-11-17T22:47:52Z
2019-11-17T22:48:55Z
DEPS: Unifying testing and building dependencies across builds
diff --git a/ci/deps/azure-36-32bit.yaml b/ci/deps/azure-36-32bit.yaml index 1e2e6c33e8c15..f3e3d577a7a33 100644 --- a/ci/deps/azure-36-32bit.yaml +++ b/ci/deps/azure-36-32bit.yaml @@ -3,21 +3,25 @@ channels: - defaults - conda-forge dependencies: + - python=3.6.* + + # tools + ### Cython 0.29.13 and pytest 5.0.1 for 32 bits are not available with conda, installing below with pip instead + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies - attrs=19.1.0 - gcc_linux-32 - - gcc_linux-32 - gxx_linux-32 - numpy=1.14.* - python-dateutil - - python=3.6.* - pytz=2017.2 - # universal - - pytest - - pytest-xdist - - pytest-mock - - pytest-azurepipelines - - hypothesis>=3.58.0 + + # see comment above - pip - pip: - # Anaconda doesn't build a new enough Cython - cython>=0.29.13 + - pytest>=5.0.1 diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml index 76868f598f11b..3baf975afc096 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-36-locale.yaml @@ -3,28 +3,31 @@ channels: - defaults - conda-forge dependencies: + - python=3.6.* + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies - beautifulsoup4==4.6.0 - bottleneck=1.2.* - - cython=0.29.13 - lxml - matplotlib=2.2.2 - numpy=1.14.* - openpyxl=2.4.8 - python-dateutil - python-blosc - - python=3.6.* - pytz=2017.2 - scipy - sqlalchemy=1.1.4 - xlrd=1.1.0 - xlsxwriter=0.9.8 - xlwt=1.2.0 - # universal - - pytest>=5.0.0 - - pytest-xdist>=1.29.0 - - pytest-mock - - pytest-azurepipelines - - hypothesis>=3.58.0 - pip - pip: - html5lib==1.0b2 diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml index 21205375204dc..01741e9b65a7a 100644 --- a/ci/deps/azure-36-locale_slow.yaml +++ b/ci/deps/azure-36-locale_slow.yaml @@ -3,8 +3,18 @@ channels: - defaults - conda-forge dependencies: - - beautifulsoup4 + - python=3.6.* + + # tools - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies + - beautifulsoup4 - gcsfs - html5lib - ipython @@ -17,7 +27,6 @@ dependencies: - openpyxl - pytables - python-dateutil - - python=3.6.* - pytz - s3fs - scipy @@ -25,12 +34,4 @@ dependencies: - xlrd - xlsxwriter - xlwt - # universal - - pytest>=4.0.2 - - pytest-xdist - - pytest-mock - - pytest-azurepipelines - moto - - pip - - pip: - - hypothesis>=3.58.0 diff --git a/ci/deps/azure-36-minimum_versions.yaml b/ci/deps/azure-36-minimum_versions.yaml index e2c78165fe4b9..1e32ef7482be3 100644 --- a/ci/deps/azure-36-minimum_versions.yaml +++ b/ci/deps/azure-36-minimum_versions.yaml @@ -3,25 +3,28 @@ channels: - defaults - conda-forge dependencies: + - python=3.6.1 + + # tools + - cython=0.29.13 + - pytest=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies - beautifulsoup4=4.6.0 - bottleneck=1.2.1 - - cython>=0.29.13 - jinja2=2.8 - numexpr=2.6.2 - numpy=1.13.3 - openpyxl=2.4.8 - pytables=3.4.2 - python-dateutil=2.6.1 - - python=3.6.1 - pytz=2017.2 - scipy=0.19.0 - xlrd=1.1.0 - xlsxwriter=0.9.8 - xlwt=1.2.0 - # universal - html5lib=1.0.1 - - hypothesis>=3.58.0 - - pytest=4.5.0 - - pytest-xdist - - pytest-mock - - pytest-azurepipelines diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 24464adb74f5b..26446ab5365b1 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -3,8 +3,18 @@ channels: - defaults - conda-forge dependencies: - - beautifulsoup4 + - python=3.7.* + + # tools - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies + - beautifulsoup4 - html5lib - ipython - jinja2 @@ -17,7 +27,6 @@ dependencies: - openpyxl - pytables - python-dateutil - - python=3.7.* - pytz - s3fs - scipy @@ -25,11 +34,3 @@ dependencies: - xlrd - xlsxwriter - xlwt - # universal - - pytest>=5.0.1 - - pytest-xdist>=1.29.0 - - pytest-mock - - pytest-azurepipelines - - pip - - pip: - - hypothesis>=3.58.0 diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 0fb06fd43724c..3264df5944e35 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -3,14 +3,17 @@ channels: - defaults dependencies: - python=3.7.* - - pytz - - Cython>=0.29.13 - # universal - # pytest < 5 until defaults has pytest-xdist>=1.29.0 - - pytest>=4.0.2,<5.0 - - pytest-xdist + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 - pytest-mock - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies + - pytz - pip - pip: - "git+git://github.com/dateutil/dateutil.git" @@ -18,5 +21,3 @@ dependencies: - "--pre" - "numpy" - "scipy" - # https://github.com/pandas-dev/pandas/issues/27421 - - pytest-azurepipelines<1.0.0 diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-36.yaml index 85c090bf6f938..48ba87d26f53d 100644 --- a/ci/deps/azure-macos-36.yaml +++ b/ci/deps/azure-macos-36.yaml @@ -2,6 +2,17 @@ name: pandas-dev channels: - defaults dependencies: + - python=3.6.* + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies - beautifulsoup4 - bottleneck - html5lib @@ -14,7 +25,6 @@ dependencies: - openpyxl - pyarrow - pytables - - python=3.6.* - python-dateutil==2.6.1 - pytz - xarray @@ -23,13 +33,4 @@ dependencies: - xlwt - pip - pip: - # Anaconda / conda-forge don't build for 3.5 - - cython>=0.29.13 - pyreadstat - # universal - - pytest>=5.0.1 - - pytest-xdist>=1.29.0 - - pytest-mock - - hypothesis>=3.58.0 - # https://github.com/pandas-dev/pandas/issues/27421 - - pytest-azurepipelines<1.0.0 diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml index 88b38aaef237c..e3ad1d8371623 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-36.yaml @@ -3,6 +3,17 @@ channels: - conda-forge - defaults dependencies: + - python=3.6.* + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies - blosc - bottleneck - fastparquet>=0.2.1 @@ -13,16 +24,8 @@ dependencies: - pyarrow - pytables - python-dateutil - - python=3.6.* - pytz - scipy - xlrd - xlsxwriter - xlwt - # universal - - cython>=0.29.13 - - pytest>=5.0.1 - - pytest-xdist>=1.29.0 - - pytest-mock - - pytest-azurepipelines - - hypothesis>=3.58.0 diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 7680ed9fd9c92..07e134b054c10 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -3,6 +3,17 @@ channels: - defaults - conda-forge dependencies: + - python=3.7.* + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-azurepipelines + + # pandas dependencies - beautifulsoup4 - bottleneck - gcsfs @@ -15,7 +26,6 @@ dependencies: - numpy=1.14.* - openpyxl - pytables - - python=3.7.* - python-dateutil - pytz - s3fs @@ -24,11 +34,4 @@ dependencies: - xlrd - xlsxwriter - xlwt - # universal - - cython>=0.29.13 - - pytest>=5.0.0 - - pytest-xdist>=1.29.0 - - pytest-mock - - pytest-azurepipelines - - hypothesis>=3.58.0 - pyreadstat diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml index b2a74fceaf0fa..9148e0d4b29d9 100644 --- a/ci/deps/travis-36-cov.yaml +++ b/ci/deps/travis-36-cov.yaml @@ -3,6 +3,17 @@ channels: - defaults - conda-forge dependencies: + - python=3.6.* + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + - pytest-cov # this is only needed in the coverage build + + # pandas dependencies - beautifulsoup4 - botocore>=1.11 - cython>=0.29.13 @@ -27,7 +38,6 @@ dependencies: - pymysql - pytables - python-snappy - - python=3.6.* - pytz - s3fs - scikit-learn @@ -38,12 +48,6 @@ dependencies: - xlrd - xlsxwriter - xlwt - # universal - - pytest>=5.0.1 - - pytest-xdist>=1.29.0 - - pytest-cov - - pytest-mock - - hypothesis>=3.58.0 - pip - pip: - brotlipy diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index 09f72e65098c9..3199ee037bc0a 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -3,10 +3,19 @@ channels: - defaults - conda-forge dependencies: + - python=3.6.* + + # tools + - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + + # pandas dependencies - beautifulsoup4 - blosc=1.14.3 - python-blosc - - cython>=0.29.13 - fastparquet=0.2.1 - gcsfs=0.2.2 - html5lib @@ -24,7 +33,6 @@ dependencies: - pymysql=0.7.11 - pytables - python-dateutil - - python=3.6.* - pytz - s3fs=0.3.0 - scipy @@ -33,10 +41,3 @@ dependencies: - xlrd - xlsxwriter - xlwt - # universal - - pytest>=5.0.1 - - pytest-xdist>=1.29.0 - - pytest-mock - - pip - - pip: - - hypothesis>=3.58.0 diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml index e9c5dadbc924a..eab374c96772c 100644 --- a/ci/deps/travis-36-slow.yaml +++ b/ci/deps/travis-36-slow.yaml @@ -3,8 +3,17 @@ channels: - defaults - conda-forge dependencies: - - beautifulsoup4 + - python=3.6.* + + # tools - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + + # pandas dependencies + - beautifulsoup4 - html5lib - lxml - matplotlib @@ -16,7 +25,6 @@ dependencies: - pymysql - pytables - python-dateutil - - python=3.6.* - pytz - s3fs - scipy @@ -24,9 +32,4 @@ dependencies: - xlrd - xlsxwriter - xlwt - # universal - - pytest>=5.0.0 - - pytest-xdist>=1.29.0 - - pytest-mock - moto - - hypothesis>=3.58.0 diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index 903636f2fe060..7b75a427a4954 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -5,20 +5,23 @@ channels: - c3i_test dependencies: - python=3.7.* - - botocore>=1.11 + + # tools - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.21 + - pytest-mock + - hypothesis>=3.58.0 + + # pandas dependencies + - botocore>=1.11 - numpy - python-dateutil - nomkl - pyarrow - pytz - # universal - - pytest>=5.0.0 - - pytest-xdist>=1.29.0 - - pytest-mock - - hypothesis>=3.58.0 - s3fs - - pip - pyreadstat + - pip - pip: - moto diff --git a/ci/deps/travis-38.yaml b/ci/deps/travis-38.yaml index bd62ffa9248fe..88da1331b463a 100644 --- a/ci/deps/travis-38.yaml +++ b/ci/deps/travis-38.yaml @@ -4,13 +4,16 @@ channels: - conda-forge dependencies: - python=3.8.* + + # tools - cython>=0.29.13 + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 # The rest of the builds use >=1.21, and use pytest-mock + - hypothesis>=3.58.0 + + # pandas dependencies - numpy - python-dateutil - nomkl - pytz - # universal - - pytest>=5.0.0 - - pytest-xdist>=1.29.0 - - hypothesis>=3.58.0 - pip diff --git a/environment.yml b/environment.yml index ef5767f26dceb..54c99f415165d 100644 --- a/environment.yml +++ b/environment.yml @@ -51,7 +51,7 @@ dependencies: - botocore>=1.11 - hypothesis>=3.82 - moto # mock S3 - - pytest>=4.0.2 + - pytest>=5.0.1 - pytest-cov - pytest-xdist>=1.21 - seaborn diff --git a/requirements-dev.txt b/requirements-dev.txt index 3ae5b57de5d02..87b348c39a17b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -30,7 +30,7 @@ boto3 botocore>=1.11 hypothesis>=3.82 moto -pytest>=4.0.2 +pytest>=5.0.1 pytest-cov pytest-xdist>=1.21 seaborn
- [X] closes #29664 In our CI builds we're using different versions of pytest, pytest-xdist and other tools. Looks like Python 3.5 was forcing part of this, since some packages were not available. In this PR I standardize the tools and versions we use in all packages, with only two exceptions: - In 32 bits we install `Cython` from pip instead of conda, since conda doesn't have the version we want - `pytest-azurepipelines` is installed only in builds currently running in pipelines I also reorganize a bit the builds so dependencies are easier to find. First is always Python, then the block with the tools, which is always the same with the exceptions mentioned above, and finally the dependencies.
https://api.github.com/repos/pandas-dev/pandas/pulls/29678
2019-11-17T20:19:47Z
2019-11-21T13:06:07Z
2019-11-21T13:06:07Z
2019-11-21T13:07:04Z
CLN: parts of #29667
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index de2133f64291d..72f2e1d8e23e5 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -11,7 +11,7 @@ from pandas.core.computation.engines import _engines from pandas.core.computation.expr import Expr, _parsers, tokenize_string -from pandas.core.computation.scope import _ensure_scope +from pandas.core.computation.scope import ensure_scope from pandas.io.formats.printing import pprint_thing @@ -309,7 +309,7 @@ def eval( _check_for_locals(expr, level, parser) # get our (possibly passed-in) scope - env = _ensure_scope( + env = ensure_scope( level + 1, global_dict=global_dict, local_dict=local_dict, diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index ce67c3152ecd0..524013ceef5ff 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -197,7 +197,9 @@ class Op: Hold an operator of arbitrary arity. """ - def __init__(self, op, operands, *args, **kwargs): + op: str + + def __init__(self, op: str, operands, *args, **kwargs): self.op = _bool_op_map.get(op, op) self.operands = operands self.encoding = kwargs.get("encoding", None) diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 13a4814068d6a..8306c634d14e8 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -13,7 +13,7 @@ import pandas as pd import pandas.core.common as com -from pandas.core.computation import expr, ops +from pandas.core.computation import expr, ops, scope as _scope from pandas.core.computation.common import _ensure_decoded from pandas.core.computation.expr import BaseExprVisitor from pandas.core.computation.ops import UndefinedVariableError, is_term @@ -21,10 +21,10 @@ from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded -class Scope(expr.Scope): +class Scope(_scope.Scope): __slots__ = ("queryables",) - def __init__(self, level, global_dict=None, local_dict=None, queryables=None): + def __init__(self, level: int, global_dict=None, local_dict=None, queryables=None): super().__init__(level + 1, global_dict=global_dict, local_dict=local_dict) self.queryables = queryables or dict() @@ -40,6 +40,7 @@ def __init__(self, name, env, side=None, encoding=None): def _resolve_name(self): # must be a queryables if self.side == "left": + # Note: The behavior of __new__ ensures that self.name is a str here if self.name not in self.env.queryables: raise NameError("name {name!r} is not defined".format(name=self.name)) return self.name diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index ee82664f6cb21..2c5c687a44680 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -16,9 +16,9 @@ from pandas.compat.chainmap import DeepChainMap -def _ensure_scope( - level, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs -): +def ensure_scope( + level: int, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs +) -> "Scope": """Ensure that we are grabbing the correct scope.""" return Scope( level + 1, @@ -119,7 +119,7 @@ def __init__( self.scope.update(local_dict.scope) if local_dict.target is not None: self.target = local_dict.target - self.update(local_dict.level) + self._update(local_dict.level) frame = sys._getframe(self.level) @@ -251,7 +251,7 @@ def _get_vars(self, stack, scopes): # scope after the loop del frame - def update(self, level: int): + def _update(self, level: int): """ Update the current scope by going back `level` levels.
Breaks off easier parts
https://api.github.com/repos/pandas-dev/pandas/pulls/29677
2019-11-17T19:49:22Z
2019-11-18T00:20:37Z
2019-11-18T00:20:37Z
2019-11-18T00:46:42Z
TYP: Add type hint for BaseGrouper in groupby._Groupby
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 294cb723eee1a..3199f166d5b3f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -48,7 +48,7 @@ class providing the base-class of operations. from pandas.core.construction import extract_array from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame -from pandas.core.groupby import base +from pandas.core.groupby import base, ops from pandas.core.index import CategoricalIndex, Index, MultiIndex from pandas.core.series import Series from pandas.core.sorting import get_group_index_sorter @@ -345,7 +345,7 @@ def __init__( keys=None, axis: int = 0, level=None, - grouper=None, + grouper: "Optional[ops.BaseGrouper]" = None, exclusions=None, selection=None, as_index: bool = True, @@ -2480,7 +2480,7 @@ def get_groupby( by=None, axis: int = 0, level=None, - grouper=None, + grouper: "Optional[ops.BaseGrouper]" = None, exclusions=None, selection=None, as_index: bool = True, diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 0edc3e4a4ff3d..74f96fb9d8def 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -26,8 +26,8 @@ from pandas.core.arrays import Categorical, ExtensionArray import pandas.core.common as com from pandas.core.frame import DataFrame +from pandas.core.groupby import ops from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby -from pandas.core.groupby.ops import BaseGrouper from pandas.core.index import CategoricalIndex, Index, MultiIndex from pandas.core.series import Series @@ -392,7 +392,7 @@ def ngroups(self) -> int: @cache_readonly def indices(self): # we have a list of groupers - if isinstance(self.grouper, BaseGrouper): + if isinstance(self.grouper, ops.BaseGrouper): return self.grouper.indices values = ensure_categorical(self.grouper) @@ -419,7 +419,7 @@ def group_index(self) -> Index: def _make_codes(self) -> None: if self._codes is None or self._group_index is None: # we have a list of groupers - if isinstance(self.grouper, BaseGrouper): + if isinstance(self.grouper, ops.BaseGrouper): codes = self.grouper.codes_info uniques = self.grouper.result_index else: @@ -442,7 +442,7 @@ def get_grouper( observed: bool = False, mutated: bool = False, validate: bool = True, -) -> Tuple[BaseGrouper, List[Hashable], FrameOrSeries]: +) -> "Tuple[ops.BaseGrouper, List[Hashable], FrameOrSeries]": """ Create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. @@ -524,7 +524,7 @@ def get_grouper( return grouper, [key.key], obj # already have a BaseGrouper, just return it - elif isinstance(key, BaseGrouper): + elif isinstance(key, ops.BaseGrouper): return key, [], obj # In the future, a tuple key will always mean an actual key, @@ -671,7 +671,7 @@ def is_in_obj(gpr) -> bool: groupings.append(Grouping(Index([], dtype="int"), np.array([], dtype=np.intp))) # create the internals grouper - grouper = BaseGrouper(group_axis, groupings, sort=sort, mutated=mutated) + grouper = ops.BaseGrouper(group_axis, groupings, sort=sort, mutated=mutated) return grouper, exclusions, obj
Add a type hint in class ``_Groupby`` for ``BaseGrouper`` to aid navigating the code base.
https://api.github.com/repos/pandas-dev/pandas/pulls/29675
2019-11-17T18:10:47Z
2019-11-17T20:55:54Z
2019-11-17T20:55:54Z
2019-11-18T06:48:39Z
CI: Use bash for windows script on azure
diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml index dfa82819b9826..86807b4010988 100644 --- a/ci/azure/windows.yml +++ b/ci/azure/windows.yml @@ -11,10 +11,12 @@ jobs: py36_np15: ENV_FILE: ci/deps/azure-windows-36.yaml CONDA_PY: "36" + PATTERN: "not slow and not network" py37_np141: ENV_FILE: ci/deps/azure-windows-37.yaml CONDA_PY: "37" + PATTERN: "not slow and not network" steps: - powershell: | @@ -22,38 +24,32 @@ jobs: Write-Host "##vso[task.prependpath]$HOME/miniconda3/bin" displayName: 'Add conda to PATH' - script: conda update -q -n base conda - displayName: Update conda - - script: | - call activate + displayName: 'Update conda' + - bash: | conda env create -q --file ci\\deps\\azure-windows-$(CONDA_PY).yaml displayName: 'Create anaconda environment' - - script: | - call activate pandas-dev - call conda list + - bash: | + source activate pandas-dev + conda list ci\\incremental\\build.cmd displayName: 'Build' - - script: | - call activate pandas-dev - pytest -m "not slow and not network" --junitxml=test-data.xml pandas -n 2 -r sxX --strict --durations=10 %* + - bash: | + source activate pandas-dev + ci/run_tests.sh displayName: 'Test' - task: PublishTestResults@2 inputs: testResultsFiles: 'test-data.xml' testRunTitle: 'Windows-$(CONDA_PY)' - powershell: | - $junitXml = "test-data.xml" - $(Get-Content $junitXml | Out-String) -match 'failures="(.*?)"' - if ($matches[1] -eq 0) - { + $(Get-Content "test-data.xml" | Out-String) -match 'failures="(.*?)"' + if ($matches[1] -eq 0) { Write-Host "No test failures in test-data" - } - else - { - # note that this will produce $LASTEXITCODE=1 - Write-Error "$($matches[1]) tests failed" + } else { + Write-Error "$($matches[1]) tests failed" # will produce $LASTEXITCODE=1 } displayName: 'Check for test failures' - - script: | + - bash: | source activate pandas-dev python ci/print_skipped.py displayName: 'Print skipped tests'
- Towards #26344 - This makes `windows.yml` and `posix.yml` steps pretty similar and they could potentially be merged/reduce duplication? (Will leave this for a separate PR) - We also now use `ci/run_tests.sh` for windows test stage. Reference https://github.com/pandas-dev/pandas/pull/27195 where I began this.
https://api.github.com/repos/pandas-dev/pandas/pulls/29674
2019-11-17T17:59:27Z
2019-11-19T04:06:58Z
2019-11-19T04:06:58Z
2019-12-25T20:35:11Z
CI: Pin black to version 19.10b0
diff --git a/environment.yml b/environment.yml index 325b79f07a61c..ef5767f26dceb 100644 --- a/environment.yml +++ b/environment.yml @@ -15,7 +15,7 @@ dependencies: - cython>=0.29.13 # code checks - - black>=19.10b0 + - black=19.10b0 - cpplint - flake8 - flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions diff --git a/requirements-dev.txt b/requirements-dev.txt index f589812e81635..3ae5b57de5d02 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,7 +3,7 @@ python-dateutil>=2.6.1 pytz asv cython>=0.29.13 -black>=19.10b0 +black==19.10b0 cpplint flake8 flake8-comprehensions>=3.1.0
This will pin black version in ci and for local dev. (This will avoid code checks failing when a new black version is released) As per comment from @jreback here https://github.com/pandas-dev/pandas/pull/29508#discussion_r346316578
https://api.github.com/repos/pandas-dev/pandas/pulls/29673
2019-11-17T16:59:06Z
2019-11-17T22:48:18Z
2019-11-17T22:48:17Z
2019-12-25T20:24:59Z
REF: align transform logic flow
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 6376dbefcf435..79e7ff5ea22ad 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -394,35 +394,39 @@ def _aggregate_named(self, func, *args, **kwargs): def transform(self, func, *args, **kwargs): func = self._get_cython_func(func) or func - if isinstance(func, str): - if not (func in base.transform_kernel_whitelist): - msg = "'{func}' is not a valid function name for transform(name)" - raise ValueError(msg.format(func=func)) - if func in base.cythonized_kernels: - # cythonized transform or canned "agg+broadcast" - return getattr(self, func)(*args, **kwargs) - else: - # If func is a reduction, we need to broadcast the - # result to the whole group. Compute func result - # and deal with possible broadcasting below. - return self._transform_fast( - lambda: getattr(self, func)(*args, **kwargs), func - ) + if not isinstance(func, str): + return self._transform_general(func, *args, **kwargs) + + elif func not in base.transform_kernel_whitelist: + msg = f"'{func}' is not a valid function name for transform(name)" + raise ValueError(msg) + elif func in base.cythonized_kernels: + # cythonized transform or canned "agg+broadcast" + return getattr(self, func)(*args, **kwargs) - # reg transform + # If func is a reduction, we need to broadcast the + # result to the whole group. Compute func result + # and deal with possible broadcasting below. + result = getattr(self, func)(*args, **kwargs) + return self._transform_fast(result, func) + + def _transform_general(self, func, *args, **kwargs): + """ + Transform with a non-str `func`. + """ klass = self._selected_obj.__class__ + results = [] - wrapper = lambda x: func(x, *args, **kwargs) for name, group in self: object.__setattr__(group, "name", name) - res = wrapper(group) + res = func(group, *args, **kwargs) if isinstance(res, (ABCDataFrame, ABCSeries)): res = res._values indexer = self._get_index(name) - s = klass(res, indexer) - results.append(s) + ser = klass(res, indexer) + results.append(ser) # check for empty "results" to avoid concat ValueError if results: @@ -433,7 +437,7 @@ def transform(self, func, *args, **kwargs): result = Series() # we will only try to coerce the result type if - # we have a numeric dtype, as these are *always* udfs + # we have a numeric dtype, as these are *always* user-defined funcs # the cython take a different path (and casting) dtype = self._selected_obj.dtype if is_numeric_dtype(dtype): @@ -443,17 +447,14 @@ def transform(self, func, *args, **kwargs): result.index = self._selected_obj.index return result - def _transform_fast(self, func, func_nm) -> Series: + def _transform_fast(self, result, func_nm: str) -> Series: """ fast version of transform, only applicable to builtin/cythonizable functions """ - if isinstance(func, str): - func = getattr(self, func) - ids, _, ngroup = self.grouper.group_info cast = self._transform_should_cast(func_nm) - out = algorithms.take_1d(func()._values, ids) + out = algorithms.take_1d(result._values, ids) if cast: out = self._try_cast(out, self.obj) return Series(out, index=self.obj.index, name=self.obj.name) @@ -1340,21 +1341,21 @@ def transform(self, func, *args, **kwargs): # optimized transforms func = self._get_cython_func(func) or func - if isinstance(func, str): - if not (func in base.transform_kernel_whitelist): - msg = "'{func}' is not a valid function name for transform(name)" - raise ValueError(msg.format(func=func)) - if func in base.cythonized_kernels: - # cythonized transformation or canned "reduction+broadcast" - return getattr(self, func)(*args, **kwargs) - else: - # If func is a reduction, we need to broadcast the - # result to the whole group. Compute func result - # and deal with possible broadcasting below. - result = getattr(self, func)(*args, **kwargs) - else: + if not isinstance(func, str): return self._transform_general(func, *args, **kwargs) + elif func not in base.transform_kernel_whitelist: + msg = f"'{func}' is not a valid function name for transform(name)" + raise ValueError(msg) + elif func in base.cythonized_kernels: + # cythonized transformation or canned "reduction+broadcast" + return getattr(self, func)(*args, **kwargs) + + # If func is a reduction, we need to broadcast the + # result to the whole group. Compute func result + # and deal with possible broadcasting below. + result = getattr(self, func)(*args, **kwargs) + # a reduction transform if not isinstance(result, DataFrame): return self._transform_general(func, *args, **kwargs) @@ -1365,9 +1366,9 @@ def transform(self, func, *args, **kwargs): if not result.columns.equals(obj.columns): return self._transform_general(func, *args, **kwargs) - return self._transform_fast(result, obj, func) + return self._transform_fast(result, func) - def _transform_fast(self, result: DataFrame, obj: DataFrame, func_nm) -> DataFrame: + def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame: """ Fast transform path for aggregations """ @@ -1375,6 +1376,8 @@ def _transform_fast(self, result: DataFrame, obj: DataFrame, func_nm) -> DataFra # try casting data to original dtype cast = self._transform_should_cast(func_nm) + obj = self._obj_with_exclusions + # for each col, reshape to to size of original frame # by take operation ids, _, ngroup = self.grouper.group_info
Implement SeriesGroupBy._transform_general to match DataFrameGroupBy._transform_general, re-arrange the checks within the two `transform` methods to be in the same order and be more linear. Make the two _transform_fast methods have closer-to-matching signatures
https://api.github.com/repos/pandas-dev/pandas/pulls/29672
2019-11-17T16:40:28Z
2019-11-19T13:30:18Z
2019-11-19T13:30:18Z
2019-11-19T15:20:55Z
Extension Module Compat Cleanup
diff --git a/pandas/_libs/src/compat_helper.h b/pandas/_libs/src/compat_helper.h index 078069fb48af2..01d5b843d1bb6 100644 --- a/pandas/_libs/src/compat_helper.h +++ b/pandas/_libs/src/compat_helper.h @@ -38,13 +38,8 @@ PANDAS_INLINE int slice_get_indices(PyObject *s, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) { -#if PY_VERSION_HEX >= 0x03000000 return PySlice_GetIndicesEx(s, length, start, stop, step, slicelength); -#else - return PySlice_GetIndicesEx((PySliceObject *)s, length, start, - stop, step, slicelength); -#endif // PY_VERSION_HEX } #endif // PANDAS__LIBS_SRC_COMPAT_HELPER_H_ diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c index 5d73230f32955..aecd4e03664e6 100644 --- a/pandas/_libs/src/parser/io.c +++ b/pandas/_libs/src/parser/io.c @@ -17,7 +17,7 @@ The full license is in the LICENSE file, distributed with this software. #define O_BINARY 0 #endif // O_BINARY -#if PY_VERSION_HEX >= 0x03060000 && defined(_WIN32) +#ifdef _WIN32 #define USE_WIN_UTF16 #include <Windows.h> #endif
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29666
2019-11-17T03:46:26Z
2019-11-18T13:37:18Z
2019-11-18T13:37:18Z
2019-11-18T17:18:44Z
CLN: de-privatize names in core.computation
diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index dfb858d797f41..197ddd999fd37 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -8,10 +8,11 @@ from pandas.errors import PerformanceWarning -import pandas as pd +from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries + from pandas.core.base import PandasObject import pandas.core.common as com -from pandas.core.computation.common import _result_type_many +from pandas.core.computation.common import result_type_many def _align_core_single_unary_op(term): @@ -49,7 +50,7 @@ def wrapper(terms): # we don't have any pandas objects if not _any_pandas_objects(terms): - return _result_type_many(*term_values), None + return result_type_many(*term_values), None return f(terms) @@ -60,7 +61,10 @@ def wrapper(terms): def _align_core(terms): term_index = [i for i, term in enumerate(terms) if hasattr(term.value, "axes")] term_dims = [terms[i].value.ndim for i in term_index] - ndims = pd.Series(dict(zip(term_index, term_dims))) + + from pandas import Series + + ndims = Series(dict(zip(term_index, term_dims))) # initial axes are the axes of the largest-axis'd term biggest = terms[ndims.idxmax()].value @@ -70,7 +74,7 @@ def _align_core(terms): gt_than_one_axis = naxes > 1 for value in (terms[i].value for i in term_index): - is_series = isinstance(value, pd.Series) + is_series = isinstance(value, ABCSeries) is_series_and_gt_one_axis = is_series and gt_than_one_axis for axis, items in enumerate(value.axes): @@ -87,7 +91,7 @@ def _align_core(terms): ti = terms[i].value if hasattr(ti, "reindex"): - transpose = isinstance(ti, pd.Series) and naxes > 1 + transpose = isinstance(ti, ABCSeries) and naxes > 1 reindexer = axes[naxes - 1] if transpose else items term_axis_size = len(ti.axes[axis]) @@ -111,28 +115,28 @@ def _align_core(terms): return typ, _zip_axes_from_type(typ, axes) -def _align(terms): +def align_terms(terms): """Align a set of terms""" try: # flatten the parse tree (a nested list, really) terms = list(com.flatten(terms)) except TypeError: # can't iterate so it must just be a constant or single variable - if isinstance(terms.value, pd.core.generic.NDFrame): + if isinstance(terms.value, (ABCSeries, ABCDataFrame)): typ = type(terms.value) return typ, _zip_axes_from_type(typ, terms.value.axes) return np.result_type(terms.type), None # if all resolved variables are numeric scalars if all(term.is_scalar for term in terms): - return _result_type_many(*(term.value for term in terms)).type, None + return result_type_many(*(term.value for term in terms)).type, None # perform the main alignment typ, axes = _align_core(terms) return typ, axes -def _reconstruct_object(typ, obj, axes, dtype): +def reconstruct_object(typ, obj, axes, dtype): """ Reconstruct an object given its type, raw value, and possibly empty (None) axes. diff --git a/pandas/core/computation/common.py b/pandas/core/computation/common.py index bd32c8bee1cdf..da47449d5e62e 100644 --- a/pandas/core/computation/common.py +++ b/pandas/core/computation/common.py @@ -15,7 +15,7 @@ def _ensure_decoded(s): return s -def _result_type_many(*arrays_and_dtypes): +def result_type_many(*arrays_and_dtypes): """ wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32) argument limit """ try: diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py index 513eb0fd7f2a6..2f3c519d352c6 100644 --- a/pandas/core/computation/engines.py +++ b/pandas/core/computation/engines.py @@ -4,7 +4,7 @@ import abc -from pandas.core.computation.align import _align, _reconstruct_object +from pandas.core.computation.align import align_terms, reconstruct_object from pandas.core.computation.ops import UndefinedVariableError, _mathops, _reductions import pandas.io.formats.printing as printing @@ -67,11 +67,11 @@ def evaluate(self): The result of the passed expression. """ if not self._is_aligned: - self.result_type, self.aligned_axes = _align(self.expr.terms) + self.result_type, self.aligned_axes = align_terms(self.expr.terms) # make sure no names in resolvers and locals/globals clash res = self._evaluate() - return _reconstruct_object( + return reconstruct_object( self.result_type, res, self.aligned_axes, self.expr.terms.return_type ) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 461561a80a7e5..de2133f64291d 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -10,6 +10,7 @@ from pandas.util._validators import validate_bool_kwarg from pandas.core.computation.engines import _engines +from pandas.core.computation.expr import Expr, _parsers, tokenize_string from pandas.core.computation.scope import _ensure_scope from pandas.io.formats.printing import pprint_thing @@ -64,7 +65,7 @@ def _check_engine(engine): return engine -def _check_parser(parser): +def _check_parser(parser: str): """ Make sure a valid parser is passed. @@ -77,7 +78,6 @@ def _check_parser(parser): KeyError * If an invalid parser is passed """ - from pandas.core.computation.expr import _parsers if parser not in _parsers: raise KeyError( @@ -115,7 +115,7 @@ def _check_expression(expr): raise ValueError("expr cannot be an empty string") -def _convert_expression(expr): +def _convert_expression(expr) -> str: """ Convert an object to an expression. @@ -131,7 +131,7 @@ def _convert_expression(expr): Returns ------- - s : unicode + str The string representation of an object. Raises @@ -144,8 +144,7 @@ def _convert_expression(expr): return s -def _check_for_locals(expr, stack_level, parser): - from pandas.core.computation.expr import tokenize_string +def _check_for_locals(expr: str, stack_level: int, parser: str): at_top_of_stack = stack_level == 0 not_pandas_parser = parser != "pandas" @@ -192,7 +191,7 @@ def eval( Parameters ---------- - expr : str or unicode + expr : str The expression to evaluate. This string cannot contain any Python `statements <https://docs.python.org/3/reference/simple_stmts.html#simple-statements>`__, @@ -282,7 +281,6 @@ def eval( See the :ref:`enhancing performance <enhancingperf.eval>` documentation for more details. """ - from pandas.core.computation.expr import Expr inplace = validate_bool_kwarg(inplace, "inplace") diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 929c9e69d56ac..4d1fc42070ea8 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -11,7 +11,6 @@ import numpy as np -import pandas as pd import pandas.core.common as com from pandas.core.computation.common import ( _BACKTICK_QUOTED_STRING, @@ -40,7 +39,7 @@ import pandas.io.formats.printing as printing -def tokenize_string(source): +def tokenize_string(source: str): """ Tokenize a Python source code string. @@ -171,7 +170,7 @@ def _compose(*funcs): def _preparse( - source, + source: str, f=_compose( _replace_locals, _replace_booleans, @@ -600,6 +599,8 @@ def visit_Index(self, node, **kwargs): return self.visit(node.value) def visit_Subscript(self, node, **kwargs): + import pandas as pd + value = self.visit(node.value) slobj = self.visit(node.slice) result = pd.eval( diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 0fdbdda30ad35..ce67c3152ecd0 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -13,7 +13,7 @@ from pandas.core.dtypes.common import is_list_like, is_scalar import pandas.core.common as com -from pandas.core.computation.common import _ensure_decoded, _result_type_many +from pandas.core.computation.common import _ensure_decoded, result_type_many from pandas.core.computation.scope import _DEFAULT_GLOBALS from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded @@ -218,7 +218,7 @@ def return_type(self): # clobber types to bool if the op is a boolean operator if self.op in (_cmp_ops_syms + _bool_ops_syms): return np.bool_ - return _result_type_many(*(term.type for term in com.flatten(self))) + return result_type_many(*(term.type for term in com.flatten(self))) @property def has_invalid_return_type(self) -> bool:
Some annotations. I'm finding that annotations in this directory are really fragile; adding a type to one thing will cause a mypy complaint in somewhere surprising.
https://api.github.com/repos/pandas-dev/pandas/pulls/29665
2019-11-17T03:28:29Z
2019-11-17T13:34:26Z
2019-11-17T13:34:26Z
2019-11-17T15:38:11Z
CLN:f-string asv
diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py index adb3dd95e3574..b8e8630e663ee 100644 --- a/asv_bench/benchmarks/io/csv.py +++ b/asv_bench/benchmarks/io/csv.py @@ -132,7 +132,7 @@ class ReadCSVConcatDatetimeBadDateValue(StringIORewind): param_names = ["bad_date_value"] def setup(self, bad_date_value): - self.StringIO_input = StringIO(("%s,\n" % bad_date_value) * 50000) + self.StringIO_input = StringIO((f"{bad_date_value},\n") * 50000) def time_read_csv(self, bad_date_value): read_csv(
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry continuation of https://github.com/pandas-dev/pandas/pull/29571 ref #29547
https://api.github.com/repos/pandas-dev/pandas/pulls/29663
2019-11-16T19:11:22Z
2019-11-16T20:35:20Z
2019-11-16T20:35:20Z
2019-11-16T20:40:21Z
CLN:F-strings
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 684fbbc23c86c..f95dd8679308f 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -30,7 +30,7 @@ def set_function_name(f, name, cls): Bind the name/qualname attributes of the function. """ f.__name__ = name - f.__qualname__ = "{klass}.{name}".format(klass=cls.__name__, name=name) + f.__qualname__ = f"{cls.__name__}.{name}" f.__module__ = cls.__module__ return f diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 14425578786d7..fc66502710b0c 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -28,15 +28,6 @@ "xlsxwriter": "0.9.8", } -message = ( - "Missing optional dependency '{name}'. {extra} " - "Use pip or conda to install {name}." -) -version_message = ( - "Pandas requires version '{minimum_version}' or newer of '{name}' " - "(version '{actual_version}' currently installed)." -) - def _get_version(module: types.ModuleType) -> str: version = getattr(module, "__version__", None) @@ -45,7 +36,7 @@ def _get_version(module: types.ModuleType) -> str: version = getattr(module, "__VERSION__", None) if version is None: - raise ImportError("Can't determine version for {}".format(module.__name__)) + raise ImportError(f"Can't determine version for {module.__name__}") return version @@ -86,11 +77,15 @@ def import_optional_dependency( is False, or when the package's version is too old and `on_version` is ``'warn'``. """ + msg = ( + f"Missing optional dependency '{name}'. {extra} " + f"Use pip or conda to install {name}." + ) try: module = importlib.import_module(name) except ImportError: if raise_on_missing: - raise ImportError(message.format(name=name, extra=extra)) from None + raise ImportError(msg) from None else: return None @@ -99,8 +94,9 @@ def import_optional_dependency( version = _get_version(module) if distutils.version.LooseVersion(version) < minimum_version: assert on_version in {"warn", "raise", "ignore"} - msg = version_message.format( - minimum_version=minimum_version, name=name, actual_version=version + msg = ( + f"Pandas requires version '{minimum_version}' or newer of '{name}' " + f"(version '{version}' currently installed)." ) if on_version == "warn": warnings.warn(msg, UserWarning) diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index 402ed62f2df65..27f1c32058941 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -18,11 +18,11 @@ if _nlv < "1.13.3": raise ImportError( - "this version of pandas is incompatible with " - "numpy < 1.13.3\n" - "your numpy version is {0}.\n" - "Please upgrade numpy to >= 1.13.3 to use " - "this pandas version".format(_np_version) + f"this version of pandas is incompatible with " + f"numpy < 1.13.3\n" + f"your numpy version is {_np_version}.\n" + f"Please upgrade numpy to >= 1.13.3 to use " + f"this pandas version" ) diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index c2fe7d1dd12f4..ea5aaf6b6476d 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -58,9 +58,7 @@ def __call__(self, args, kwargs, fname=None, max_fname_arg_count=None, method=No fname, args, kwargs, max_fname_arg_count, self.defaults ) else: - raise ValueError( - "invalid validation method '{method}'".format(method=method) - ) + raise ValueError(f"invalid validation method '{method}'") ARGMINMAX_DEFAULTS = dict(out=None) @@ -312,9 +310,8 @@ def validate_take_with_convert(convert, args, kwargs): def validate_window_func(name, args, kwargs): numpy_args = ("axis", "dtype", "out") msg = ( - "numpy operations are not " - "valid with window objects. " - "Use .{func}() directly instead ".format(func=name) + f"numpy operations are not valid with window objects. " + f"Use .{name}() directly instead " ) if len(args) > 0: @@ -328,9 +325,8 @@ def validate_window_func(name, args, kwargs): def validate_rolling_func(name, args, kwargs): numpy_args = ("axis", "dtype", "out") msg = ( - "numpy operations are not " - "valid with window objects. " - "Use .rolling(...).{func}() instead ".format(func=name) + f"numpy operations are not valid with window objects. " + f"Use .rolling(...).{name}() instead " ) if len(args) > 0: @@ -344,9 +340,8 @@ def validate_rolling_func(name, args, kwargs): def validate_expanding_func(name, args, kwargs): numpy_args = ("axis", "dtype", "out") msg = ( - "numpy operations are not " - "valid with window objects. " - "Use .expanding(...).{func}() instead ".format(func=name) + f"numpy operations are not valid with window objects. " + f"Use .expanding(...).{name}() instead " ) if len(args) > 0: @@ -371,11 +366,9 @@ def validate_groupby_func(name, args, kwargs, allowed=None): if len(args) + len(kwargs) > 0: raise UnsupportedFunctionCall( - ( - "numpy operations are not valid " - "with groupby. Use .groupby(...)." - "{func}() instead".format(func=name) - ) + f"numpy operations are not valid with " + f"groupby. Use .groupby(...).{name}() " + f"instead" ) @@ -391,11 +384,9 @@ def validate_resampler_func(method, args, kwargs): if len(args) + len(kwargs) > 0: if method in RESAMPLER_NUMPY_OPS: raise UnsupportedFunctionCall( - ( - "numpy operations are not valid " - "with resample. Use .resample(...)." - "{func}() instead".format(func=method) - ) + f"numpy operations are not " + f"valid with resample. Use " + f".resample(...).{method}() instead" ) else: raise TypeError("too many arguments passed in") @@ -418,7 +409,4 @@ def validate_minmax_axis(axis): if axis is None: return if axis >= ndim or (axis < 0 and ndim + axis < 0): - raise ValueError( - "`axis` must be fewer than the number of " - "dimensions ({ndim})".format(ndim=ndim) - ) + raise ValueError(f"`axis` must be fewer than the number of dimensions ({ndim})")
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry ref https://github.com/pandas-dev/pandas/issues/29547
https://api.github.com/repos/pandas-dev/pandas/pulls/29662
2019-11-16T18:17:55Z
2019-11-16T20:30:04Z
2019-11-16T20:30:04Z
2019-11-16T20:40:46Z
CI: Forcing GitHub actions to activate
diff --git a/.github/workflows/activate.yml b/.github/workflows/activate.yml new file mode 100644 index 0000000000000..f6aede6289ebf --- /dev/null +++ b/.github/workflows/activate.yml @@ -0,0 +1,21 @@ +# Simple first task to activate GitHub actions. +# This won't run until is merged, but future actions will +# run on PRs, so we can see we don't break things in more +# complex actions added later, like real builds. +# +# TODO: Remove this once another action exists +name: Activate + +on: + push: + branches: master + pull_request: + branches: master + +jobs: + activate: + name: Activate actions + runs-on: ubuntu-latest + steps: + - name: Activate + run: echo "GitHub actions ok"
GitHub actions won't start running until the first action is committed. This PR adds a simple action with an echo, so we can activate GitHub actions risk free, and when we move an actual build, the action will run in the PR, and we can see that it works. Tested this action in a test repo, to make sure it works: https://github.com/datapythonista/xql/commit/cdc596df626da5f81980c773de94269546880753/checks?check_suite_id=314215608
https://api.github.com/repos/pandas-dev/pandas/pulls/29661
2019-11-16T14:56:22Z
2019-11-16T20:39:06Z
2019-11-16T20:39:06Z
2019-11-16T20:39:15Z
BUG: resolved problem with DataFrame.equals() (#28839)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 30a828064f812..bf30f2d356b44 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -451,6 +451,7 @@ Reshaping - Fix to ensure all int dtypes can be used in :func:`merge_asof` when using a tolerance value. Previously every non-int64 type would raise an erroneous ``MergeError`` (:issue:`28870`). - Better error message in :func:`get_dummies` when `columns` isn't a list-like value (:issue:`28383`) - Bug :meth:`Series.pct_change` where supplying an anchored frequency would throw a ValueError (:issue:`28664`) +- Bug where :meth:`DataFrame.equals` returned True incorrectly in some cases when two DataFrames had the same columns in different orders (:issue:`28839`) Sparse ^^^^^^ diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 8a9410c076f9b..0e6ba8a2c2a6a 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1394,12 +1394,12 @@ def equals(self, other): if len(self.blocks) != len(other.blocks): return False - # canonicalize block order, using a tuple combining the type - # name and then mgr_locs because there might be unconsolidated + # canonicalize block order, using a tuple combining the mgr_locs + # then type name because there might be unconsolidated # blocks (say, Categorical) which can only be distinguished by # the iteration order def canonicalize(block): - return (block.dtype.name, block.mgr_locs.as_array.tolist()) + return (block.mgr_locs.as_array.tolist(), block.dtype.name) self_blocks = sorted(self.blocks, key=canonicalize) other_blocks = sorted(other.blocks, key=canonicalize) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index dbd84f15d143c..c98bdab0df766 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -1297,3 +1297,10 @@ def test_make_block_no_pandas_array(): result = make_block(arr.to_numpy(), slice(len(arr)), dtype=arr.dtype) assert result.is_integer is True assert result.is_extension is False + + +def test_dataframe_not_equal(): + # see GH28839 + df1 = pd.DataFrame({"a": [1, 2], "b": ["s", "d"]}) + df2 = pd.DataFrame({"a": ["s", "d"], "b": [1, 2]}) + assert df1.equals(df2) is False
The function was returning True in case shown in added test. The cause of the problem was sorting Blocks of DataFrame by type, and then mgr_locs before comparison. It resulted in arranging the identical blocks in the same way, which resulted in having the same two lists of blocks. Changing sorting order to (mgr_locs, type) resolves the problem, while not interrupting the other aspects of comparison. - [x] closes #28839 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29657
2019-11-16T08:47:17Z
2019-11-19T13:31:14Z
2019-11-19T13:31:13Z
2019-11-19T16:44:36Z
TYP: annotations in core.indexes
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index a7cf2c20b0dec..f650a62bc5b74 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -1,4 +1,5 @@ import textwrap +from typing import List, Set import warnings from pandas._libs import NaT, lib @@ -64,7 +65,9 @@ ] -def get_objs_combined_axis(objs, intersect=False, axis=0, sort=True): +def get_objs_combined_axis( + objs, intersect: bool = False, axis=0, sort: bool = True +) -> Index: """ Extract combined index: return intersection or union (depending on the value of "intersect") of indexes on given axis, or None if all objects @@ -72,9 +75,8 @@ def get_objs_combined_axis(objs, intersect=False, axis=0, sort=True): Parameters ---------- - objs : list of objects - Each object will only be considered if it has a _get_axis - attribute. + objs : list + Series or DataFrame objects, may be mix of the two. intersect : bool, default False If True, calculate the intersection between indexes. Otherwise, calculate the union. @@ -87,26 +89,27 @@ def get_objs_combined_axis(objs, intersect=False, axis=0, sort=True): ------- Index """ - obs_idxes = [obj._get_axis(axis) for obj in objs if hasattr(obj, "_get_axis")] - if obs_idxes: - return _get_combined_index(obs_idxes, intersect=intersect, sort=sort) + obs_idxes = [obj._get_axis(axis) for obj in objs] + return _get_combined_index(obs_idxes, intersect=intersect, sort=sort) -def _get_distinct_objs(objs): +def _get_distinct_objs(objs: List[Index]) -> List[Index]: """ Return a list with distinct elements of "objs" (different ids). Preserves order. """ - ids = set() + ids: Set[int] = set() res = [] for obj in objs: - if not id(obj) in ids: + if id(obj) not in ids: ids.add(id(obj)) res.append(obj) return res -def _get_combined_index(indexes, intersect=False, sort=False): +def _get_combined_index( + indexes: List[Index], intersect: bool = False, sort: bool = False +) -> Index: """ Return the union or intersection of indexes. @@ -147,7 +150,7 @@ def _get_combined_index(indexes, intersect=False, sort=False): return index -def union_indexes(indexes, sort=True): +def union_indexes(indexes, sort=True) -> Index: """ Return the union of indexes. @@ -173,7 +176,7 @@ def union_indexes(indexes, sort=True): indexes, kind = _sanitize_and_check(indexes) - def _unique_indices(inds): + def _unique_indices(inds) -> Index: """ Convert indexes to lists and concatenate them, removing duplicates. diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5b57d3f096b0c..699994964ab40 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1650,7 +1650,7 @@ def _get_grouper_for_level(self, mapper, level=None): # Introspection Methods @property - def is_monotonic(self): + def is_monotonic(self) -> bool: """ Alias for is_monotonic_increasing. """ @@ -1691,7 +1691,7 @@ def is_monotonic_decreasing(self) -> bool: return self._engine.is_monotonic_decreasing @property - def _is_strictly_monotonic_increasing(self): + def _is_strictly_monotonic_increasing(self) -> bool: """ Return if the index is strictly monotonic increasing (only increasing) values. @@ -1708,7 +1708,7 @@ def _is_strictly_monotonic_increasing(self): return self.is_unique and self.is_monotonic_increasing @property - def _is_strictly_monotonic_decreasing(self): + def _is_strictly_monotonic_decreasing(self) -> bool: """ Return if the index is strictly monotonic decreasing (only decreasing) values. @@ -1725,7 +1725,7 @@ def _is_strictly_monotonic_decreasing(self): return self.is_unique and self.is_monotonic_decreasing @cache_readonly - def is_unique(self): + def is_unique(self) -> bool: """ Return if the index has unique values. """ @@ -1735,22 +1735,22 @@ def is_unique(self): def has_duplicates(self) -> bool: return not self.is_unique - def is_boolean(self): + def is_boolean(self) -> bool: return self.inferred_type in ["boolean"] - def is_integer(self): + def is_integer(self) -> bool: return self.inferred_type in ["integer"] - def is_floating(self): + def is_floating(self) -> bool: return self.inferred_type in ["floating", "mixed-integer-float", "integer-na"] - def is_numeric(self): + def is_numeric(self) -> bool: return self.inferred_type in ["integer", "floating"] - def is_object(self): + def is_object(self) -> bool: return is_object_dtype(self.dtype) - def is_categorical(self): + def is_categorical(self) -> bool: """ Check if the Index holds categorical data. @@ -1786,10 +1786,10 @@ def is_categorical(self): """ return self.inferred_type in ["categorical"] - def is_interval(self): + def is_interval(self) -> bool: return self.inferred_type in ["interval"] - def is_mixed(self): + def is_mixed(self) -> bool: return self.inferred_type in ["mixed"] def holds_integer(self): @@ -1868,7 +1868,7 @@ def _isnan(self): @cache_readonly def _nan_idxs(self): if self._can_hold_na: - w, = self._isnan.nonzero() + w = self._isnan.nonzero()[0] return w else: return np.array([], dtype=np.int64) @@ -4086,13 +4086,13 @@ def _assert_can_do_op(self, value): msg = "'value' must be a scalar, passed: {0}" raise TypeError(msg.format(type(value).__name__)) - def _is_memory_usage_qualified(self): + def _is_memory_usage_qualified(self) -> bool: """ Return a boolean if we need a qualified .info display. """ return self.is_object() - def is_type_compatible(self, kind): + def is_type_compatible(self, kind) -> bool: """ Whether the index type is compatible with the provided type. """ @@ -4131,14 +4131,14 @@ def is_type_compatible(self, kind): """ @Appender(_index_shared_docs["contains"] % _index_doc_kwargs) - def __contains__(self, key): + def __contains__(self, key) -> bool: hash(key) try: return key in self._engine except (OverflowError, TypeError, ValueError): return False - def contains(self, key): + def contains(self, key) -> bool: """ Return a boolean indicating whether the provided key is in the index. @@ -4199,7 +4199,7 @@ def __getitem__(self, key): else: return result - def _can_hold_identifiers_and_holds_name(self, name): + def _can_hold_identifiers_and_holds_name(self, name) -> bool: """ Faster check for ``name in self`` when we know `name` is a Python identifier (e.g. in NDFrame.__getattr__, which hits this to support @@ -4290,7 +4290,7 @@ def putmask(self, mask, value): # coerces to object return self.astype(object).putmask(mask, value) - def equals(self, other): + def equals(self, other) -> bool: """ Determine if two Index objects contain the same elements. @@ -4314,7 +4314,7 @@ def equals(self, other): com.values_from_object(self), com.values_from_object(other) ) - def identical(self, other): + def identical(self, other) -> bool: """ Similar to equals, but check that other comparable attributes are also equal. diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 49bb705e09469..819f8ac53197a 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -276,7 +276,7 @@ def _shallow_copy(self, values=None, dtype=None, **kwargs): dtype = self.dtype return super()._shallow_copy(values=values, dtype=dtype, **kwargs) - def _is_dtype_compat(self, other): + def _is_dtype_compat(self, other) -> bool: """ *this is an internal non-public method* @@ -407,7 +407,7 @@ def _reverse_indexer(self): return self._data._reverse_indexer() @Appender(_index_shared_docs["contains"] % _index_doc_kwargs) - def __contains__(self, key): + def __contains__(self, key) -> bool: # if key is a NaN, check if any NaN is in self. if is_scalar(key) and isna(key): return self.hasnans @@ -455,7 +455,7 @@ def _engine(self): # introspection @cache_readonly - def is_unique(self): + def is_unique(self) -> bool: return self._engine.is_unique @property diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index f694b85f1ca5d..ceb23f61ae15a 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -148,7 +148,7 @@ def wrapper(self, other): return wrapper @property - def _ndarray_values(self): + def _ndarray_values(self) -> np.ndarray: return self._data._ndarray_values # ------------------------------------------------------------------------ diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index aee9be20a1593..41f5eb90d51b0 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -410,7 +410,7 @@ def tz(self, value): tzinfo = tz @cache_readonly - def _is_dates_only(self): + def _is_dates_only(self) -> bool: """Return a boolean if we are only dates (and don't have a timezone)""" from pandas.io.formats.format import _is_dates_only @@ -1237,7 +1237,7 @@ def searchsorted(self, value, side="left", sorter=None): return self.values.searchsorted(value, side=side) - def is_type_compatible(self, typ): + def is_type_compatible(self, typ) -> bool: return typ == self.inferred_type or typ == "datetime" @property diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 4a75ab58b7a65..35e8405e0f1aa 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -343,7 +343,7 @@ def _engine(self): right = self._maybe_convert_i8(self.right) return IntervalTree(left, right, closed=self.closed) - def __contains__(self, key): + def __contains__(self, key) -> bool: """ return a boolean if this key is IN the index We *only* accept an Interval @@ -483,7 +483,7 @@ def _values(self): return self._data @cache_readonly - def _ndarray_values(self): + def _ndarray_values(self) -> np.ndarray: return np.array(self._data) def __array__(self, result=None): @@ -529,7 +529,7 @@ def inferred_type(self) -> str: return "interval" @Appender(Index.memory_usage.__doc__) - def memory_usage(self, deep=False): + def memory_usage(self, deep: bool = False) -> int: # we don't use an explicit engine # so return the bytes here return self.left.memory_usage(deep=deep) + self.right.memory_usage(deep=deep) @@ -542,7 +542,7 @@ def mid(self): return self._data.mid @cache_readonly - def is_monotonic(self): + def is_monotonic(self) -> bool: """ Return True if the IntervalIndex is monotonic increasing (only equal or increasing values), else False @@ -550,7 +550,7 @@ def is_monotonic(self): return self.is_monotonic_increasing @cache_readonly - def is_monotonic_increasing(self): + def is_monotonic_increasing(self) -> bool: """ Return True if the IntervalIndex is monotonic increasing (only equal or increasing values), else False @@ -1213,7 +1213,7 @@ def _format_space(self): def argsort(self, *args, **kwargs): return np.lexsort((self.right, self.left)) - def equals(self, other): + def equals(self, other) -> bool: """ Determines if two IntervalIndex objects contain the same elements """ @@ -1374,7 +1374,7 @@ def is_all_dates(self) -> bool: IntervalIndex._add_logical_methods_disabled() -def _is_valid_endpoint(endpoint): +def _is_valid_endpoint(endpoint) -> bool: """helper for interval_range to check if start/end are valid types""" return any( [ @@ -1386,7 +1386,7 @@ def _is_valid_endpoint(endpoint): ) -def _is_type_compatible(a, b): +def _is_type_compatible(a, b) -> bool: """helper for interval_range to check type compat of start/end/freq""" is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset)) is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset)) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7b02a99263266..f3a735511c96b 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1025,7 +1025,7 @@ def _shallow_copy_with_infer(self, values, **kwargs): return self._shallow_copy(values, **kwargs) @Appender(_index_shared_docs["contains"] % _index_doc_kwargs) - def __contains__(self, key): + def __contains__(self, key) -> bool: hash(key) try: self.get_loc(key) @@ -1043,10 +1043,10 @@ def _shallow_copy(self, values=None, **kwargs): return self.copy(**kwargs) @cache_readonly - def dtype(self): + def dtype(self) -> np.dtype: return np.dtype("O") - def _is_memory_usage_qualified(self): + def _is_memory_usage_qualified(self) -> bool: """ return a boolean if we need a qualified .info display """ def f(l): @@ -1055,18 +1055,18 @@ def f(l): return any(f(l) for l in self._inferred_type_levels) @Appender(Index.memory_usage.__doc__) - def memory_usage(self, deep=False): + def memory_usage(self, deep: bool = False) -> int: # we are overwriting our base class to avoid # computing .values here which could materialize # a tuple representation unnecessarily return self._nbytes(deep) @cache_readonly - def nbytes(self): + def nbytes(self) -> int: """ return the number of bytes in the underlying data """ return self._nbytes(False) - def _nbytes(self, deep=False): + def _nbytes(self, deep: bool = False) -> int: """ return the number of bytes in the underlying data deeply introspect the level data if deep=True @@ -1325,7 +1325,7 @@ def _constructor(self): def inferred_type(self) -> str: return "mixed" - def _get_level_number(self, level): + def _get_level_number(self, level) -> int: count = self.names.count(level) if (count > 1) and not is_integer(level): raise ValueError( @@ -1397,7 +1397,7 @@ def values(self): return self._tuples @cache_readonly - def is_monotonic_increasing(self): + def is_monotonic_increasing(self) -> bool: """ return if the index is monotonic increasing (only equal or increasing) values. @@ -1789,7 +1789,7 @@ def to_flat_index(self): def is_all_dates(self) -> bool: return False - def is_lexsorted(self): + def is_lexsorted(self) -> bool: """ Return True if the codes are lexicographically sorted. @@ -3126,7 +3126,7 @@ def truncate(self, before=None, after=None): return MultiIndex(levels=new_levels, codes=new_codes, verify_integrity=False) - def equals(self, other): + def equals(self, other) -> bool: """ Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) @@ -3459,7 +3459,7 @@ def isin(self, values, level=None): MultiIndex._add_logical_methods_disabled() -def _sparsify(label_list, start=0, sentinel=""): +def _sparsify(label_list, start: int = 0, sentinel=""): pivoted = list(zip(*label_list)) k = len(label_list) @@ -3487,7 +3487,7 @@ def _sparsify(label_list, start=0, sentinel=""): return list(zip(*result)) -def _get_na_rep(dtype): +def _get_na_rep(dtype) -> str: return {np.datetime64: "NaT", np.timedelta64: "NaT"}.get(dtype, "NaN") diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 3e2b41f62f30b..ee96e4cd699bb 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -206,7 +206,7 @@ class IntegerIndex(NumericIndex): This is an abstract class for Int64Index, UInt64Index. """ - def __contains__(self, key): + def __contains__(self, key) -> bool: """ Check if key is a float and has a decimal. If it has, return False. """ @@ -233,7 +233,7 @@ def inferred_type(self) -> str: return "integer" @property - def asi8(self): + def asi8(self) -> np.ndarray: # do not cache or you'll create a memory leak return self.values.view("i8") @@ -288,7 +288,7 @@ def inferred_type(self) -> str: return "integer" @property - def asi8(self): + def asi8(self) -> np.ndarray: # do not cache or you'll create a memory leak return self.values.view("u8") @@ -425,7 +425,7 @@ def get_value(self, series, key): return new_values - def equals(self, other): + def equals(self, other) -> bool: """ Determines if two Index objects contain the same elements. """ @@ -447,7 +447,7 @@ def equals(self, other): except (TypeError, ValueError): return False - def __contains__(self, other): + def __contains__(self, other) -> bool: if super().__contains__(other): return True @@ -482,7 +482,7 @@ def get_loc(self, key, method=None, tolerance=None): return super().get_loc(key, method=method, tolerance=tolerance) @cache_readonly - def is_unique(self): + def is_unique(self) -> bool: return super().is_unique and self._nan_idxs.size < 2 @Appender(Index.isin.__doc__) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 2df58b0bbc105..cae1380e930f1 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -310,7 +310,7 @@ def values(self): return np.asarray(self) @property - def freq(self): + def freq(self) -> DateOffset: return self._data.freq @freq.setter @@ -447,7 +447,7 @@ def _engine(self): return self._engine_type(period, len(self)) @Appender(_index_shared_docs["contains"]) - def __contains__(self, key): + def __contains__(self, key) -> bool: if isinstance(key, Period): if key.freq != self.freq: return False @@ -578,7 +578,7 @@ def is_all_dates(self) -> bool: return True @property - def is_full(self): + def is_full(self) -> bool: """ Returns True if this PeriodIndex is range-like in that all Periods between start and end are present, in order. @@ -995,7 +995,9 @@ def memory_usage(self, deep=False): PeriodIndex._add_datetimelike_methods() -def period_range(start=None, end=None, periods=None, freq=None, name=None): +def period_range( + start=None, end=None, periods=None, freq=None, name=None +) -> PeriodIndex: """ Return a fixed frequency PeriodIndex. diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 6f806c5bab6e4..d200ff6a71264 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -302,7 +302,7 @@ def _step(self): return self.step @cache_readonly - def nbytes(self): + def nbytes(self) -> int: """ Return the number of bytes in the underlying data. """ @@ -312,7 +312,7 @@ def nbytes(self): for attr_name in ["start", "stop", "step"] ) - def memory_usage(self, deep=False): + def memory_usage(self, deep: bool = False) -> int: """ Memory usage of my values @@ -338,16 +338,16 @@ def memory_usage(self, deep=False): return self.nbytes @property - def dtype(self): + def dtype(self) -> np.dtype: return np.dtype(np.int64) @property - def is_unique(self): + def is_unique(self) -> bool: """ return if the index has unique values """ return True @cache_readonly - def is_monotonic_increasing(self): + def is_monotonic_increasing(self) -> bool: return self._range.step > 0 or len(self) <= 1 @cache_readonly @@ -703,7 +703,7 @@ def __len__(self) -> int: return len(self._range) @property - def size(self): + def size(self) -> int: return len(self) def __getitem__(self, key): diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 6caac43af163b..1fd824235c2be 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -604,7 +604,7 @@ def searchsorted(self, value, side="left", sorter=None): return self.values.searchsorted(value, side=side, sorter=sorter) - def is_type_compatible(self, typ): + def is_type_compatible(self, typ) -> bool: return typ == self.inferred_type or typ == "timedelta" @property @@ -699,7 +699,7 @@ def delete(self, loc): TimedeltaIndex._add_datetimelike_methods() -def _is_convertible_to_index(other): +def _is_convertible_to_index(other) -> bool: """ return a boolean whether I can attempt conversion to a TimedeltaIndex """ @@ -719,7 +719,7 @@ def _is_convertible_to_index(other): def timedelta_range( start=None, end=None, periods=None, freq=None, name=None, closed=None -): +) -> TimedeltaIndex: """ Return a fixed frequency TimedeltaIndex, with day as the default frequency. diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 2980deb9a052c..6d518aa1abeb9 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -489,7 +489,9 @@ def _list_to_arrays(data, columns, coerce_float=False, dtype=None): def _list_of_series_to_arrays(data, columns, coerce_float=False, dtype=None): if columns is None: - columns = get_objs_combined_axis(data, sort=False) + # We know pass_data is non-empty because data[0] is a Series + pass_data = [x for x in data if isinstance(x, (ABCSeries, ABCDataFrame))] + columns = get_objs_combined_axis(pass_data, sort=False) indexer_cache = {} diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 3efe8072d3323..3e8d19096a36e 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -522,13 +522,9 @@ def _get_new_axes(self): def _get_comb_axis(self, i): data_axis = self.objs[0]._get_block_manager_axis(i) - try: - return get_objs_combined_axis( - self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort - ) - except IndexError: - types = [type(x).__name__ for x in self.objs] - raise TypeError("Cannot concatenate list of {types}".format(types=types)) + return get_objs_combined_axis( + self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort + ) def _get_concat_axis(self): """ diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 9ac27b0450bbe..0626420d9c114 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -541,7 +541,10 @@ def crosstab( rownames = _get_names(index, rownames, prefix="row") colnames = _get_names(columns, colnames, prefix="col") - common_idx = get_objs_combined_axis(index + columns, intersect=True, sort=False) + common_idx = None + pass_objs = [x for x in index + columns if isinstance(x, (ABCSeries, ABCDataFrame))] + if pass_objs: + common_idx = get_objs_combined_axis(pass_objs, intersect=True, sort=False) data = {} data.update(zip(rownames, index)) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index c237b094a0e01..9ec0dce438099 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -308,7 +308,7 @@ def deltas_asi8(self): return unique_deltas(self.index.asi8) @cache_readonly - def is_unique(self): + def is_unique(self) -> bool: return len(self.deltas) == 1 @cache_readonly
Changes the behavior of get_objs_combined_axis to ensure that it always returns an Index and never `None`, otherwise just annotations and some docstring cleanup
https://api.github.com/repos/pandas-dev/pandas/pulls/29656
2019-11-16T04:12:20Z
2019-11-16T20:49:41Z
2019-11-16T20:49:41Z
2019-11-16T22:23:33Z
CI: Fix error when creating postgresql db
diff --git a/ci/setup_env.sh b/ci/setup_env.sh index 4d454f9c5041a..0e8d6fb7cd35a 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -114,6 +114,11 @@ echo "w/o removing anything else" conda remove pandas -y --force || true pip uninstall -y pandas || true +echo +echo "remove postgres if has been installed with conda" +echo "we use the one from the CI" +conda remove postgresql -y --force || true + echo echo "conda list pandas" conda list pandas
- [X] closes #29643 Not sure if this makes sense, but let's try if this is the problem.
https://api.github.com/repos/pandas-dev/pandas/pulls/29655
2019-11-16T02:59:58Z
2019-11-16T16:47:14Z
2019-11-16T16:47:14Z
2019-11-16T16:47:14Z
CI: Format isort output for azure
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index ceb13c52ded9c..cfe55f1e05f71 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -105,7 +105,12 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then # Imports - Check formatting using isort see setup.cfg for settings MSG='Check import format using isort ' ; echo $MSG - isort --recursive --check-only pandas asv_bench + ISORT_CMD="isort --recursive --check-only pandas asv_bench" + if [[ "$GITHUB_ACTIONS" == "true" ]]; then + eval $ISORT_CMD | awk '{print "##[error]" $0}'; RET=$(($RET + ${PIPESTATUS[0]})) + else + eval $ISORT_CMD + fi RET=$(($RET + $?)) ; echo $MSG "DONE" fi
- [x] closes #27179 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Current behaviour on master of isort formatting: ![image](https://user-images.githubusercontent.com/16733618/69010035-12c41f80-0953-11ea-8e70-4d17e8dec943.png) Finishing up stale PR @https://github.com/pandas-dev/pandas/pull/27334
https://api.github.com/repos/pandas-dev/pandas/pulls/29654
2019-11-16T02:59:26Z
2019-12-06T01:10:29Z
2019-12-06T01:10:28Z
2019-12-25T20:27:02Z
CI: bump mypy 0.730
diff --git a/environment.yml b/environment.yml index a3582c56ee9d2..b4ffe9577b379 100644 --- a/environment.yml +++ b/environment.yml @@ -21,7 +21,7 @@ dependencies: - flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions - flake8-rst>=0.6.0,<=0.7.0 # linting of code blocks in rst files - isort # check that imports are in the right order - - mypy=0.720 + - mypy=0.730 - pycodestyle # used by flake8 # documentation diff --git a/requirements-dev.txt b/requirements-dev.txt index 6235b61d92f29..b963b9978da34 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -9,7 +9,7 @@ flake8 flake8-comprehensions>=3.1.0 flake8-rst>=0.6.0,<=0.7.0 isort -mypy==0.720 +mypy==0.730 pycodestyle gitpython sphinx diff --git a/setup.cfg b/setup.cfg index 10670a4eae387..46e6b88f8018a 100644 --- a/setup.cfg +++ b/setup.cfg @@ -145,10 +145,13 @@ ignore_errors=True [mypy-pandas.tests.extension.json.test_json] ignore_errors=True +[mypy-pandas.tests.indexes.datetimes.test_tools] +ignore_errors=True + [mypy-pandas.tests.indexes.test_base] ignore_errors=True -[mypy-pandas.tests.indexing.test_loc] +[mypy-pandas.tests.scalar.period.test_period] ignore_errors=True [mypy-pandas.tests.series.test_operators]
xref https://github.com/pandas-dev/pandas/pull/29188#issuecomment-554524916
https://api.github.com/repos/pandas-dev/pandas/pulls/29653
2019-11-16T01:39:31Z
2019-11-17T14:27:19Z
2019-11-17T14:27:19Z
2019-11-20T13:09:07Z