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
DEPR: Enforce deprecation of dropping columns when numeric_only=False in groupby / resample
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 1ca513e8f5e6a..c51c859040c16 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -557,6 +557,7 @@ Removal of prior version deprecations/changes - Enforced deprecation ``numeric_only=None`` (the default) in DataFrame reductions that would silently drop columns that raised; ``numeric_only`` now defaults to ``False`` (:issue:`41480`) - Changed default of ``numeric_only`` to ``False`` in all DataFrame methods with that argument (:issue:`46096`, :issue:`46906`) - Changed default of ``numeric_only`` to ``False`` in :meth:`Series.rank` (:issue:`47561`) +- Enforced deprecation of silently dropping nuisance columns in groupby and resample operations when ``numeric_only=False`` (:issue:`41475`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 571559dc838f5..4ac701952e258 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1357,7 +1357,13 @@ def arr_func(bvalues: ArrayLike) -> ArrayLike: # We could use `mgr.apply` here and not have to set_axis, but # we would have to do shape gymnastics for ArrayManager compat - res_mgr = mgr.grouped_reduce(arr_func, ignore_failures=True) + try: + res_mgr = mgr.grouped_reduce( + arr_func, ignore_failures=numeric_only is lib.no_default + ) + except NotImplementedError as err: + # For NotImplementedError, args[0] is the error message + raise TypeError(err.args[0]) from err res_mgr.set_axis(1, mgr.axes[1]) if len(res_mgr) < orig_mgr_len: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 5a1108c17e631..7a225712b63a7 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1655,6 +1655,7 @@ def _agg_general( alt=npfunc, numeric_only=numeric_only, min_count=min_count, + ignore_failures=numeric_only is lib.no_default, ) return result.__finalize__(self.obj, method="groupby") @@ -2123,6 +2124,7 @@ def mean( "mean", alt=lambda x: Series(x).mean(numeric_only=numeric_only_bool), numeric_only=numeric_only, + ignore_failures=numeric_only is lib.no_default, ) return result.__finalize__(self.obj, method="groupby") @@ -2152,6 +2154,7 @@ def median(self, numeric_only: bool | lib.NoDefault = lib.no_default): "median", alt=lambda x: Series(x).median(numeric_only=numeric_only_bool), numeric_only=numeric_only, + ignore_failures=numeric_only is lib.no_default, ) return result.__finalize__(self.obj, method="groupby") @@ -3756,7 +3759,9 @@ def blk_func(values: ArrayLike) -> ArrayLike: if numeric_only_bool: mgr = mgr.get_numeric_data() - res_mgr = mgr.grouped_reduce(blk_func, ignore_failures=True) + res_mgr = mgr.grouped_reduce( + blk_func, ignore_failures=numeric_only is lib.no_default + ) if not is_ser and len(res_mgr.items) != orig_mgr_len: howstr = how.replace("group_", "") diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index f05874c3286c7..4adf2d5f38ead 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -163,14 +163,12 @@ def test_averages(self, df, method): "int", "float", "category_int", - "datetime", - "datetimetz", - "timedelta", ], ) - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid"): - result = getattr(gb, method)(numeric_only=False) + with pytest.raises(TypeError, match="[Cc]ould not convert"): + getattr(gb, method)(numeric_only=False) + result = getattr(gb, method)() tm.assert_frame_equal(result.reindex_like(expected), expected) expected_columns = expected.columns @@ -252,30 +250,35 @@ def test_cummin_cummax(self, df, method): def _check(self, df, method, expected_columns, expected_columns_numeric): gb = df.groupby("group") - # cummin, cummax dont have numeric_only kwarg, always use False - warn = None - if method in ["cummin", "cummax"]: - # these dont have numeric_only kwarg, always use False - warn = FutureWarning - elif method in ["min", "max"]: - # these have numeric_only kwarg, but default to False - warn = FutureWarning - - with tm.assert_produces_warning( - warn, match="Dropping invalid columns", raise_on_extra_warnings=False - ): + if method in ("min", "max", "cummin", "cummax"): + # The methods default to numeric_only=False and raise TypeError + msg = "|".join( + [ + "Categorical is not ordered", + "function is not implemented for this dtype", + ] + ) + with pytest.raises(TypeError, match=msg): + getattr(gb, method)() + else: result = getattr(gb, method)() - - tm.assert_index_equal(result.columns, expected_columns_numeric) - - # GH#41475 deprecated silently ignoring nuisance columns - warn = None - if len(expected_columns) < len(gb._obj_with_exclusions.columns): - warn = FutureWarning - with tm.assert_produces_warning(warn, match="Dropping invalid columns"): + tm.assert_index_equal(result.columns, expected_columns_numeric) + + if method not in ("first", "last"): + msg = "|".join( + [ + "[Cc]ould not convert", + "Categorical is not ordered", + "category type does not support", + "can't multiply sequence", + "function is not implemented for this dtype", + ] + ) + with pytest.raises(TypeError, match=msg): + getattr(gb, method)(numeric_only=False) + else: result = getattr(gb, method)(numeric_only=False) - - tm.assert_index_equal(result.columns, expected_columns) + tm.assert_index_equal(result.columns, expected_columns) class TestGroupByNonCythonPaths: @@ -1323,45 +1326,45 @@ def test_groupby_sum_timedelta_with_nat(): @pytest.mark.parametrize( - "kernel, numeric_only_default, drops_nuisance, has_arg", + "kernel, numeric_only_default, has_arg", [ - ("all", False, False, False), - ("any", False, False, False), - ("bfill", False, False, False), - ("corr", True, False, True), - ("corrwith", True, False, True), - ("cov", True, False, True), - ("cummax", False, True, True), - ("cummin", False, True, True), - ("cumprod", True, True, True), - ("cumsum", True, True, True), - ("diff", False, False, False), - ("ffill", False, False, False), - ("fillna", False, False, False), - ("first", False, False, True), - ("idxmax", True, False, True), - ("idxmin", True, False, True), - ("last", False, False, True), - ("max", False, True, True), - ("mean", True, True, True), - ("median", True, True, True), - ("min", False, True, True), - ("nth", False, False, False), - ("nunique", False, False, False), - ("pct_change", False, False, False), - ("prod", True, True, True), - ("quantile", True, False, True), - ("sem", True, True, True), - ("skew", True, False, True), - ("std", True, True, True), - ("sum", True, True, True), - ("var", True, False, True), + ("all", False, False), + ("any", False, False), + ("bfill", False, False), + ("corr", True, True), + ("corrwith", True, True), + ("cov", True, True), + ("cummax", False, True), + ("cummin", False, True), + ("cumprod", True, True), + ("cumsum", True, True), + ("diff", False, False), + ("ffill", False, False), + ("fillna", False, False), + ("first", False, True), + ("idxmax", True, True), + ("idxmin", True, True), + ("last", False, True), + ("max", False, True), + ("mean", True, True), + ("median", True, True), + ("min", False, True), + ("nth", False, False), + ("nunique", False, False), + ("pct_change", False, False), + ("prod", True, True), + ("quantile", True, True), + ("sem", True, True), + ("skew", True, True), + ("std", True, True), + ("sum", True, True), + ("var", True, True), ], ) @pytest.mark.parametrize("numeric_only", [True, False, lib.no_default]) @pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) def test_deprecate_numeric_only( - kernel, numeric_only_default, drops_nuisance, has_arg, numeric_only, keys + kernel, numeric_only_default, has_arg, numeric_only, keys ): # GH#46072 # drops_nuisance: Whether the op drops nuisance columns even when numeric_only=False @@ -1380,10 +1383,9 @@ def test_deprecate_numeric_only( # Cases where b does not appear in the result numeric_only is True or (numeric_only is lib.no_default and numeric_only_default) - or drops_nuisance ) ): - if numeric_only is True or (not numeric_only_default and not drops_nuisance): + if numeric_only is True or not numeric_only_default: warn = None else: warn = FutureWarning @@ -1408,14 +1410,17 @@ def test_deprecate_numeric_only( assert "b" in result.columns elif has_arg or kernel in ("idxmax", "idxmin"): assert numeric_only is not True - assert not drops_nuisance # kernels that are successful on any dtype were above; this will fail - msg = ( - "(not allowed for this dtype" - "|must be a string or a number" - "|cannot be performed against 'object' dtypes" - "|must be a string or a real number" - "|unsupported operand type)" + msg = "|".join( + [ + "not allowed for this dtype", + "must be a string or a number", + "cannot be performed against 'object' dtypes", + "must be a string or a real number", + "unsupported operand type", + "not supported between instances of", + "function is not implemented for this dtype", + ] ) with pytest.raises(TypeError, match=msg): method(*args, **kwargs) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 7fd52d3cf5bb8..96be7a0cb785c 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -915,11 +915,13 @@ def test_omit_nuisance_agg(df, agg_function, numeric_only): grouped = df.groupby("A") - if agg_function in ("var", "std", "sem") and numeric_only is False: + no_drop_nuisance = ("var", "std", "sem", "mean", "prod", "median") + if agg_function in no_drop_nuisance and numeric_only is False: # Added numeric_only as part of GH#46560; these do not drop nuisance # columns when numeric_only is False - klass = TypeError if agg_function == "var" else ValueError - with pytest.raises(klass, match="could not convert string to float"): + klass = ValueError if agg_function in ("std", "sem") else TypeError + msg = "|".join(["[C|c]ould not convert", "can't multiply sequence"]) + with pytest.raises(klass, match=msg): getattr(grouped, agg_function)(numeric_only=numeric_only) else: if numeric_only is lib.no_default: @@ -2049,10 +2051,13 @@ def get_result(): and isinstance(values, Categorical) and len(keys) == 1 ): + if op in ("min", "max"): + with pytest.raises(TypeError, match="Categorical is not ordered"): + get_result() + return # Categorical doesn't implement, so with numeric_only=True # these are dropped and we get an empty DataFrame back result = get_result() - expected = df.set_index(keys)[[]] # with numeric_only=True, these are dropped, and we get # an empty DataFrame back diff --git a/pandas/tests/groupby/test_min_max.py b/pandas/tests/groupby/test_min_max.py index b26ee057d2041..72772775b3fa1 100644 --- a/pandas/tests/groupby/test_min_max.py +++ b/pandas/tests/groupby/test_min_max.py @@ -48,15 +48,17 @@ def test_max_min_object_multiple_columns(using_array_manager): gb = df.groupby("A") - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid"): - result = gb.max(numeric_only=False) + with pytest.raises(TypeError, match="not supported between instances"): + gb.max(numeric_only=False) + result = gb[["C"]].max() # "max" is valid for column "C" but not for "B" ei = Index([1, 2, 3], name="A") expected = DataFrame({"C": ["b", "d", "e"]}, index=ei) tm.assert_frame_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid"): - result = gb.min(numeric_only=False) + with pytest.raises(TypeError, match="not supported between instances"): + gb.max(numeric_only=False) + result = gb[["C"]].min() # "min" is valid for column "C" but not for "B" ei = Index([1, 2, 3], name="A") expected = DataFrame({"C": ["a", "c", "e"]}, index=ei) diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 5721de9e5f3bb..ca5444fd4e62f 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -821,8 +821,8 @@ def test_end_and_end_day_origin( ("sum", False, {"cat": ["cat_1cat_2"], "num": [25]}), ("sum", lib.no_default, {"num": [25]}), ("prod", True, {"num": [100]}), - ("prod", False, {"num": [100]}), - ("prod", lib.no_default, {"num": [100]}), + ("prod", False, "can't multiply sequence"), + ("prod", lib.no_default, "can't multiply sequence"), ("min", True, {"num": [5]}), ("min", False, {"cat": ["cat_1"], "num": [5]}), ("min", lib.no_default, {"cat": ["cat_1"], "num": [5]}), @@ -836,10 +836,10 @@ def test_end_and_end_day_origin( ("last", False, {"cat": ["cat_2"], "num": [20]}), ("last", lib.no_default, {"cat": ["cat_2"], "num": [20]}), ("mean", True, {"num": [12.5]}), - ("mean", False, {"num": [12.5]}), + ("mean", False, "Could not convert"), ("mean", lib.no_default, {"num": [12.5]}), ("median", True, {"num": [12.5]}), - ("median", False, {"num": [12.5]}), + ("median", False, "could not convert"), ("median", lib.no_default, {"num": [12.5]}), ("std", True, {"num": [10.606601717798213]}), ("std", False, "could not convert string to float"), @@ -876,15 +876,14 @@ def test_frame_downsample_method(method, numeric_only, expected_data): msg = ( f"default value of numeric_only in DataFrameGroupBy.{method} is deprecated" ) - elif method in ("prod", "mean", "median") and numeric_only is not True: - warn = FutureWarning - msg = f"Dropping invalid columns in DataFrameGroupBy.{method} is deprecated" else: warn = None msg = "" with tm.assert_produces_warning(warn, match=msg): if isinstance(expected_data, str): - klass = TypeError if method == "var" else ValueError + klass = ( + TypeError if method in ("var", "mean", "median", "prod") else ValueError + ) with pytest.raises(klass, match=expected_data): _ = func(**kwargs) else:
- [ ] 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. Prior to calling the cython code, cummin/cummax/cumsum/cumprod raise NotImplementedError on object dtypes. The Series path intercepts this and raises a TypeError instead. I've implemented the same here ~except for DataFrame, we can't readily tell which dtype(s) would fail, so it raises a somewhat vague "at least one dtype" message~.
https://api.github.com/repos/pandas-dev/pandas/pulls/49665
2022-11-12T15:42:34Z
2022-11-16T21:29:33Z
2022-11-16T21:29:33Z
2022-11-16T21:48:17Z
TYP: MergeHow + JoinHow
diff --git a/pandas/_typing.py b/pandas/_typing.py index dad5ffd48caa8..05421f6bd8126 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -343,6 +343,12 @@ def closed(self) -> bool: # dropna AnyAll = Literal["any", "all"] +# merge +MergeHow = Literal["left", "right", "inner", "outer", "cross"] + +# join +JoinHow = Literal["left", "right", "inner", "outer"] + MatplotlibColor = Union[str, Sequence[float]] TimeGrouperOrigin = Union[ "Timestamp", Literal["epoch", "start", "start_day", "end", "end_day"] diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5654ba469d05a..c1024b86b4df2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -71,6 +71,7 @@ IndexKeyFunc, IndexLabel, Level, + MergeHow, NaPosition, PythonFuncType, QuantileInterpolation, @@ -9528,7 +9529,7 @@ def join( self, other: DataFrame | Series | list[DataFrame | Series], on: IndexLabel | None = None, - how: str = "left", + how: MergeHow = "left", lsuffix: str = "", rsuffix: str = "", sort: bool = False, @@ -9701,7 +9702,7 @@ def _join_compat( self, other: DataFrame | Series | Iterable[DataFrame | Series], on: IndexLabel | None = None, - how: str = "left", + how: MergeHow = "left", lsuffix: str = "", rsuffix: str = "", sort: bool = False, @@ -9787,7 +9788,7 @@ def _join_compat( def merge( self, right: DataFrame | Series, - how: str = "inner", + how: MergeHow = "inner", on: IndexLabel | None = None, left_on: IndexLabel | None = None, right_on: IndexLabel | None = None, diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 068ff7a0bf1c9..b4c3af17ecce0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -53,6 +53,7 @@ F, IgnoreRaise, IndexLabel, + JoinHow, Level, Shape, npt, @@ -218,7 +219,7 @@ def join( self, other: Index, *, - how: str_t = "left", + how: JoinHow = "left", level=None, return_indexers: bool = False, sort: bool = False, @@ -4325,7 +4326,7 @@ def join( self, other: Index, *, - how: str_t = ..., + how: JoinHow = ..., level: Level = ..., return_indexers: Literal[True], sort: bool = ..., @@ -4337,7 +4338,7 @@ def join( self, other: Index, *, - how: str_t = ..., + how: JoinHow = ..., level: Level = ..., return_indexers: Literal[False] = ..., sort: bool = ..., @@ -4349,7 +4350,7 @@ def join( self, other: Index, *, - how: str_t = ..., + how: JoinHow = ..., level: Level = ..., return_indexers: bool = ..., sort: bool = ..., @@ -4362,7 +4363,7 @@ def join( self, other: Index, *, - how: str_t = "left", + how: JoinHow = "left", level: Level = None, return_indexers: bool = False, sort: bool = False, @@ -4437,7 +4438,8 @@ def join( return join_index, None, rindexer if self._join_precedence < other._join_precedence: - how = {"right": "left", "left": "right"}.get(how, how) + flip: dict[JoinHow, JoinHow] = {"right": "left", "left": "right"} + how = flip.get(how, how) join_index, lidx, ridx = other.join( self, how=how, level=level, return_indexers=True ) @@ -4483,7 +4485,7 @@ def join( @final def _join_via_get_indexer( - self, other: Index, how: str_t, sort: bool + self, other: Index, how: JoinHow, sort: bool ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: # Fallback if we do not have any fastpaths available based on # uniqueness/monotonicity @@ -4517,7 +4519,7 @@ def _join_via_get_indexer( return join_index, lindexer, rindexer @final - def _join_multi(self, other: Index, how: str_t): + def _join_multi(self, other: Index, how: JoinHow): from pandas.core.indexes.multi import MultiIndex from pandas.core.reshape.merge import restore_dropped_levels_multijoin @@ -4589,7 +4591,8 @@ def _join_multi(self, other: Index, how: str_t): self, other = other, self flip_order = True # flip if join method is right or left - how = {"right": "left", "left": "right"}.get(how, how) + flip: dict[JoinHow, JoinHow] = {"right": "left", "left": "right"} + how = flip.get(how, how) level = other.names.index(jl) result = self._join_level(other, level, how=how) @@ -4600,7 +4603,7 @@ def _join_multi(self, other: Index, how: str_t): @final def _join_non_unique( - self, other: Index, how: str_t = "left" + self, other: Index, how: JoinHow = "left" ) -> tuple[Index, npt.NDArray[np.intp], npt.NDArray[np.intp]]: from pandas.core.reshape.merge import get_join_indexers @@ -4632,7 +4635,7 @@ def _join_non_unique( @final def _join_level( - self, other: Index, level, how: str_t = "left", keep_order: bool = True + self, other: Index, level, how: JoinHow = "left", keep_order: bool = True ) -> tuple[MultiIndex, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: """ The join method *only* affects the level of the resulting @@ -4683,7 +4686,8 @@ def _get_leaf_sorter(labels: list[np.ndarray]) -> npt.NDArray[np.intp]: flip_order = not isinstance(self, MultiIndex) if flip_order: left, right = right, left - how = {"right": "left", "left": "right"}.get(how, how) + flip: dict[JoinHow, JoinHow] = {"right": "left", "left": "right"} + how = flip.get(how, how) assert isinstance(left, MultiIndex) @@ -4780,7 +4784,7 @@ def _get_leaf_sorter(labels: list[np.ndarray]) -> npt.NDArray[np.intp]: @final def _join_monotonic( - self, other: Index, how: str_t = "left" + self, other: Index, how: JoinHow = "left" ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: # We only get here with matching dtypes and both monotonic increasing assert other.dtype == self.dtype diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 74a1051825820..6299978e2dcfe 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -30,6 +30,9 @@ AxisInt, DtypeObj, IndexLabel, + JoinHow, + Literal, + MergeHow, Shape, Suffixes, npt, @@ -98,7 +101,7 @@ def merge( left: DataFrame | Series, right: DataFrame | Series, - how: str = "inner", + how: MergeHow = "inner", on: IndexLabel | None = None, left_on: IndexLabel | None = None, right_on: IndexLabel | None = None, @@ -197,7 +200,7 @@ def merge_ordered( right_by=None, fill_method: str | None = None, suffixes: Suffixes = ("_x", "_y"), - how: str = "outer", + how: JoinHow = "outer", ) -> DataFrame: """ Perform a merge for ordered data with optional filling/interpolation. @@ -612,7 +615,7 @@ class _MergeOperation: """ _merge_type = "merge" - how: str + how: MergeHow | Literal["asof"] on: IndexLabel | None # left_on/right_on may be None when passed, but in validate_specification # get replaced with non-None. @@ -635,7 +638,7 @@ def __init__( self, left: DataFrame | Series, right: DataFrame | Series, - how: str = "inner", + how: MergeHow | Literal["asof"] = "inner", on: IndexLabel | None = None, left_on: IndexLabel | None = None, right_on: IndexLabel | None = None, @@ -1010,7 +1013,8 @@ def _get_join_indexers(self) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp] def _get_join_info( self, ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: - + # make mypy happy + assert self.how != "cross" left_ax = self.left.axes[self.axis] right_ax = self.right.axes[self.axis] @@ -1072,7 +1076,7 @@ def _create_join_index( index: Index, other_index: Index, indexer: npt.NDArray[np.intp], - how: str = "left", + how: JoinHow = "left", ) -> Index: """ Create a join index by rearranging one index to match another @@ -1406,7 +1410,7 @@ def _maybe_coerce_merge_keys(self) -> None: def _create_cross_configuration( self, left: DataFrame, right: DataFrame - ) -> tuple[DataFrame, DataFrame, str, str]: + ) -> tuple[DataFrame, DataFrame, JoinHow, str]: """ Creates the configuration to dispatch the cross operation to inner join, e.g. adding a join column and resetting parameters. Join column is added @@ -1424,7 +1428,7 @@ def _create_cross_configuration( to join over. """ cross_col = f"_cross_{uuid.uuid4()}" - how = "inner" + how: JoinHow = "inner" return ( left.assign(**{cross_col: 1}), right.assign(**{cross_col: 1}), @@ -1584,7 +1588,11 @@ def _validate(self, validate: str) -> None: def get_join_indexers( - left_keys, right_keys, sort: bool = False, how: str = "inner", **kwargs + left_keys, + right_keys, + sort: bool = False, + how: MergeHow | Literal["asof"] = "inner", + **kwargs, ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: """ @@ -1757,7 +1765,7 @@ def __init__( axis: AxisInt = 1, suffixes: Suffixes = ("_x", "_y"), fill_method: str | None = None, - how: str = "outer", + how: JoinHow | Literal["asof"] = "outer", ) -> None: self.fill_method = fill_method @@ -1847,7 +1855,7 @@ def __init__( suffixes: Suffixes = ("_x", "_y"), copy: bool = True, fill_method: str | None = None, - how: str = "asof", + how: Literal["asof"] = "asof", tolerance=None, allow_exact_matches: bool = True, direction: str = "backward", @@ -2256,7 +2264,10 @@ def _left_join_on_index( def _factorize_keys( - lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner" + lk: ArrayLike, + rk: ArrayLike, + sort: bool = True, + how: MergeHow | Literal["asof"] = "inner", ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp], int]: """ Encode left and right keys as enumerated types.
- [x] closes #48503 - [ ] [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/49664
2022-11-12T13:51:40Z
2022-12-05T09:59:59Z
2022-12-05T09:59:59Z
2022-12-05T10:00:47Z
STYLE: fix pylint redefined-outer-name warnings (#49656)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index b36eeab70726e..1ba82fc2f063a 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -112,13 +112,13 @@ ) from pandas.core import ( + algorithms, nanops, ops, ) from pandas.core.algorithms import ( checked_add_with_arr, isin, - mode, unique1d, ) from pandas.core.arraylike import OpsMixin @@ -1690,7 +1690,7 @@ def _mode(self, dropna: bool = True): if dropna: mask = self.isna() - i8modes = mode(self.view("i8"), mask=mask) + i8modes = algorithms.mode(self.view("i8"), mask=mask) npmodes = i8modes.view(self._ndarray.dtype) npmodes = cast(np.ndarray, npmodes) return self._from_backing_data(npmodes) diff --git a/pandas/core/base.py b/pandas/core/base.py index 46803e1f28975..3d06c1830cc53 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -61,11 +61,6 @@ ops, ) from pandas.core.accessor import DirNamesMixin -from pandas.core.algorithms import ( - duplicated, - unique1d, - value_counts, -) from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ExtensionArray from pandas.core.construction import ( @@ -991,7 +986,7 @@ def value_counts( NaN 1 dtype: int64 """ - return value_counts( + return algorithms.value_counts( self, sort=sort, ascending=ascending, @@ -1006,7 +1001,7 @@ def unique(self): # i.e. ExtensionArray result = values.unique() else: - result = unique1d(values) + result = algorithms.unique1d(values) return result @final @@ -1294,7 +1289,7 @@ def drop_duplicates(self, *, keep: DropKeep = "first"): @final def _duplicated(self, keep: DropKeep = "first") -> npt.NDArray[np.bool_]: - return duplicated(self._values, keep=keep) + return algorithms.duplicated(self._values, keep=keep) def _arith_method(self, other, op): res_name = ops.get_op_result_name(self, other) diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index ea7b8b654efa1..93928d8bf6b83 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -650,7 +650,7 @@ def maybe_expression(s) -> bool: """loose checking if s is a pytables-acceptable expression""" if not isinstance(s, str): return False - ops = PyTablesExprVisitor.binary_ops + PyTablesExprVisitor.unary_ops + ("=",) + operations = PyTablesExprVisitor.binary_ops + PyTablesExprVisitor.unary_ops + ("=",) # make sure we have an op at least - return any(op in s for op in ops) + return any(op in s for op in operations)
Fixed warnings for the following files :- - **pandas/core/arrays/datetimelike.py** - **pandas/core/base.py** - **pandas/core/computation/pytables.py** - [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. - [ ] 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/49662
2022-11-12T12:57:09Z
2022-11-13T11:12:18Z
2022-11-13T11:12:18Z
2022-11-13T11:12:18Z
API: Float64Index.astype(datetimelike)
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 561e39df60b64..b8b9780cd5deb 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -329,6 +329,7 @@ Other API changes - Default value of ``dtype`` in :func:`get_dummies` is changed to ``bool`` from ``uint8`` (:issue:`45848`) - :meth:`DataFrame.astype`, :meth:`Series.astype`, and :meth:`DatetimeIndex.astype` casting datetime64 data to any of "datetime64[s]", "datetime64[ms]", "datetime64[us]" will return an object with the given resolution instead of coercing back to "datetime64[ns]" (:issue:`48928`) - :meth:`DataFrame.astype`, :meth:`Series.astype`, and :meth:`DatetimeIndex.astype` casting timedelta64 data to any of "timedelta64[s]", "timedelta64[ms]", "timedelta64[us]" will return an object with the given resolution instead of coercing to "float64" dtype (:issue:`48963`) +- :meth:`Index.astype` now allows casting from ``float64`` dtype to datetime-like dtypes, matching :class:`Series` behavior (:issue:`49660`) - Passing data with dtype of "timedelta64[s]", "timedelta64[ms]", or "timedelta64[us]" to :class:`TimedeltaIndex`, :class:`Series`, or :class:`DataFrame` constructors will now retain that dtype instead of casting to "timedelta64[ns]"; timedelta64 data with lower resolution will be cast to the lowest supported resolution "timedelta64[s]" (:issue:`49014`) - Passing ``dtype`` of "timedelta64[s]", "timedelta64[ms]", or "timedelta64[us]" to :class:`TimedeltaIndex`, :class:`Series`, or :class:`DataFrame` constructors will now retain that dtype instead of casting to "timedelta64[ns]"; passing a dtype with lower resolution for :class:`Series` or :class:`DataFrame` will be cast to the lowest supported resolution "timedelta64[s]" (:issue:`49014`) - Passing a ``np.datetime64`` object with non-nanosecond resolution to :class:`Timestamp` will retain the input resolution if it is "s", "ms", or "ns"; otherwise it will be cast to the closest supported resolution (:issue:`49008`) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 77e2fdac26da9..5ebd882cd3a13 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -919,6 +919,15 @@ def astype(self, dtype, copy: bool = True): if dtype == self.dtype: return self.copy() if copy else self + if is_float_dtype(self.dtype.subtype) and needs_i8_conversion( + dtype.subtype + ): + # This is allowed on the Index.astype but we disallow it here + msg = ( + f"Cannot convert {self.dtype} to {dtype}; subtypes are incompatible" + ) + raise TypeError(msg) + # need to cast to different subtype try: # We need to use Index rules for astype to prevent casting diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 9498fad8c211e..d48e6ab6ee72f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1016,14 +1016,6 @@ def astype(self, dtype, copy: bool = True): with rewrite_exception(type(values).__name__, type(self).__name__): new_values = values.astype(dtype, copy=copy) - elif is_float_dtype(self.dtype) and needs_i8_conversion(dtype): - # NB: this must come before the ExtensionDtype check below - # TODO: this differs from Series behavior; can/should we align them? - raise TypeError( - f"Cannot convert dtype={self.dtype} to dtype {dtype}; integer " - "values are required for conversion" - ) - elif isinstance(dtype, ExtensionDtype): cls = dtype.construct_array_type() # Note: for RangeIndex and CategoricalDtype self vs self._values diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py index 88e3dca62d9e0..0e316cf419cb0 100644 --- a/pandas/tests/arithmetic/test_interval.py +++ b/pandas/tests/arithmetic/test_interval.py @@ -133,18 +133,8 @@ def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed): expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected) - def test_compare_scalar_na( - self, op, interval_array, nulls_fixture, box_with_array, request - ): + def test_compare_scalar_na(self, op, interval_array, nulls_fixture, box_with_array): box = box_with_array - - if box is pd.DataFrame: - if interval_array.dtype.subtype.kind not in "iuf": - mark = pytest.mark.xfail( - reason="raises on DataFrame.transpose (would be fixed by EA2D)" - ) - request.node.add_marker(mark) - obj = tm.box_expected(interval_array, box) result = op(obj, nulls_fixture) diff --git a/pandas/tests/indexes/numeric/test_astype.py b/pandas/tests/indexes/numeric/test_astype.py index fd4421f72663c..044ba71be9b62 100644 --- a/pandas/tests/indexes/numeric/test_astype.py +++ b/pandas/tests/indexes/numeric/test_astype.py @@ -1,11 +1,11 @@ -import re - import numpy as np import pytest -from pandas.core.dtypes.common import pandas_dtype - -from pandas import Index +from pandas import ( + Index, + to_datetime, + to_timedelta, +) import pandas._testing as tm @@ -66,15 +66,22 @@ def test_astype_float64_to_float_dtype(self, dtype): tm.assert_index_equal(result, expected, exact=True) @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) - def test_cannot_cast_to_datetimelike(self, dtype): + def test_astype_float_to_datetimelike(self, dtype): + # GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised, + # inconsistent with Series.astype idx = Index([0, 1.1, 2], dtype=np.float64) - msg = ( - f"Cannot convert dtype=float64 to dtype {pandas_dtype(dtype)}; " - f"integer values are required for conversion" - ) - with pytest.raises(TypeError, match=re.escape(msg)): - idx.astype(dtype) + result = idx.astype(dtype) + if dtype[0] == "M": + expected = to_datetime(idx.values) + else: + expected = to_timedelta(idx.values) + tm.assert_index_equal(result, expected) + + # check that we match Series behavior + result = idx.to_series().set_axis(range(3)).astype(dtype) + expected = expected.to_series().set_axis(range(3)) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"]) @pytest.mark.parametrize("non_finite", [np.inf, np.nan])
- [ ] 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/49660
2022-11-12T00:28:26Z
2022-11-17T04:36:41Z
2022-11-17T04:36:41Z
2022-11-17T15:52:48Z
REF: remove no-longer-needed ignore_failures
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index efad2edddf360..b6b731da98d8d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10460,7 +10460,7 @@ def _get_data() -> DataFrame: # After possibly _get_data and transposing, we are now in the # simple case where we can use BlockManager.reduce - res, _ = df._mgr.reduce(blk_func, ignore_failures=False) + res = df._mgr.reduce(blk_func) out = df._constructor(res).iloc[0] if out_dtype is not None: out = out.astype(out_dtype) diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index d325e5e9b92cc..b061560c5f7dc 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -196,7 +196,6 @@ def apply( self: T, f, align_keys: list[str] | None = None, - ignore_failures: bool = False, **kwargs, ) -> T: """ @@ -207,7 +206,6 @@ def apply( f : str or callable Name of the Array method to apply. align_keys: List[str] or None, default None - ignore_failures: bool, default False **kwargs Keywords to pass to `f` @@ -215,11 +213,10 @@ def apply( ------- ArrayManager """ - assert "filter" not in kwargs + assert "filter" not in kwargs and "ignore_failures" not in kwargs align_keys = align_keys or [] result_arrays: list[np.ndarray] = [] - result_indices: list[int] = [] # fillna: Series/DataFrame is responsible for making sure value is aligned aligned_args = {k: kwargs[k] for k in align_keys} @@ -243,27 +240,17 @@ def apply( # otherwise we have an array-like kwargs[k] = obj[i] - try: - if callable(f): - applied = f(arr, **kwargs) - else: - applied = getattr(arr, f)(**kwargs) - except (TypeError, NotImplementedError): - if not ignore_failures: - raise - continue + if callable(f): + applied = f(arr, **kwargs) + else: + applied = getattr(arr, f)(**kwargs) + # if not isinstance(applied, ExtensionArray): # # TODO not all EA operations return new EAs (eg astype) # applied = array(applied) result_arrays.append(applied) - result_indices.append(i) - new_axes: list[Index] - if ignore_failures: - # TODO copy? - new_axes = [self._axes[0], self._axes[1][result_indices]] - else: - new_axes = self._axes + new_axes = self._axes # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]"; # expected "List[Union[ndarray, ExtensionArray]]" @@ -985,58 +972,41 @@ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: # expected "List[Union[ndarray, ExtensionArray]]" return type(self)(result_arrays, [index, columns]) # type: ignore[arg-type] - def reduce( - self: T, func: Callable, ignore_failures: bool = False - ) -> tuple[T, np.ndarray]: + def reduce(self: T, func: Callable) -> T: """ Apply reduction function column-wise, returning a single-row ArrayManager. Parameters ---------- func : reduction function - ignore_failures : bool, default False - Whether to drop columns where func raises TypeError. Returns ------- ArrayManager - np.ndarray - Indexer of column indices that are retained. """ result_arrays: list[np.ndarray] = [] - result_indices: list[int] = [] for i, arr in enumerate(self.arrays): - try: - res = func(arr, axis=0) - except TypeError: - if not ignore_failures: - raise + res = func(arr, axis=0) + + # TODO NaT doesn't preserve dtype, so we need to ensure to create + # a timedelta result array if original was timedelta + # what if datetime results in timedelta? (eg std) + if res is NaT and is_timedelta64_ns_dtype(arr.dtype): + result_arrays.append(np.array(["NaT"], dtype="timedelta64[ns]")) else: - # TODO NaT doesn't preserve dtype, so we need to ensure to create - # a timedelta result array if original was timedelta - # what if datetime results in timedelta? (eg std) - if res is NaT and is_timedelta64_ns_dtype(arr.dtype): - result_arrays.append(np.array(["NaT"], dtype="timedelta64[ns]")) - else: - # error: Argument 1 to "append" of "list" has incompatible type - # "ExtensionArray"; expected "ndarray" - result_arrays.append( - sanitize_array([res], None) # type: ignore[arg-type] - ) - result_indices.append(i) + # error: Argument 1 to "append" of "list" has incompatible type + # "ExtensionArray"; expected "ndarray" + result_arrays.append( + sanitize_array([res], None) # type: ignore[arg-type] + ) index = Index._simple_new(np.array([None], dtype=object)) # placeholder - if ignore_failures: - indexer = np.array(result_indices) - columns = self.items[result_indices] - else: - indexer = np.arange(self.shape[0]) - columns = self.items + columns = self.items # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]"; # expected "List[Union[ndarray, ExtensionArray]]" new_mgr = type(self)(result_arrays, [index, columns]) # type: ignore[arg-type] - return new_mgr, indexer + return new_mgr def operate_blockwise(self, other: ArrayManager, array_op) -> ArrayManager: """ diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py index 5b6dcba2371d9..37aa60f1ee52d 100644 --- a/pandas/core/internals/base.py +++ b/pandas/core/internals/base.py @@ -134,7 +134,6 @@ def apply( self: T, f, align_keys: list[str] | None = None, - ignore_failures: bool = False, **kwargs, ) -> T: raise AbstractMethodError(self) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index cab8901ff3596..1fb050f32c750 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -326,17 +326,12 @@ def apply(self, func, **kwargs) -> list[Block]: return self._split_op_result(result) - def reduce(self, func, ignore_failures: bool = False) -> list[Block]: + def reduce(self, func) -> list[Block]: # We will apply the function and reshape the result into a single-row # Block with the same mgr_locs; squeezing will be done at a higher level assert self.ndim == 2 - try: - result = func(self.values) - except (TypeError, NotImplementedError): - if ignore_failures: - return [] - raise + result = func(self.values) if self.values.ndim == 1: # TODO(EA2D): special case not needed with 2D EAs @@ -1957,23 +1952,17 @@ class ObjectBlock(NumpyBlock): __slots__ = () is_object = True - @maybe_split - def reduce(self, func, ignore_failures: bool = False) -> list[Block]: + def reduce(self, func) -> list[Block]: """ For object-dtype, we operate column-wise. """ assert self.ndim == 2 - try: - res = func(self.values) - except TypeError: - if not ignore_failures: - raise - return [] + res = func(self.values) assert isinstance(res, np.ndarray) assert res.ndim == 1 - res = res.reshape(1, -1) + res = res.reshape(-1, 1) return [self.make_block_same_class(res)] @maybe_split diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 91bb3a128ae27..3eca3756e1678 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -303,7 +303,6 @@ def apply( self: T, f, align_keys: list[str] | None = None, - ignore_failures: bool = False, **kwargs, ) -> T: """ @@ -314,7 +313,6 @@ def apply( f : str or callable Name of the Block method to apply. align_keys: List[str] or None, default None - ignore_failures: bool, default False **kwargs Keywords to pass to `f` @@ -322,7 +320,7 @@ def apply( ------- BlockManager """ - assert "filter" not in kwargs + assert "filter" not in kwargs and "ignore_failures" not in kwargs align_keys = align_keys or [] result_blocks: list[Block] = [] @@ -346,20 +344,12 @@ def apply( # otherwise we have an ndarray kwargs[k] = obj[b.mgr_locs.indexer] - try: - if callable(f): - applied = b.apply(f, **kwargs) - else: - applied = getattr(b, f)(**kwargs) - except (TypeError, NotImplementedError): - if not ignore_failures: - raise - continue + if callable(f): + applied = b.apply(f, **kwargs) + else: + applied = getattr(b, f)(**kwargs) result_blocks = extend_blocks(applied, result_blocks) - if ignore_failures: - return self._combine(result_blocks) - out = type(self).from_blocks(result_blocks, self.axes) return out @@ -1527,44 +1517,29 @@ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: return type(self).from_blocks(result_blocks, [self.axes[0], index]) - def reduce( - self: T, func: Callable, ignore_failures: bool = False - ) -> tuple[T, np.ndarray]: + def reduce(self: T, func: Callable) -> T: """ Apply reduction function blockwise, returning a single-row BlockManager. Parameters ---------- func : reduction function - ignore_failures : bool, default False - Whether to drop blocks where func raises TypeError. Returns ------- BlockManager - np.ndarray - Indexer of mgr_locs that are retained. """ # If 2D, we assume that we're operating column-wise assert self.ndim == 2 res_blocks: list[Block] = [] for blk in self.blocks: - nbs = blk.reduce(func, ignore_failures) + nbs = blk.reduce(func) res_blocks.extend(nbs) index = Index([None]) # placeholder - if ignore_failures: - if res_blocks: - indexer = np.concatenate([blk.mgr_locs.as_array for blk in res_blocks]) - new_mgr = self._combine(res_blocks, copy=False, index=index) - else: - indexer = [] - new_mgr = type(self).from_blocks([], [self.items[:0], index]) - else: - indexer = np.arange(self.shape[0]) - new_mgr = type(self).from_blocks(res_blocks, [self.items, index]) - return new_mgr, indexer + new_mgr = type(self).from_blocks(res_blocks, [self.items, index]) + return new_mgr def operate_blockwise(self, other: BlockManager, array_op) -> BlockManager: """
- [ ] 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/49659
2022-11-12T00:17:24Z
2022-11-16T10:15:29Z
2022-11-16T10:15:29Z
2022-11-16T15:47:40Z
API: Series[bytes].astype(str) behavior
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 43a34c8e18b2d..656f6f13b4e82 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -773,6 +773,7 @@ Other API changes - :func:`read_stata` with parameter ``index_col`` set to ``None`` (the default) will now set the index on the returned :class:`DataFrame` to a :class:`RangeIndex` instead of a :class:`Int64Index` (:issue:`49745`) - Changed behavior of :class:`Index`, :class:`Series`, and :class:`DataFrame` arithmetic methods when working with object-dtypes, the results no longer do type inference on the result of the array operations, use ``result.infer_objects(copy=False)`` to do type inference on the result (:issue:`49999`, :issue:`49714`) - Changed behavior of :class:`Index` constructor with an object-dtype ``numpy.ndarray`` containing all-``bool`` values or all-complex values, this will now retain object dtype, consistent with the :class:`Series` behavior (:issue:`49594`) +- Changed behavior of :meth:`Series.astype` from object-dtype containing ``bytes`` objects to string dtypes; this now does ``val.decode()"`` on bytes objects instead of ``str(val)``, matching :meth:`Index.astype` behavior (:issue:`45326`) - Added ``"None"`` to default ``na_values`` in :func:`read_csv` (:issue:`50286`) - Changed behavior of :class:`Series` and :class:`DataFrame` constructors when given an integer dtype and floating-point data that is not round numbers, this now raises ``ValueError`` instead of silently retaining the float dtype; do ``Series(data)`` or ``DataFrame(data)`` to get the old behavior, and ``Series(data).astype(dtype)`` or ``DataFrame(data).astype(dtype)`` to get the specified dtype (:issue:`49599`) - Changed behavior of :meth:`DataFrame.shift` with ``axis=1``, an integer ``fill_value``, and homogeneous datetime-like dtype, this now fills new columns with integer dtypes instead of casting to datetimelike (:issue:`49842`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index d79f7068effc3..04b1266e4df17 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -777,7 +777,10 @@ cpdef ndarray[object] ensure_string_array( already_copied = True if not checknull(val): - if not util.is_float_object(val): + if isinstance(val, bytes): + # GH#49658 discussion of desired behavior here + result[i] = val.decode() + elif not util.is_float_object(val): # f"{val}" is faster than str(val) result[i] = f"{val}" else: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 363bfe76d40fb..75c0168f66126 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -995,12 +995,8 @@ def astype(self, dtype, copy: bool = True): new_values = cls._from_sequence(self, dtype=dtype, copy=copy) else: - if dtype == str: - # GH#38607 see test_astype_str_from_bytes - new_values = values.astype(dtype, copy=copy) - else: - # GH#13149 specifically use astype_array instead of astype - new_values = astype_array(values, dtype=dtype, copy=copy) + # GH#13149 specifically use astype_array instead of astype + new_values = astype_array(values, dtype=dtype, copy=copy) # pass copy=False because any copying will be done in the astype above return Index(new_values, name=self.name, dtype=new_values.dtype, copy=False) diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index 6e1795b150b27..89ea1670d9e7b 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -55,9 +55,12 @@ def test_astype_str(self, data): ], ) def test_astype_string(self, data, nullable_string_dtype): - # GH-33465 + # GH-33465, GH#45326 as of 2.0 we decode bytes instead of calling str(obj) result = pd.Series(data[:5]).astype(nullable_string_dtype) - expected = pd.Series([str(x) for x in data[:5]], dtype=nullable_string_dtype) + expected = pd.Series( + [str(x) if not isinstance(x, bytes) else x.decode() for x in data[:5]], + dtype=nullable_string_dtype, + ) self.assert_series_equal(result, expected) def test_to_numpy(self, data): diff --git a/pandas/tests/indexes/object/test_astype.py b/pandas/tests/indexes/object/test_astype.py index 33e45a707df63..273b39b5e319d 100644 --- a/pandas/tests/indexes/object/test_astype.py +++ b/pandas/tests/indexes/object/test_astype.py @@ -3,17 +3,26 @@ from pandas import ( Index, NaT, + Series, ) import pandas._testing as tm def test_astype_str_from_bytes(): # https://github.com/pandas-dev/pandas/issues/38607 + # GH#49658 pre-2.0 Index called .values.astype(str) here, which effectively + # did a .decode() on the bytes object. In 2.0 we go through + # ensure_string_array which does f"{val}" idx = Index(["あ", b"a"], dtype="object") result = idx.astype(str) expected = Index(["あ", "a"], dtype="object") tm.assert_index_equal(result, expected) + # while we're here, check that Series.astype behaves the same + result = Series(idx).astype(str) + expected = Series(expected) + tm.assert_series_equal(result, expected) + def test_astype_invalid_nas_to_tdt64_raises(): # GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index ce17614e1f8b7..aae51ebc5a017 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -389,7 +389,13 @@ def test_astype_unicode(self): former_encoding = None if sys.getdefaultencoding() == "utf-8": - test_series.append(Series(["野菜食べないとやばい".encode()])) + # GH#45326 as of 2.0 Series.astype matches Index.astype by handling + # bytes with obj.decode() instead of str(obj) + item = "野菜食べないとやばい" + ser = Series([item.encode()]) + result = ser.astype("unicode") + expected = Series([item]) + tm.assert_series_equal(result, expected) for ser in test_series: res = ser.astype("unicode")
- [x] closes #45326 (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. I'm not married to this particular API design, just easier to demonstrate the relevant issues in a PR rather than in #45326. <s>Note: this adds the possibility of raising in some cases that currently do not raise e.g. `pd.Series([b'\xa7']).astype(str)`</s>
https://api.github.com/repos/pandas-dev/pandas/pulls/49658
2022-11-11T22:43:02Z
2023-02-15T18:08:22Z
2023-02-15T18:08:22Z
2023-02-15T18:12:49Z
REF: share astype exception messages
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index d0a932ec378b9..bd134dc11201e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -641,10 +641,12 @@ def astype(self, dtype, copy: bool = True): elif self.tz is None and isinstance(dtype, DatetimeTZDtype): # pre-2.0 this did self.tz_localize(dtype.tz), which did not match - # the Series behavior + # the Series behavior which did + # values.tz_localize("UTC").tz_convert(dtype.tz) raise TypeError( "Cannot use .astype to convert from timezone-naive dtype to " - "timezone-aware dtype. Use obj.tz_localize instead." + "timezone-aware dtype. Use obj.tz_localize instead or " + "series.dt.tz_localize instead" ) elif self.tz is not None and is_datetime64_dtype(dtype): diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 4dd49ec6b64bb..858882fd28f0d 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -23,7 +23,6 @@ from pandas.core.dtypes.common import ( is_datetime64_dtype, - is_datetime64tz_dtype, is_dtype_equal, is_integer_dtype, is_object_dtype, @@ -211,16 +210,6 @@ def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> Arra msg = rf"cannot astype a datetimelike from [{values.dtype}] to [{dtype}]" raise TypeError(msg) - if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype): - # Series.astype behavior pre-2.0 did - # values.tz_localize("UTC").tz_convert(dtype.tz) - # which did not match the DTA/DTI behavior. - # We special-case here to give a Series-specific exception message. - raise TypeError( - "Cannot use .astype to convert from timezone-naive dtype to " - "timezone-aware dtype. Use ser.dt.tz_localize instead." - ) - if is_dtype_equal(values.dtype, dtype): if copy: return values.copy() diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 27672c82fdf15..88ef5a8daccbc 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1020,7 +1020,7 @@ def astype(self, dtype, copy: bool = True): # NB: this must come before the ExtensionDtype check below # TODO: this differs from Series behavior; can/should we align them? raise TypeError( - f"Cannot convert Float64Index to dtype {dtype}; integer " + f"Cannot convert dtype={self.dtype} to dtype {dtype}; integer " "values are required for conversion" ) diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index a5d762a280566..e3fabf2edc288 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -36,6 +36,7 @@ from pandas._typing import ( ArrayLike, DtypeArg, + DtypeObj, Scalar, ) from pandas.errors import ( @@ -61,7 +62,10 @@ is_string_dtype, pandas_dtype, ) -from pandas.core.dtypes.dtypes import CategoricalDtype +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + ExtensionDtype, +) from pandas.core.dtypes.missing import isna from pandas import StringDtype @@ -69,6 +73,7 @@ from pandas.core.arrays import ( BooleanArray, Categorical, + ExtensionArray, FloatingArray, IntegerArray, ) @@ -599,14 +604,8 @@ def _convert_to_ndarrays( # type specified in dtype param or cast_type is an EA if cast_type and (not is_dtype_equal(cvals, cast_type) or is_ea): if not is_ea and na_count > 0: - try: - if is_bool_dtype(cast_type): - raise ValueError( - f"Bool column has NA values in column {c}" - ) - except (AttributeError, TypeError): - # invalid input to is_bool_dtype - pass + if is_bool_dtype(cast_type): + raise ValueError(f"Bool column has NA values in column {c}") cast_type = pandas_dtype(cast_type) cvals = self._cast_types(cvals, cast_type, c) @@ -686,7 +685,7 @@ def _set(x) -> int: def _infer_types( self, values, na_values, no_dtype_specified, try_num_bool: bool = True - ): + ) -> tuple[ArrayLike, int]: """ Infer types of values, possibly casting @@ -700,7 +699,7 @@ def _infer_types( Returns ------- - converted : ndarray + converted : ndarray or ExtensionArray na_count : int """ na_count = 0 @@ -777,21 +776,21 @@ def _infer_types( return result, na_count - def _cast_types(self, values, cast_type, column): + def _cast_types(self, values: ArrayLike, cast_type: DtypeObj, column) -> ArrayLike: """ Cast values to specified type Parameters ---------- - values : ndarray - cast_type : string or np.dtype + values : ndarray or ExtensionArray + cast_type : np.dtype or ExtensionDtype dtype to cast values to column : string column name - used only for error reporting Returns ------- - converted : ndarray + converted : ndarray or ExtensionArray """ if is_categorical_dtype(cast_type): known_cats = ( @@ -799,12 +798,14 @@ def _cast_types(self, values, cast_type, column): and cast_type.categories is not None ) - if not is_object_dtype(values) and not known_cats: + if not is_object_dtype(values.dtype) and not known_cats: # TODO: this is for consistency with # c-parser which parses all categories # as strings - values = astype_nansafe(values, np.dtype(str)) + values = lib.ensure_string_array( + values, skipna=False, convert_na_value=False + ) cats = Index(values).unique().dropna() values = Categorical._from_inferred_categories( @@ -812,13 +813,13 @@ def _cast_types(self, values, cast_type, column): ) # use the EA's implementation of casting - elif is_extension_array_dtype(cast_type): - # ensure cast_type is an actual dtype and not a string - cast_type = pandas_dtype(cast_type) + elif isinstance(cast_type, ExtensionDtype): array_type = cast_type.construct_array_type() try: if is_bool_dtype(cast_type): - return array_type._from_sequence_of_strings( + # error: Unexpected keyword argument "true_values" for + # "_from_sequence_of_strings" of "ExtensionArray" + return array_type._from_sequence_of_strings( # type: ignore[call-arg] # noqa:E501 values, dtype=cast_type, true_values=self.true_values, @@ -832,6 +833,8 @@ def _cast_types(self, values, cast_type, column): "_from_sequence_of_strings in order to be used in parser methods" ) from err + elif isinstance(values, ExtensionArray): + values = values.astype(cast_type, copy=False) else: try: values = astype_nansafe(values, cast_type, copy=True, skipna=True) diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 166362a9a8c30..fa38ad0885db5 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -368,7 +368,7 @@ def test_astype_copies(self, dtype, other): if err: if dtype == "datetime64[ns]": - msg = "Use ser.dt.tz_localize instead" + msg = "Use obj.tz_localize instead or series.dt.tz_localize instead" else: msg = "from timezone-aware dtype to timezone-naive dtype" with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/indexes/numeric/test_astype.py b/pandas/tests/indexes/numeric/test_astype.py index ee75f56eac7ce..86a426838cdce 100644 --- a/pandas/tests/indexes/numeric/test_astype.py +++ b/pandas/tests/indexes/numeric/test_astype.py @@ -75,7 +75,7 @@ def test_cannot_cast_to_datetimelike(self, dtype): idx = Float64Index([0, 1.1, 2]) msg = ( - f"Cannot convert Float64Index to dtype {pandas_dtype(dtype)}; " + f"Cannot convert dtype=float64 to dtype {pandas_dtype(dtype)}; " f"integer values are required for conversion" ) with pytest.raises(TypeError, match=re.escape(msg)):
- [ ] 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/49655
2022-11-11T19:30:47Z
2022-11-16T22:04:10Z
2022-11-16T22:04:10Z
2022-11-16T22:51:20Z
Backport PR #49615 on branch 1.5.x (REGR: Better warning in pivot_table when dropping nuisance columns)
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 66a3425d0d398..7ef58c7836c81 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -21,6 +21,7 @@ Substitution, deprecate_nonkeyword_arguments, ) +from pandas.util._exceptions import rewrite_warning from pandas.core.dtypes.cast import maybe_downcast_to_dtype from pandas.core.dtypes.common import ( @@ -163,7 +164,18 @@ def __internal_pivot_table( values = list(values) grouped = data.groupby(keys, observed=observed, sort=sort) - agged = grouped.agg(aggfunc) + msg = ( + "pivot_table dropped a column because it failed to aggregate. This behavior " + "is deprecated and will raise in a future version of pandas. Select only the " + "columns that can be aggregated." + ) + with rewrite_warning( + target_message="The default value of numeric_only", + target_category=FutureWarning, + new_message=msg, + ): + agged = grouped.agg(aggfunc) + if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns): agged = agged.dropna(how="all") diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 77a43954cf699..f8b6f1f5d6cf6 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -146,7 +146,7 @@ def test_pivot_table_nocols(self): df = DataFrame( {"rows": ["a", "b", "c"], "cols": ["x", "y", "z"], "values": [1, 2, 3]} ) - msg = "The default value of numeric_only" + msg = "pivot_table dropped a column because it failed to aggregate" with tm.assert_produces_warning(FutureWarning, match=msg): rs = df.pivot_table(columns="cols", aggfunc=np.sum) xp = df.pivot_table(index="cols", aggfunc=np.sum).T @@ -907,7 +907,7 @@ def test_no_col(self): # to help with a buglet self.data.columns = [k * 2 for k in self.data.columns] - msg = "The default value of numeric_only" + msg = "pivot_table dropped a column because it failed to aggregate" with tm.assert_produces_warning(FutureWarning, match=msg): table = self.data.pivot_table( index=["AA", "BB"], margins=True, aggfunc=np.mean @@ -975,7 +975,7 @@ def test_margin_with_only_columns_defined( } ) - msg = "The default value of numeric_only" + msg = "pivot_table dropped a column because it failed to aggregate" with tm.assert_produces_warning(FutureWarning, match=msg): result = df.pivot_table(columns=columns, margins=True, aggfunc=aggfunc) expected = DataFrame(values, index=Index(["D", "E"]), columns=expected_columns) @@ -2004,7 +2004,7 @@ def test_pivot_string_func_vs_func(self, f, f_numpy): # GH #18713 # for consistency purposes - msg = "The default value of numeric_only" + msg = "pivot_table dropped a column because it failed to aggregate" with tm.assert_produces_warning(FutureWarning, match=msg): result = pivot_table(self.data, index="A", columns="B", aggfunc=f) expected = pivot_table(self.data, index="A", columns="B", aggfunc=f_numpy) diff --git a/pandas/tests/util/test_rewrite_warning.py b/pandas/tests/util/test_rewrite_warning.py new file mode 100644 index 0000000000000..f847a06d8ea8d --- /dev/null +++ b/pandas/tests/util/test_rewrite_warning.py @@ -0,0 +1,39 @@ +import warnings + +import pytest + +from pandas.util._exceptions import rewrite_warning + +import pandas._testing as tm + + +@pytest.mark.parametrize( + "target_category, target_message, hit", + [ + (FutureWarning, "Target message", True), + (FutureWarning, "Target", True), + (FutureWarning, "get mess", True), + (FutureWarning, "Missed message", False), + (DeprecationWarning, "Target message", False), + ], +) +@pytest.mark.parametrize( + "new_category", + [ + None, + DeprecationWarning, + ], +) +def test_rewrite_warning(target_category, target_message, hit, new_category): + new_message = "Rewritten message" + if hit: + expected_category = new_category if new_category else target_category + expected_message = new_message + else: + expected_category = FutureWarning + expected_message = "Target message" + with tm.assert_produces_warning(expected_category, match=expected_message): + with rewrite_warning( + target_message, target_category, new_message, new_category + ): + warnings.warn(message="Target message", category=FutureWarning) diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py index c718451fbf621..f300f2c52f175 100644 --- a/pandas/util/_exceptions.py +++ b/pandas/util/_exceptions.py @@ -3,7 +3,9 @@ import contextlib import inspect import os +import re from typing import Iterator +import warnings @contextlib.contextmanager @@ -47,3 +49,46 @@ def find_stack_level() -> int: else: break return n + + +@contextlib.contextmanager +def rewrite_warning( + target_message: str, + target_category: type[Warning], + new_message: str, + new_category: type[Warning] | None = None, +) -> Iterator[None]: + """ + Rewrite the message of a warning. + + Parameters + ---------- + target_message : str + Warning message to match. + target_category : Warning + Warning type to match. + new_message : str + New warning message to emit. + new_category : Warning or None, default None + New warning type to emit. When None, will be the same as target_category. + """ + if new_category is None: + new_category = target_category + with warnings.catch_warnings(record=True) as record: + yield + if len(record) > 0: + match = re.compile(target_message) + for warning in record: + if warning.category is target_category and re.search( + match, str(warning.message) + ): + category = new_category + message: Warning | str = new_message + else: + category, message = warning.category, warning.message + warnings.warn_explicit( + message=message, + category=category, + filename=warning.filename, + lineno=warning.lineno, + )
Backport PR #49615
https://api.github.com/repos/pandas-dev/pandas/pulls/49653
2022-11-11T19:07:32Z
2022-11-11T22:08:13Z
2022-11-11T22:08:13Z
2023-01-12T12:51:32Z
BUG: groupby with dropna=False drops nulls from categorical groupers
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index ee08a55c42e4a..8bcc863a0df6c 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -751,6 +751,7 @@ Groupby/resample/rolling - Bug in :meth:`.DataFrameGroupBy.apply` and :class:`SeriesGroupBy.apply` with ``as_index=False`` would not attempt the computation without using the grouping keys when using them failed with a ``TypeError`` (:issue:`49256`) - Bug in :meth:`.DataFrameGroupBy.describe` would describe the group keys (:issue:`49256`) - Bug in :meth:`.SeriesGroupBy.describe` with ``as_index=False`` would have the incorrect shape (:issue:`49256`) +- Bug in :class:`.DataFrameGroupBy` and :class:`.SeriesGroupBy` with ``dropna=False`` would drop NA values when the grouper was categorical (:issue:`36327`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 65691e6f46eb5..c94b1068e5e65 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -406,6 +406,29 @@ def unique(values): return unique_with_mask(values) +def nunique_ints(values: ArrayLike) -> int: + """ + Return the number of unique values for integer array-likes. + + Significantly faster than pandas.unique for long enough sequences. + No checks are done to ensure input is integral. + + Parameters + ---------- + values : 1d array-like + + Returns + ------- + int : The number of unique values in ``values`` + """ + if len(values) == 0: + return 0 + values = _ensure_data(values) + # bincount requires intp + result = (np.bincount(values.ravel().astype("intp")) != 0).sum() + return result + + def unique_with_mask(values, mask: npt.NDArray[np.bool_] | None = None): """See algorithms.unique for docs. Takes a mask for masked arrays.""" values = _ensure_arraylike(values) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c73a2d40a33e1..659ca228bdcb0 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -42,6 +42,7 @@ class providing the base-class of operations. Timestamp, lib, ) +from pandas._libs.algos import rank_1d import pandas._libs.groupby as libgroupby from pandas._typing import ( AnyArrayLike, @@ -2268,12 +2269,15 @@ def size(self) -> DataFrame | Series: else: result = self._obj_1d_constructor(result) + with com.temp_setattr(self, "as_index", True): + # size already has the desired behavior in GH#49519, but this makes the + # as_index=False path of _reindex_output fail on categorical groupers. + result = self._reindex_output(result, fill_value=0) if not self.as_index: # error: Incompatible types in assignment (expression has # type "DataFrame", variable has type "Series") result = result.rename("size").reset_index() # type: ignore[assignment] - - return self._reindex_output(result, fill_value=0) + return result @final @doc(_groupby_agg_method_template, fname="sum", no=False, mc=0) @@ -3269,6 +3273,10 @@ def ngroup(self, ascending: bool = True): else: dtype = np.int64 + if any(ping._passed_categorical for ping in self.grouper.groupings): + # comp_ids reflect non-observed groups, we need only observed + comp_ids = rank_1d(comp_ids, ties_method="dense") - 1 + result = self._obj_1d_constructor(comp_ids, index, dtype=dtype) if not ascending: result = self.ngroups - 1 - result @@ -3950,7 +3958,7 @@ def _reindex_output( names = names + [None] index = MultiIndex.from_product(levels_list, names=names) if self.sort: - index = index.sortlevel()[0] + index = index.sort_values() if self.as_index: # Always holds for SeriesGroupBy unless GH#36507 is implemented @@ -3972,12 +3980,12 @@ def _reindex_output( # reindex `output`, and then reset the in-axis grouper columns. # Select in-axis groupers - in_axis_grps = ( + in_axis_grps = list( (i, ping.name) for (i, ping) in enumerate(groupings) if ping.in_axis ) - g_nums, g_names = zip(*in_axis_grps) - - output = output.drop(labels=list(g_names), axis=1) + if len(in_axis_grps) > 0: + g_nums, g_names = zip(*in_axis_grps) + 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( @@ -3986,7 +3994,8 @@ def _reindex_output( # Reset in-axis grouper columns # (using level numbers `g_nums` because level names may not be unique) - output = output.reset_index(level=g_nums) + if len(in_axis_grps) > 0: + output = output.reset_index(level=g_nums) return output.reset_index(drop=True) diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 9e756e7006bd4..d4818eabeac1b 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -612,6 +612,9 @@ def group_arraylike(self) -> ArrayLike: # retain dtype for categories, including unobserved ones return self.result_index._values + elif self._passed_categorical: + return self.group_index._values + return self._codes_and_uniques[1] @cache_readonly @@ -621,14 +624,31 @@ def result_index(self) -> Index: if self._all_grouper is not None: group_idx = self.group_index assert isinstance(group_idx, CategoricalIndex) - categories = self._all_grouper.categories + cats = self._orig_cats # set_categories is dynamically added - return group_idx.set_categories(categories) # type: ignore[attr-defined] + return group_idx.set_categories(cats) # type: ignore[attr-defined] return self.group_index @cache_readonly def group_index(self) -> Index: - uniques = self._codes_and_uniques[1] + codes, uniques = self._codes_and_uniques + if not self._dropna and self._passed_categorical: + assert isinstance(uniques, Categorical) + if self._sort and (codes == len(uniques)).any(): + # Add NA value on the end when sorting + uniques = Categorical.from_codes( + np.append(uniques.codes, [-1]), uniques.categories + ) + else: + # Need to determine proper placement of NA value when not sorting + cat = self.grouping_vector + na_idx = (cat.codes < 0).argmax() + if cat.codes[na_idx] < 0: + # count number of unique codes that comes before the nan value + na_unique_idx = algorithms.nunique_ints(cat.codes[:na_idx]) + uniques = Categorical.from_codes( + np.insert(uniques.codes, na_unique_idx, -1), uniques.categories + ) return Index._with_infer(uniques, name=self.name) @cache_readonly @@ -651,9 +671,28 @@ def _codes_and_uniques(self) -> tuple[npt.NDArray[np.signedinteger], ArrayLike]: uniques = Categorical.from_codes( codes=ucodes, categories=categories, ordered=cat.ordered ) + + codes = cat.codes + if not self._dropna: + na_mask = codes < 0 + if np.any(na_mask): + if self._sort: + # Replace NA codes with `largest code + 1` + na_code = len(categories) + codes = np.where(na_mask, na_code, codes) + else: + # Insert NA code into the codes based on first appearance + # A negative code must exist, no need to check codes[na_idx] < 0 + na_idx = na_mask.argmax() + # count number of unique codes that comes before the nan value + na_code = algorithms.nunique_ints(codes[:na_idx]) + codes = np.where(codes >= na_code, codes + 1, codes) + codes = np.where(na_mask, na_code, codes) + if not self._observed: uniques = uniques.reorder_categories(self._orig_cats) - return cat.codes, uniques + + return codes, uniques elif isinstance(self.grouping_vector, ops.BaseGrouper): # we have a list of groupers diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index b35c4158bf420..48d0ee15c80a4 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -831,6 +831,7 @@ def test_preserve_categories(): df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)}) sort_index = CategoricalIndex(categories, categories, ordered=False, name="A") # GH#48749 - don't change order of categories + # GH#42482 - don't sort result when sort=False, even when ordered=True nosort_index = CategoricalIndex(list("bac"), list("abc"), ordered=False, name="A") tm.assert_index_equal( df.groupby("A", sort=True, observed=False).first().index, sort_index @@ -1218,7 +1219,7 @@ def test_seriesgroupby_observed_true(df_cat, operation): lev_a = Index(["bar", "bar", "foo", "foo"], dtype=df_cat["A"].dtype, name="A") lev_b = Index(["one", "three", "one", "two"], dtype=df_cat["B"].dtype, name="B") index = MultiIndex.from_arrays([lev_a, lev_b]) - expected = Series(data=[2, 4, 1, 3], index=index, name="C") + expected = Series(data=[2, 4, 1, 3], index=index, name="C").sort_index() grouped = df_cat.groupby(["A", "B"], observed=True)["C"] result = getattr(grouped, operation)(sum) diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py index 50eb9aabcc55c..5418a2a60dc80 100644 --- a/pandas/tests/groupby/test_groupby_dropna.py +++ b/pandas/tests/groupby/test_groupby_dropna.py @@ -7,6 +7,7 @@ import pandas as pd import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args @pytest.mark.parametrize( @@ -424,7 +425,7 @@ def test_groupby_drop_nan_with_multi_index(): ], ) @pytest.mark.parametrize("test_series", [True, False]) -def test_no_sort_keep_na(request, sequence_index, dtype, test_series): +def test_no_sort_keep_na(sequence_index, dtype, test_series, as_index): # GH#46584, GH#48794 # Convert sequence_index into a string sequence, e.g. 5 becomes "xxyz" @@ -433,11 +434,6 @@ def test_no_sort_keep_na(request, sequence_index, dtype, test_series): [{0: "x", 1: "y", 2: "z"}[sequence_index // (3**k) % 3] for k in range(4)] ) - if dtype == "category" and "z" in sequence: - # Only xfail when nulls are present - msg = "dropna=False not correct for categorical, GH#48645" - request.node.add_marker(pytest.mark.xfail(reason=msg)) - # Unique values to use for grouper, depends on dtype if dtype in ("string", "string[pyarrow]"): uniques = {"x": "x", "y": "y", "z": pd.NA} @@ -452,7 +448,7 @@ def test_no_sort_keep_na(request, sequence_index, dtype, test_series): "a": [0, 1, 2, 3], } ) - gb = df.groupby("key", dropna=False, sort=False) + gb = df.groupby("key", dropna=False, sort=False, as_index=as_index) if test_series: gb = gb["a"] result = gb.sum() @@ -477,6 +473,10 @@ def test_no_sort_keep_na(request, sequence_index, dtype, test_series): expected = pd.Series(summed.values(), index=index, name="a", dtype=None) if not test_series: expected = expected.to_frame() + if not as_index: + expected = expected.reset_index() + if dtype is not None and dtype.startswith("Sparse"): + expected["key"] = expected["key"].astype(dtype) tm.assert_equal(result, expected) @@ -498,3 +498,187 @@ def test_null_is_null_for_dtype( tm.assert_series_equal(result, expected["a"]) else: tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +def test_categorical_reducers( + request, reduction_func, observed, sort, as_index, index_kind +): + # GH#36327 + if ( + reduction_func in ("idxmin", "idxmax") + and not observed + and index_kind != "multi" + ): + msg = "GH#10694 - idxmin/max broken for categorical with observed=False" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + + # Ensure there is at least one null value by appending to the end + values = np.append(np.random.choice([1, 2, None], size=19), None) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(20)} + ) + + # Strategy: Compare to dropna=True by filling null values with a new code + df_filled = df.copy() + df_filled["x"] = pd.Categorical(values, categories=[1, 2, 3, 4]).fillna(4) + + if index_kind == "range": + keys = ["x"] + elif index_kind == "single": + keys = ["x"] + df = df.set_index("x") + df_filled = df_filled.set_index("x") + else: + keys = ["x", "x2"] + df["x2"] = df["x"] + df = df.set_index(["x", "x2"]) + df_filled["x2"] = df_filled["x"] + df_filled = df_filled.set_index(["x", "x2"]) + args = get_groupby_method_args(reduction_func, df) + args_filled = get_groupby_method_args(reduction_func, df_filled) + if reduction_func == "corrwith" and index_kind == "range": + # Don't include the grouping columns so we can call reset_index + args = (args[0].drop(columns=keys),) + args_filled = (args_filled[0].drop(columns=keys),) + + gb_filled = df_filled.groupby(keys, observed=observed, sort=sort, as_index=True) + expected = getattr(gb_filled, reduction_func)(*args_filled).reset_index() + expected["x"] = expected["x"].replace(4, None) + if index_kind == "multi": + expected["x2"] = expected["x2"].replace(4, None) + if as_index: + if index_kind == "multi": + expected = expected.set_index(["x", "x2"]) + else: + expected = expected.set_index("x") + else: + if index_kind != "range" and reduction_func != "size": + # size, unlike other methods, has the desired behavior in GH#49519 + expected = expected.drop(columns="x") + if index_kind == "multi": + expected = expected.drop(columns="x2") + if reduction_func in ("idxmax", "idxmin") and index_kind != "range": + # expected was computed with a RangeIndex; need to translate to index values + values = expected["y"].values.tolist() + if index_kind == "single": + values = [np.nan if e == 4 else e for e in values] + else: + values = [(np.nan, np.nan) if e == (4, 4) else e for e in values] + expected["y"] = values + if reduction_func == "size": + # size, unlike other methods, has the desired behavior in GH#49519 + expected = expected.rename(columns={0: "size"}) + if as_index: + expected = expected["size"].rename(None) + + gb_keepna = df.groupby( + keys, dropna=False, observed=observed, sort=sort, as_index=as_index + ) + result = getattr(gb_keepna, reduction_func)(*args) + + # size will return a Series, others are DataFrame + tm.assert_equal(result, expected) + + +def test_categorical_transformers( + request, transformation_func, observed, sort, as_index +): + # GH#36327 + if transformation_func == "fillna": + msg = "GH#49651 fillna may incorrectly reorders results when dropna=False" + request.node.add_marker(pytest.mark.xfail(reason=msg, strict=False)) + + values = np.append(np.random.choice([1, 2, None], size=19), None) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(20)} + ) + args = get_groupby_method_args(transformation_func, df) + + # Compute result for null group + null_group_values = df[df["x"].isnull()]["y"] + if transformation_func == "cumcount": + null_group_data = list(range(len(null_group_values))) + elif transformation_func == "ngroup": + if sort: + if observed: + na_group = df["x"].nunique(dropna=False) - 1 + else: + # TODO: Should this be 3? + na_group = df["x"].nunique(dropna=False) - 1 + else: + na_group = df.iloc[: null_group_values.index[0]]["x"].nunique() + null_group_data = len(null_group_values) * [na_group] + else: + null_group_data = getattr(null_group_values, transformation_func)(*args) + null_group_result = pd.DataFrame({"y": null_group_data}) + + gb_keepna = df.groupby( + "x", dropna=False, observed=observed, sort=sort, as_index=as_index + ) + gb_dropna = df.groupby("x", dropna=True, observed=observed, sort=sort) + result = getattr(gb_keepna, transformation_func)(*args) + expected = getattr(gb_dropna, transformation_func)(*args) + for iloc, value in zip( + df[df["x"].isnull()].index.tolist(), null_group_result.values + ): + if expected.ndim == 1: + expected.iloc[iloc] = value + else: + expected.iloc[iloc, 0] = value + if transformation_func == "ngroup": + expected[df["x"].notnull() & expected.ge(na_group)] += 1 + if transformation_func not in ("rank", "diff", "pct_change", "shift"): + expected = expected.astype("int64") + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("method", ["head", "tail"]) +def test_categorical_head_tail(method, observed, sort, as_index): + # GH#36327 + values = np.random.choice([1, 2, None], 30) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))} + ) + gb = df.groupby("x", dropna=False, observed=observed, sort=sort, as_index=as_index) + result = getattr(gb, method)() + + if method == "tail": + values = values[::-1] + # Take the top 5 values from each group + mask = ( + ((values == 1) & ((values == 1).cumsum() <= 5)) + | ((values == 2) & ((values == 2).cumsum() <= 5)) + # flake8 doesn't like the vectorized check for None, thinks we should use `is` + | ((values == None) & ((values == None).cumsum() <= 5)) # noqa: E711 + ) + if method == "tail": + mask = mask[::-1] + expected = df[mask] + + tm.assert_frame_equal(result, expected) + + +def test_categorical_agg(): + # GH#36327 + values = np.random.choice([1, 2, None], 30) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))} + ) + gb = df.groupby("x", dropna=False) + result = gb.agg(lambda x: x.sum()) + expected = gb.sum() + tm.assert_frame_equal(result, expected) + + +def test_categorical_transform(): + # GH#36327 + values = np.random.choice([1, 2, None], 30) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))} + ) + gb = df.groupby("x", dropna=False) + result = gb.transform(lambda x: x.sum()) + expected = gb.transform("sum") + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index b982d247c2707..df83a5e410e71 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -852,6 +852,14 @@ def test_unique_masked(self, any_numeric_ea_dtype): tm.assert_extension_array_equal(result, expected) +def test_nunique_ints(index_or_series_or_array): + # GH#36327 + values = index_or_series_or_array(np.random.randint(0, 20, 30)) + result = algos.nunique_ints(values) + expected = len(algos.unique(values)) + assert result == expected + + class TestIsin: def test_invalid(self):
- [x] closes #36327 (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. The function nunique here is faster than using `pd.unique`, but only works on integers: ``` arr = np.random.randint(0, 300, size) %timeit len(unique(arr)) %timeit nunique_ints(arr) size: 10 8.94 µs ± 133 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) 2.94 µs ± 12.2 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) size: 100 9.82 µs ± 22.2 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) 3.01 µs ± 5.16 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) size: 1000 11 µs ± 76.5 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) 3.74 µs ± 9.7 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) size: 10000 27.9 µs ± 66.8 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) 10.4 µs ± 9.43 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) size: 100000 187 µs ± 214 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) 78.8 µs ± 408 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/49652
2022-11-11T18:14:37Z
2022-12-02T18:49:42Z
2022-12-02T18:49:42Z
2022-12-02T20:09:31Z
STYLE: fix pylint reimported warnings
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 6cce1137e707b..64f5d97f588c5 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -610,8 +610,6 @@ def makeCustomIndex( for i in range(nlevels): def keyfunc(x): - import re - numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_") return [int(num) for num in numeric_tuple] diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index ee94c1d3aae0c..e5f716c62eca7 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -62,7 +62,6 @@ def set_timezone(tz: str) -> Generator[None, None, None]: ... 'EST' """ - import os import time def setTZ(tz) -> None: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d26a11eae9f7f..8398abc9cc78a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9045,8 +9045,6 @@ def compare( keep_equal: bool_t = False, result_names: Suffixes = ("self", "other"), ): - from pandas.core.reshape.concat import concat - if type(self) is not type(other): cls_self, cls_other = type(self).__name__, type(other).__name__ raise TypeError( diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 591fa25bd36d1..a7d1da69e2729 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -741,7 +741,6 @@ def pandasSQL_builder(con, schema: str | None = None) -> SQLDatabase | SQLiteDat provided parameters. """ import sqlite3 - import warnings if isinstance(con, sqlite3.Connection) or con is None: return SQLiteDatabase(con) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index dea5dbd33bbdf..27603f7d987d2 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1655,8 +1655,6 @@ def _start_base(self): return self.bottom def _make_plot(self) -> None: - import matplotlib as mpl - colors = self._get_colors() ncolors = len(colors) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index e3b7ad8f78750..9659b4aa5f45c 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -393,8 +393,6 @@ def test_groupby_grouper(self, df): def test_groupby_dict_mapping(self): # GH #679 - from pandas import Series - s = Series({"T1": 5}) result = s.groupby({"T1": "T2"}).agg(sum) expected = s.groupby(["T2"]).agg(sum) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 0068a0a0ded67..26eb7532adfa4 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -953,11 +953,7 @@ def test_loc_coercion(self): def test_loc_coercion2(self): # GH#12045 - import datetime - - df = DataFrame( - {"date": [datetime.datetime(2012, 1, 1), datetime.datetime(1012, 1, 2)]} - ) + df = DataFrame({"date": [datetime(2012, 1, 1), datetime(1012, 1, 2)]}) expected = df.dtypes result = df.iloc[[0]] diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index ee2a8f518cd56..bff4c98fe2842 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -882,10 +882,7 @@ def test_read_from_file_url(self, read_ext, datapath): tm.assert_frame_equal(url_table, local_table) def test_read_from_pathlib_path(self, read_ext): - # GH12655 - from pathlib import Path - str_path = "test1" + read_ext expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index f870ef25991df..640c686bb56ca 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -5,6 +5,7 @@ from datetime import ( datetime, time, + timedelta, ) from io import StringIO import itertools @@ -994,12 +995,10 @@ def test_truncate_with_different_dtypes(self): # when truncated the dtypes of the splits can differ # 11594 - import datetime - s = Series( - [datetime.datetime(2012, 1, 1)] * 10 - + [datetime.datetime(1012, 1, 2)] - + [datetime.datetime(2012, 1, 3)] * 10 + [datetime(2012, 1, 1)] * 10 + + [datetime(1012, 1, 2)] + + [datetime(2012, 1, 3)] * 10 ) with option_context("display.max_rows", 8): @@ -1250,8 +1249,6 @@ def test_long_series(self): dtype="int64", ) - import re - str_rep = str(s) nmatches = len(re.findall("dtype", str_rep)) assert nmatches == 1 @@ -2445,12 +2442,6 @@ def test_datetimeindex_highprecision(self, start_date): assert start_date in result def test_timedelta64(self): - - from datetime import ( - datetime, - timedelta, - ) - Series(np.array([1100, 20], dtype="timedelta64[ns]")).to_string() s = Series(date_range("2012-1-1", periods=3, freq="D")) diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 231228ef6c0af..986c0039715a6 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -866,7 +866,7 @@ def test_with_large_max_level(self): def test_deprecated_import(self): with tm.assert_produces_warning(FutureWarning): - from pandas.io.json import json_normalize + from pandas.io.json import json_normalize # pylint: disable=reimported recs = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}] json_normalize(recs) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 8888e2687621d..7d60ebabfbe01 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -890,8 +890,6 @@ def test_idxmax(self): allna = string_series * np.nan assert isna(allna.idxmax()) - from pandas import date_range - s = Series(date_range("20130102", periods=6)) result = s.idxmax() assert result == 5 diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py index 93d212d0a581d..f16358813488e 100644 --- a/pandas/tests/reshape/concat/test_datetimes.py +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -22,8 +22,6 @@ class TestDatetimeConcat: def test_concat_datetime64_block(self): - from pandas.core.indexes.datetimes import date_range - rng = date_range("1/1/2000", periods=10) df = DataFrame({"time": rng}) diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index 1e929cd43842b..689c8ba845a6c 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -632,12 +632,6 @@ def test_strftime_all_nat(self, data): tm.assert_series_equal(result, expected) def test_valid_dt_with_missing_values(self): - - from datetime import ( - date, - time, - ) - # GH 8689 ser = Series(date_range("20130101", periods=5, freq="D")) ser.iloc[2] = pd.NaT diff --git a/pandas/tests/tseries/offsets/test_custom_business_month.py b/pandas/tests/tseries/offsets/test_custom_business_month.py index 36c690e89256d..bc9f7f3f511b8 100644 --- a/pandas/tests/tseries/offsets/test_custom_business_month.py +++ b/pandas/tests/tseries/offsets/test_custom_business_month.py @@ -400,8 +400,6 @@ def test_holidays(self): @pytest.mark.filterwarnings("ignore:Non:pandas.errors.PerformanceWarning") def test_datetimeindex(self): - from pandas.tseries.holiday import USFederalHolidayCalendar - hcal = USFederalHolidayCalendar() freq = CBMonthEnd(calendar=hcal) diff --git a/pyproject.toml b/pyproject.toml index 71b1f44dbff6f..b436b29c03c84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -153,7 +153,6 @@ disable = [ "raise-missing-from", "redefined-builtin", "redefined-outer-name", - "reimported", "self-assigning-variable", "self-cls-assignment", "signature-differs",
Related to https://github.com/pandas-dev/pandas/issues/48855 - [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/49645
2022-11-11T14:59:05Z
2022-11-11T20:53:59Z
2022-11-11T20:53:59Z
2022-11-12T00:53:08Z
BUG: groupby.describe with as_index=False incorrect
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index efb4a572486e3..28c4b89b925dd 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -716,7 +716,9 @@ Groupby/resample/rolling - Bug in :class:`.DataFrameGroupBy` and :class:`.SeriesGroupBy` would not include unobserved categories in result when grouping by categorical indexes (:issue:`49354`) - Bug in :class:`.DataFrameGroupBy` and :class:`.SeriesGroupBy` would change result order depending on the input index when grouping by categoricals (:issue:`49223`) - Bug in :class:`.DataFrameGroupBy` and :class:`.SeriesGroupBy` when grouping on categorical data would sort result values even when used with ``sort=False`` (:issue:`42482`) -- +- Bug in :meth:`.DataFrameGroupBy.apply` and :class:`SeriesGroupBy.apply` with ``as_index=False`` would not attempt the computation without using the grouping keys when using them failed with a ``TypeError`` (:issue:`49256`) +- Bug in :meth:`.DataFrameGroupBy.describe` would describe the group keys (:issue:`49256`) +- Bug in :meth:`.SeriesGroupBy.describe` with ``as_index=False`` would have the incorrect shape (:issue:`49256`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 7a225712b63a7..1d8271a845f9a 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1061,8 +1061,7 @@ def _set_group_selection(self) -> None: # This is a no-op for SeriesGroupBy grp = self.grouper if not ( - self.as_index - and grp.groupings is not None + grp.groupings is not None and self.obj.ndim > 1 and self._group_selection is None ): @@ -2640,7 +2639,14 @@ def describe(self, **kwargs): ) if self.axis == 1: return result.T - return result.unstack() + + # GH#49256 - properly handle the grouping column(s) + if self._selected_obj.ndim != 1 or self.as_index: + result = result.unstack() + if not self.as_index: + self._insert_inaxis_grouper_inplace(result) + + return result @final def resample(self, rule, *args, **kwargs): diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index eb61f8defeaf8..af523928e0bc8 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -974,15 +974,21 @@ def test_apply_function_index_return(function): def test_apply_function_with_indexing_return_column(): - # GH#7002, GH#41480 + # GH#7002, GH#41480, GH#49256 df = DataFrame( { "foo1": ["one", "two", "two", "three", "one", "two"], "foo2": [1, 2, 4, 4, 5, 6], } ) - with pytest.raises(TypeError, match="Could not convert"): - df.groupby("foo1", as_index=False).apply(lambda x: x.mean()) + result = df.groupby("foo1", as_index=False).apply(lambda x: x.mean()) + expected = DataFrame( + { + "foo1": ["one", "three", "two"], + "foo2": [3.0, 4.0, 4.0], + } + ) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index b848ff81f35ee..ba3db6037245c 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -336,13 +336,7 @@ def test_describe(self, df, gb, gni): result = gb.describe() tm.assert_frame_equal(result, expected) - expected = pd.concat( - [ - df[df.A == 1].describe().unstack().to_frame().T, - df[df.A == 3].describe().unstack().to_frame().T, - ] - ) - expected.index = Index([0, 1]) + expected = expected.reset_index() result = gni.describe() tm.assert_frame_equal(result, expected) @@ -1093,6 +1087,38 @@ def test_series_describe_single(): tm.assert_series_equal(result, expected) +@pytest.mark.parametrize("keys", ["key1", ["key1", "key2"]]) +def test_series_describe_as_index(as_index, keys): + # GH#49256 + df = DataFrame( + { + "key1": ["one", "two", "two", "three", "two"], + "key2": ["one", "two", "two", "three", "two"], + "foo2": [1, 2, 4, 4, 6], + } + ) + gb = df.groupby(keys, as_index=as_index)["foo2"] + result = gb.describe() + expected = DataFrame( + { + "key1": ["one", "three", "two"], + "count": [1.0, 1.0, 3.0], + "mean": [1.0, 4.0, 4.0], + "std": [np.nan, np.nan, 2.0], + "min": [1.0, 4.0, 2.0], + "25%": [1.0, 4.0, 3.0], + "50%": [1.0, 4.0, 4.0], + "75%": [1.0, 4.0, 5.0], + "max": [1.0, 4.0, 6.0], + } + ) + if len(keys) == 2: + expected.insert(1, "key2", expected["key1"]) + if as_index: + expected = expected.set_index(keys) + tm.assert_frame_equal(result, expected) + + def test_series_index_name(df): grouped = df.loc[:, ["C"]].groupby(df["A"]) result = grouped.agg(lambda x: x.mean()) @@ -1177,29 +1203,25 @@ def test_frame_describe_unstacked_format(): "pandas.errors.PerformanceWarning" ) @pytest.mark.parametrize("as_index", [True, False]) -def test_describe_with_duplicate_output_column_names(as_index): +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +def test_describe_with_duplicate_output_column_names(as_index, keys): # GH 35314 df = DataFrame( { - "a": [99, 99, 99, 88, 88, 88], + "a1": [99, 99, 99, 88, 88, 88], + "a2": [99, 99, 99, 88, 88, 88], "b": [1, 2, 3, 4, 5, 6], "c": [10, 20, 30, 40, 50, 60], }, - columns=["a", "b", "b"], + columns=["a1", "a2", "b", "b"], copy=False, ) + if keys == ["a1"]: + df = df.drop(columns="a2") expected = ( DataFrame.from_records( [ - ("a", "count", 3.0, 3.0), - ("a", "mean", 88.0, 99.0), - ("a", "std", 0.0, 0.0), - ("a", "min", 88.0, 99.0), - ("a", "25%", 88.0, 99.0), - ("a", "50%", 88.0, 99.0), - ("a", "75%", 88.0, 99.0), - ("a", "max", 88.0, 99.0), ("b", "count", 3.0, 3.0), ("b", "mean", 5.0, 2.0), ("b", "std", 1.0, 1.0), @@ -1222,14 +1244,17 @@ def test_describe_with_duplicate_output_column_names(as_index): .T ) expected.columns.names = [None, None] - expected.index = Index([88, 99], name="a") - - if as_index: - expected = expected.drop(columns=["a"], level=0) + if len(keys) == 2: + expected.index = MultiIndex( + levels=[[88, 99], [88, 99]], codes=[[0, 1], [0, 1]], names=["a1", "a2"] + ) else: - expected = expected.reset_index(drop=True) + expected.index = Index([88, 99], name="a1") + + if not as_index: + expected = expected.reset_index() - result = df.groupby("a", as_index=as_index).describe() + result = df.groupby(keys, as_index=as_index).describe() tm.assert_frame_equal(result, expected)
- [x] closes #49256 (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. The describe bug was found while comparing differences between `_selected_obj` and `_obj_with_exclusions` (#46944). By removing `as_index` from the conditions that determine `_selected_obj`, we fix the describe bug, the apply inconsistency (see below), and bring `_selected_obj` and `_obj_with_exclusions` closer so that the latter can eventually be removed. Currently `groupby(...).apply` with `as_index=True` will try to use the group keys, then if that fails with a TypeError will try to redo the computation without the group keys. In main, this is also attempted when `as_index=False`, however in that case the selection context does not exclude the group keys and so it's really just attempting the same exact computation again. This PR fixes this inconsistency by making `as_index=False` adopt the `as_index=True` behavior. In the one test that picked this up, we now agree with the original behavior that was desired in #7002.
https://api.github.com/repos/pandas-dev/pandas/pulls/49643
2022-11-11T14:33:06Z
2022-11-18T01:36:50Z
2022-11-18T01:36:50Z
2022-11-18T03:03:03Z
DOC: Gitpod documentation
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index d0bda0ba42bd7..4e654f68dd317 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -1,4 +1,4 @@ -.. _contributing: +3.. _contributing: {{ header }} diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 449b6de36cd24..2f73cf08823b7 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -783,6 +783,7 @@ preferred if the inputs or logic are simple, with Hypothesis tests reserved for cases with complex logic or where there are too many combinations of options or subtle interactions to test (or think of!) all of them. +.. _contributing.running_tests: Running the test suite ---------------------- diff --git a/doc/source/development/contributing_documentation.rst b/doc/source/development/contributing_documentation.rst index fac6a91ce82f2..f064c5eb07a9a 100644 --- a/doc/source/development/contributing_documentation.rst +++ b/doc/source/development/contributing_documentation.rst @@ -127,6 +127,7 @@ for some tips and tricks to get the doctests passing. When doing a PR with a docstring update, it is good to post the output of the validation script in a comment on github. +.. _contributing.howto-build-docs: How to build the pandas documentation --------------------------------------- diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst index 942edd863a19a..703fcb58abd54 100644 --- a/doc/source/development/contributing_environment.rst +++ b/doc/source/development/contributing_environment.rst @@ -12,8 +12,11 @@ changes, you can skip to :ref:`contributing to the documentation <contributing_d creating the development environment you won't be able to build the documentation locally before pushing your changes. It's recommended to also install the :ref:`pre-commit hooks <contributing.pre-commit>`. -.. contents:: Table of contents: - :local: +.. toctree:: + :maxdepth: 2 + :hidden: + + contributing_gitpod.rst Step 1: install a C compiler ---------------------------- @@ -188,6 +191,17 @@ Enable Docker support and use the Services tool window to build and manage image run and interact with containers. See https://www.jetbrains.com/help/pycharm/docker.html for details. +Option 4: using Gitpod +~~~~~~~~~~~~~~~~~~~~~~ + +Gitpod is an open-source platform that automatically creates the correct development +environment right in your browser, reducing the need to install local development +environments and deal with incompatible dependencies. + +If you are a Windows user, unfamiliar with using the command line or building pandas +for the first time, it is often faster to build with Gitpod. Here are the in-depth instructions +for :ref:`building pandas with GitPod <contributing-gitpod>`. + Step 3: build and install pandas -------------------------------- diff --git a/doc/source/development/contributing_gitpod.rst b/doc/source/development/contributing_gitpod.rst new file mode 100644 index 0000000000000..664711dc8928b --- /dev/null +++ b/doc/source/development/contributing_gitpod.rst @@ -0,0 +1,273 @@ +.. _contributing-gitpod: + +Using Gitpod for pandas development +=================================== + +This section of the documentation will guide you through: + +* using Gitpod for your pandas development environment +* creating a personal fork of the pandas repository on GitHub +* a quick tour of pandas and VSCode +* working on the pandas documentation in Gitpod + +Gitpod +------ + +`Gitpod`_ is an open-source platform for automated and ready-to-code +development environments. It enables developers to describe their dev +environment as code and start instant and fresh development environments for +each new task directly from your browser. This reduces the need to install local +development environments and deal with incompatible dependencies. + + +Gitpod GitHub integration +------------------------- + +To be able to use Gitpod, you will need to have the Gitpod app installed on your +GitHub account, so if +you do not have an account yet, you will need to create one first. + +To get started just login at `Gitpod`_, and grant the appropriate permissions to GitHub. + +We have built a python 3.8 environment and all development dependencies will +install when the environment starts. + + +Forking the pandas repository +----------------------------- + +The best way to work on pandas as a contributor is by making a fork of the +repository first. + +#. Browse to the `pandas repository on GitHub`_ and `create your own fork`_. + +#. Browse to your fork. Your fork will have a URL like + https://github.com/noatamir/pandas-dev, except with your GitHub username in place of + ``noatamir``. + +Starting Gitpod +--------------- +Once you have authenticated to Gitpod through GitHub, you can install the +`Gitpod Chromium or Firefox browser extension <https://www.gitpod.io/docs/browser-extension>`_ +which will add a **Gitpod** button next to the **Code** button in the +repository: + +.. image:: ./gitpod-imgs/pandas-github.png + :alt: pandas repository with Gitpod button screenshot + +#. If you install the extension - you can click the **Gitpod** button to start + a new workspace. + +#. Alternatively, if you do not want to install the browser extension, you can + visit https://gitpod.io/#https://github.com/USERNAME/pandas replacing + ``USERNAME`` with your GitHub username. + +#. In both cases, this will open a new tab on your web browser and start + building your development environment. Please note this can take a few + minutes. + +#. Once the build is complete, you will be directed to your workspace, + including the VSCode editor and all the dependencies you need to work on + pandas. The first time you start your workspace, you will notice that there + might be some actions running. This will ensure that you have a development + version of pandas installed. + +#. When your workspace is ready, you can :ref:`test the build<contributing.running_tests>` by + entering:: + + $ python -m pytest pandas + + +Quick workspace tour +-------------------- +Gitpod uses VSCode as the editor. If you have not used this editor before, you +can check the Getting started `VSCode docs`_ to familiarize yourself with it. + +Your workspace will look similar to the image below: + +.. image:: ./gitpod-imgs/gitpod-workspace.png + :alt: Gitpod workspace screenshot + +We have marked some important sections in the editor: + +#. Your current Python interpreter - by default, this is ``pandas-dev`` and + should be displayed in the status bar and on your terminal. You do not need + to activate the conda environment as this will always be activated for you. +#. Your current branch is always displayed in the status bar. You can also use + this button to change or create branches. +#. GitHub Pull Requests extension - you can use this to work with Pull Requests + from your workspace. +#. Marketplace extensions - we have added some essential extensions to the pandas + Gitpod. Still, you can also install other extensions or syntax highlighting + themes for your user, and these will be preserved for you. +#. Your workspace directory - by default, it is ``/workspace/pandas-dev``. **Do not + change this** as this is the only directory preserved in Gitpod. + +We have also pre-installed a few tools and VSCode extensions to help with the +development experience: + +* `VSCode rst extension <https://marketplace.visualstudio.com/items?itemName=lextudio.restructuredtext>`_ +* `Markdown All in One <https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one>`_ +* `VSCode Gitlens extension <https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens>`_ +* `VSCode Git Graph extension <https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph>`_ + +Development workflow with Gitpod +-------------------------------- +The :ref:`contributing` section of this documentation contains +information regarding the pandas development workflow. Make sure to check this +before working on your contributions. + +When using Gitpod, git is pre configured for you: + +#. You do not need to configure your git username, and email as this should be + done for you as you authenticated through GitHub. Unless you are using GitHub + feature to keep email address private. You can check the git + configuration with the command ``git config --list`` in your terminal. Use + ``git config --global user.email “your-secret-email@users.noreply.github.com”`` + to set your email address to the one you use to make commits with your github + profile. +#. As you started your workspace from your own pandas fork, you will by default + have both ``upstream`` and ``origin`` added as remotes. You can verify this by + typing ``git remote`` on your terminal or by clicking on the **branch name** + on the status bar (see image below). + + .. image:: ./gitpod-imgs/pandas-gitpod-branches.png + :alt: Gitpod workspace branches plugin screenshot + +Rendering the pandas documentation +---------------------------------- +You can find the detailed documentation on how rendering the documentation with +Sphinx works in the :ref:`contributing.howto-build-docs` section. To build the full +docs you need to run the following command in the docs directory:: + + $ cd docs + $ python make.py html + +Alternatively you can build a single page with:: + + python make.py html python make.py --single development/contributing_gitpod.rst + +You have two main options to render the documentation in Gitpod. + +Option 1: using Liveserve +~~~~~~~~~~~~~~~~~~~~~~~~~ + +#. View the documentation in ``pandas/doc/build/html``. +#. To see the rendered version of a page, you can right-click on the ``.html`` + file and click on **Open with Live Serve**. Alternatively, you can open the + file in the editor and click on the **Go live** button on the status bar. + + .. image:: ./gitpod-imgs/vscode-statusbar.png + :alt: Gitpod workspace VSCode start live serve screenshot + +#. A simple browser will open to the right-hand side of the editor. We recommend + closing it and click on the **Open in browser** button in the pop-up. +#. To stop the server click on the **Port: 5500** button on the status bar. + +Option 2: using the rst extension +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A quick and easy way to see live changes in a ``.rst`` file as you work on it +uses the rst extension with docutils. + +.. note:: This will generate a simple live preview of the document without the + ``html`` theme, and some backlinks might not be added correctly. But it is an + easy and lightweight way to get instant feedback on your work, without + building the html files. + +#. Open any of the source documentation files located in ``doc/source`` in the + editor. +#. Open VSCode Command Palette with :kbd:`Cmd-Shift-P` in Mac or + :kbd:`Ctrl-Shift-P` in Linux and Windows. Start typing "restructured" + and choose either "Open preview" or "Open preview to the Side". + + .. image:: ./gitpod-imgs/vscode-rst.png + :alt: Gitpod workspace VSCode open rst screenshot + +#. As you work on the document, you will see a live rendering of it on the editor. + + .. image:: ./gitpod-imgs/rst-rendering.png + :alt: Gitpod workspace VSCode rst rendering screenshot + +If you want to see the final output with the ``html`` theme you will need to +rebuild the docs with ``make html`` and use Live Serve as described in option 1. + +FAQ's and troubleshooting +------------------------- + +How long is my Gitpod workspace kept for? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Your stopped workspace will be kept for 14 days and deleted afterwards if you do +not use them. + +Can I come back to a previous workspace? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yes, let's say you stepped away for a while and you want to carry on working on +your pandas contributions. You need to visit https://gitpod.io/workspaces and +click on the workspace you want to spin up again. All your changes will be there +as you last left them. + +Can I install additional VSCode extensions? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Absolutely! Any extensions you installed will be installed in your own workspace +and preserved. + +I registered on Gitpod but I still cannot see a ``Gitpod`` button in my repositories. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Head to https://gitpod.io/integrations and make sure you are logged in. +Hover over GitHub and click on the three buttons that appear on the right. +Click on edit permissions and make sure you have ``user:email``, +``read:user``, and ``public_repo`` checked. Click on **Update Permissions** +and confirm the changes in the GitHub application page. + +.. image:: ./gitpod-imgs/gitpod-edit-permissions-gh.png + :alt: Gitpod integrations - edit GH permissions screenshot + +How long does my workspace stay active if I'm not using it? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you keep your workspace open in a browser tab but don't interact with it, +it will shut down after 30 minutes. If you close the browser tab, it will +shut down after 3 minutes. + +My terminal is blank - there is no cursor and it's completely unresponsive +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Unfortunately this is a known-issue on Gitpod's side. You can sort this +issue in two ways: + +#. Create a new Gitpod workspace altogether. +#. Head to your `Gitpod dashboard <https://gitpod.io/workspaces>`_ and locate + the running workspace. Hover on it and click on the **three dots menu** + and then click on **Stop**. When the workspace is completely stopped you + can click on its name to restart it again. + +.. image:: ./gitpod-imgs/gitpod-dashboard-stop.png + :alt: Gitpod dashboard and workspace menu screenshot + +I authenticated through GitHub but I still cannot commit to the repository through Gitpod. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Head to https://gitpod.io/integrations and make sure you are logged in. +Hover over GitHub and click on the three buttons that appear on the right. +Click on edit permissions and make sure you have ``public_repo`` checked. +Click on **Update Permissions** and confirm the changes in the +GitHub application page. + +.. image:: ./gitpod-imgs/gitpod-edit-permissions-repo.png + :alt: Gitpod integrations - edit GH repository permissions screenshot + +Acknowledgments +--------------- + +This page is lightly adapted from the `NumPy`_ project . + +.. _Gitpod: https://www.gitpod.io/ +.. _pandas repository on GitHub: https://github.com/pandas-dev/pandas +.. _create your own fork: https://help.github.com/en/articles/fork-a-repo +.. _VSCode docs: https://code.visualstudio.com/docs/getstarted/tips-and-tricks +.. _NumPy: https://www.numpy.org/ diff --git a/doc/source/development/gitpod-imgs/gitpod-dashboard-stop.png b/doc/source/development/gitpod-imgs/gitpod-dashboard-stop.png new file mode 100644 index 0000000000000..b64790a986646 Binary files /dev/null and b/doc/source/development/gitpod-imgs/gitpod-dashboard-stop.png differ diff --git a/doc/source/development/gitpod-imgs/gitpod-edit-permissions-gh.png b/doc/source/development/gitpod-imgs/gitpod-edit-permissions-gh.png new file mode 100644 index 0000000000000..ec21a9064c83d Binary files /dev/null and b/doc/source/development/gitpod-imgs/gitpod-edit-permissions-gh.png differ diff --git a/doc/source/development/gitpod-imgs/gitpod-edit-permissions-repo.png b/doc/source/development/gitpod-imgs/gitpod-edit-permissions-repo.png new file mode 100644 index 0000000000000..8bfaff81cfb69 Binary files /dev/null and b/doc/source/development/gitpod-imgs/gitpod-edit-permissions-repo.png differ diff --git a/doc/source/development/gitpod-imgs/gitpod-workspace.png b/doc/source/development/gitpod-imgs/gitpod-workspace.png new file mode 100644 index 0000000000000..daf763e9adb05 Binary files /dev/null and b/doc/source/development/gitpod-imgs/gitpod-workspace.png differ diff --git a/doc/source/development/gitpod-imgs/pandas-github.png b/doc/source/development/gitpod-imgs/pandas-github.png new file mode 100644 index 0000000000000..010b0fc5ea33d Binary files /dev/null and b/doc/source/development/gitpod-imgs/pandas-github.png differ diff --git a/doc/source/development/gitpod-imgs/pandas-gitpod-branches.png b/doc/source/development/gitpod-imgs/pandas-gitpod-branches.png new file mode 100644 index 0000000000000..f95c66056ca37 Binary files /dev/null and b/doc/source/development/gitpod-imgs/pandas-gitpod-branches.png differ diff --git a/doc/source/development/gitpod-imgs/rst-rendering.png b/doc/source/development/gitpod-imgs/rst-rendering.png new file mode 100644 index 0000000000000..b613c621c398b Binary files /dev/null and b/doc/source/development/gitpod-imgs/rst-rendering.png differ diff --git a/doc/source/development/gitpod-imgs/vscode-rst.png b/doc/source/development/gitpod-imgs/vscode-rst.png new file mode 100644 index 0000000000000..5b574c115a2b7 Binary files /dev/null and b/doc/source/development/gitpod-imgs/vscode-rst.png differ diff --git a/doc/source/development/gitpod-imgs/vscode-statusbar.png b/doc/source/development/gitpod-imgs/vscode-statusbar.png new file mode 100644 index 0000000000000..dad25369fedfd Binary files /dev/null and b/doc/source/development/gitpod-imgs/vscode-statusbar.png differ diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py index f647f066d0125..44d59aecde718 100755 --- a/scripts/validate_rst_title_capitalization.py +++ b/scripts/validate_rst_title_capitalization.py @@ -151,6 +151,10 @@ "Numba", "Timestamp", "PyArrow", + "Gitpod", + "Liveserve", + "I", + "VSCode", } CAP_EXCEPTIONS_DICT = {word.lower(): word for word in CAPITALIZATION_EXCEPTIONS}
xref #48107 Documentation for using the development Gitpod.
https://api.github.com/repos/pandas-dev/pandas/pulls/49642
2022-11-11T13:36:24Z
2023-01-09T23:39:01Z
2023-01-09T23:39:01Z
2023-01-09T23:39:08Z
for #49638 updated the doc
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 6ed8dee044d1f..b230516c9c3e5 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -137,6 +137,7 @@ want to clone your fork to your machine:: git clone https://github.com/your-user-name/pandas.git pandas-yourname cd pandas-yourname git remote add upstream https://github.com/pandas-dev/pandas.git + git fetch upstream This creates the directory ``pandas-yourname`` and connects your repository to the upstream (main project) *pandas* repository.
added the `git fetch upstream` command - [x] closes #49638 - [ ] [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/49639
2022-11-11T10:15:34Z
2022-11-11T10:24:36Z
2022-11-11T10:24:36Z
2022-11-11T10:48:38Z
BUG/API: Indexes on empty frames/series should be RangeIndex
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 7838ef8df4164..1fc7a06f8b7f0 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -311,6 +311,35 @@ The new behavior, as for datetime64, either gives exactly the requested dtype or ser.astype("timedelta64[s]") ser.astype("timedelta64[D]") +.. _whatsnew_200.api_breaking.zero_len_indexes: + +Empty DataFrames/Series will now default to have a ``RangeIndex`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Before, constructing an empty (where ``data`` is ``None`` or an empty list-like argument) :class:`Series` or :class:`DataFrame` without +specifying the axes (``index=None``, ``columns=None``) would return the axes as empty :class:`Index` with object dtype. + +Now, the axes return an empty :class:`RangeIndex`. + +*Previous behavior*: + +.. code-block:: ipython + + In [8]: pd.Series().index + Out[8]: + Index([], dtype='object') + + In [9] pd.DataFrame().axes + Out[9]: + [Index([], dtype='object'), Index([], dtype='object')] + +*New behavior*: + +.. ipython:: python + + pd.Series().index + pd.DataFrame().axes + .. _whatsnew_200.api_breaking.deps: Increased minimum versions for dependencies @@ -370,6 +399,7 @@ Other API changes - Changed behavior of :class:`Index` constructor with an object-dtype ``numpy.ndarray`` containing all-``bool`` values or all-complex values, this will now retain object dtype, consistent with the :class:`Series` behavior (:issue:`49594`) - Changed behavior of :meth:`DataFrame.shift` with ``axis=1``, an integer ``fill_value``, and homogeneous datetime-like dtype, this now fills new columns with integer dtypes instead of casting to datetimelike (:issue:`49842`) - Files are now closed when encountering an exception in :func:`read_json` (:issue:`49921`) +- Changed behavior of :func:`read_csv`, :func:`read_json` & :func:`read_fwf`, where the index will now always be a :class:`RangeIndex`, when no index is specified. Previously the index would be a :class:`Index` with dtype ``object`` if the new DataFrame/Series has length 0 (:issue:`49572`) - :meth:`DataFrame.values`, :meth:`DataFrame.to_numpy`, :meth:`DataFrame.xs`, :meth:`DataFrame.reindex`, :meth:`DataFrame.fillna`, and :meth:`DataFrame.replace` no longer silently consolidate the underlying arrays; do ``df = df.copy()`` to ensure consolidation (:issue:`49356`) - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 98af277cc0bd7..37c48bb7adbba 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -632,8 +632,6 @@ def __init__( copy: bool | None = None, ) -> None: - if data is None: - data = {} if dtype is not None: dtype = self._validate_dtype(dtype) @@ -671,6 +669,12 @@ def __init__( else: copy = False + if data is None: + index = index if index is not None else default_index(0) + columns = columns if columns is not None else default_index(0) + dtype = dtype if dtype is not None else pandas_dtype(object) + data = [] + if isinstance(data, (BlockManager, ArrayManager)): mgr = self._init_mgr( data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy @@ -777,7 +781,7 @@ def __init__( mgr = dict_to_mgr( {}, index, - columns, + columns if columns is not None else default_index(0), dtype=dtype, typ=manager, ) @@ -2309,8 +2313,7 @@ def maybe_reorder( result_index = None if len(arrays) == 0 and index is None and length == 0: - # for backward compat use an object Index instead of RangeIndex - result_index = Index([]) + result_index = default_index(0) arrays, arr_columns = reorder_arrays(arrays, arr_columns, columns, length) return arrays, arr_columns, result_index diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 563011abe2c41..07fab0080a747 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -582,7 +582,7 @@ def _extract_index(data) -> Index: """ index: Index if len(data) == 0: - return Index([]) + return default_index(0) raw_lengths = [] indexes: list[list[Hashable] | Index] = [] diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index c422b5b14cacc..16f1a5d0b81e2 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1084,8 +1084,8 @@ def _get_join_info( else: join_index = default_index(len(left_indexer)) - if len(join_index) == 0: - join_index = join_index.astype(object) + if len(join_index) == 0 and not isinstance(join_index, MultiIndex): + join_index = default_index(0).set_names(join_index.name) return join_index, left_indexer, right_indexer def _create_join_index( diff --git a/pandas/core/series.py b/pandas/core/series.py index 1e5f565934b50..3d2783b939743 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -385,11 +385,16 @@ def __init__( if index is not None: index = ensure_index(index) - if data is None: - data = {} if dtype is not None: dtype = self._validate_dtype(dtype) + if data is None: + index = index if index is not None else default_index(0) + if len(index) or dtype is not None: + data = na_value_for_dtype(pandas_dtype(dtype), compat=False) + else: + data = [] + if isinstance(data, MultiIndex): raise NotImplementedError( "initializing a Series from a MultiIndex is not supported" diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index d6cb3d79c81e4..ddcd114aa352b 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -30,6 +30,8 @@ def dataframe_from_int_dict(data, frame_template): result = DataFrame(data, index=frame_template.index) if len(result.columns) > 0: result.columns = frame_template.columns[result.columns] + else: + result.columns = frame_template.columns.copy() return result results = {} diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index c5fc054952b1f..ff94502d69ca3 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -84,6 +84,7 @@ from pandas.core.indexes.api import ( Index, MultiIndex, + default_index, ensure_index_from_sequences, ) from pandas.core.series import Series @@ -1093,8 +1094,9 @@ def _get_empty_meta( # # Both must be non-null to ensure a successful construction. Otherwise, # we have to create a generic empty Index. + index: Index if (index_col is None or index_col is False) or index_names is None: - index = Index([]) + index = default_index(0) else: data = [Series([], dtype=dtype_dict[name]) for name in index_names] index = ensure_index_from_sequences(data, names=index_names) diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index e7c2618d388c2..c28c3ae58219a 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -114,14 +114,14 @@ def test_apply_with_reduce_empty(): result = empty_frame.apply(x.append, axis=1, result_type="expand") tm.assert_frame_equal(result, empty_frame) result = empty_frame.apply(x.append, axis=1, result_type="reduce") - expected = Series([], index=pd.Index([], dtype=object), dtype=np.float64) + expected = Series([], dtype=np.float64) tm.assert_series_equal(result, expected) empty_with_cols = DataFrame(columns=["a", "b", "c"]) result = empty_with_cols.apply(x.append, axis=1, result_type="expand") tm.assert_frame_equal(result, empty_with_cols) result = empty_with_cols.apply(x.append, axis=1, result_type="reduce") - expected = Series([], index=pd.Index([], dtype=object), dtype=np.float64) + expected = Series([], dtype=np.float64) tm.assert_series_equal(result, expected) # Ensure that x.append hasn't been called @@ -147,7 +147,7 @@ def test_nunique_empty(): tm.assert_series_equal(result, expected) result = df.T.nunique() - expected = Series([], index=pd.Index([]), dtype=np.float64) + expected = Series([], dtype=np.float64) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py index 61c879fb2b20f..add7b5c77ef65 100644 --- a/pandas/tests/apply/test_str.py +++ b/pandas/tests/apply/test_str.py @@ -8,7 +8,6 @@ from pandas import ( DataFrame, - Index, Series, ) import pandas._testing as tm @@ -149,8 +148,8 @@ def test_agg_cython_table_series(series, func, expected): tm.get_cython_table_params( Series(dtype=np.float64), [ - ("cumprod", Series([], Index([]), dtype=np.float64)), - ("cumsum", Series([], Index([]), dtype=np.float64)), + ("cumprod", Series([], dtype=np.float64)), + ("cumsum", Series([], dtype=np.float64)), ], ), tm.get_cython_table_params( diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py index b9f8f8512a995..29766ff392296 100644 --- a/pandas/tests/extension/base/constructors.py +++ b/pandas/tests/extension/base/constructors.py @@ -119,7 +119,7 @@ def test_construct_empty_dataframe(self, dtype): # GH 33623 result = pd.DataFrame(columns=["a"], dtype=dtype) expected = pd.DataFrame( - {"a": pd.array([], dtype=dtype)}, index=pd.Index([], dtype="object") + {"a": pd.array([], dtype=dtype)}, index=pd.RangeIndex(0) ) self.assert_frame_equal(result, expected) diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index 3d43dc47b5280..cab81f864d8d8 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -55,7 +55,7 @@ def test_dropna_frame(self, data_missing): # axis = 1 result = df.dropna(axis="columns") - expected = pd.DataFrame(index=[0, 1]) + expected = pd.DataFrame(index=pd.RangeIndex(2), columns=pd.Index([])) self.assert_frame_equal(result, expected) # multiple diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py index e4a92ecc5dac1..971ce2e467aa9 100644 --- a/pandas/tests/frame/indexing/test_xs.py +++ b/pandas/tests/frame/indexing/test_xs.py @@ -84,7 +84,7 @@ def test_xs_corner(self): # no columns but Index(dtype=object) df = DataFrame(index=["a", "b", "c"]) result = df.xs("a") - expected = Series([], name="a", index=Index([]), dtype=np.float64) + expected = Series([], name="a", dtype=np.float64) tm.assert_series_equal(result, expected) def test_xs_duplicates(self): diff --git a/pandas/tests/frame/methods/test_count.py b/pandas/tests/frame/methods/test_count.py index 43eb96f7f32d9..1553a8a86305d 100644 --- a/pandas/tests/frame/methods/test_count.py +++ b/pandas/tests/frame/methods/test_count.py @@ -28,7 +28,7 @@ def test_count(self): df = DataFrame() result = df.count() - expected = Series(0, index=[]) + expected = Series(dtype="int64") tm.assert_series_equal(result, expected) def test_count_objects(self, float_string_frame): diff --git a/pandas/tests/frame/methods/test_get_numeric_data.py b/pandas/tests/frame/methods/test_get_numeric_data.py index 8628b76f54b1d..456dfe1075981 100644 --- a/pandas/tests/frame/methods/test_get_numeric_data.py +++ b/pandas/tests/frame/methods/test_get_numeric_data.py @@ -17,7 +17,7 @@ def test_get_numeric_data_preserve_dtype(self): # get the numeric data obj = DataFrame({"A": [1, "2", 3.0]}) result = obj._get_numeric_data() - expected = DataFrame(index=[0, 1, 2], dtype=object) + expected = DataFrame(dtype=object, index=pd.RangeIndex(3), columns=[]) tm.assert_frame_equal(result, expected) def test_get_numeric_data(self): diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 6826b15596850..93e1bcc113765 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -420,7 +420,7 @@ def test_quantile_datetime(self): tm.assert_series_equal(result, expected) result = df[["a", "c"]].quantile([0.5], numeric_only=True) - expected = DataFrame(index=[0.5]) + expected = DataFrame(index=[0.5], columns=[]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -451,7 +451,7 @@ def test_quantile_dt64_empty(self, dtype, interp_method): interpolation=interpolation, method=method, ) - expected = DataFrame(index=[0.5]) + expected = DataFrame(index=[0.5], columns=[]) tm.assert_frame_equal(res, expected) @pytest.mark.parametrize("invalid", [-1, 2, [0.5, -1], [0.5, 2]]) diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py index 5f648c76d0aa4..271a32017dd97 100644 --- a/pandas/tests/frame/methods/test_rank.py +++ b/pandas/tests/frame/methods/test_rank.py @@ -483,7 +483,7 @@ def test_rank_object_first(self, frame_or_series, na_option, ascending, expected "data,expected", [ ({"a": [1, 2, "a"], "b": [4, 5, 6]}, DataFrame({"b": [1.0, 2.0, 3.0]})), - ({"a": [1, 2, "a"]}, DataFrame(index=range(3))), + ({"a": [1, 2, "a"]}, DataFrame(index=range(3), columns=[])), ], ) def test_rank_mixed_axis_zero(self, data, expected): diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py index 7487b2c70a264..638387452903b 100644 --- a/pandas/tests/frame/methods/test_to_csv.py +++ b/pandas/tests/frame/methods/test_to_csv.py @@ -390,7 +390,7 @@ def test_to_csv_dup_cols(self, nrows): def test_to_csv_empty(self): df = DataFrame(index=np.arange(10)) result, expected = self._return_result_expected(df, 1000) - tm.assert_frame_equal(result, expected, check_names=False) + tm.assert_frame_equal(result, expected, check_column_type=False) @pytest.mark.slow def test_to_csv_chunksize(self): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index cacfd6f7a77b1..8051fff7b329d 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -193,13 +193,11 @@ def test_series_with_name_not_matching_column(self): [ lambda: DataFrame(), lambda: DataFrame(None), - lambda: DataFrame({}), lambda: DataFrame(()), lambda: DataFrame([]), lambda: DataFrame(_ for _ in []), lambda: DataFrame(range(0)), lambda: DataFrame(data=None), - lambda: DataFrame(data={}), lambda: DataFrame(data=()), lambda: DataFrame(data=[]), lambda: DataFrame(data=(_ for _ in [])), @@ -213,6 +211,20 @@ def test_empty_constructor(self, constructor): assert len(result.columns) == 0 tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "constructor", + [ + lambda: DataFrame({}), + lambda: DataFrame(data={}), + ], + ) + def test_empty_constructor_object_index(self, constructor): + expected = DataFrame(columns=Index([])) + result = constructor() + assert len(result.index) == 0 + assert len(result.columns) == 0 + tm.assert_frame_equal(result, expected, check_index_type=True) + @pytest.mark.parametrize( "emptylike,expected_index,expected_columns", [ @@ -1391,7 +1403,7 @@ def test_constructor_generator(self): def test_constructor_list_of_dicts(self): result = DataFrame([{}]) - expected = DataFrame(index=[0]) + expected = DataFrame(index=RangeIndex(1), columns=[]) tm.assert_frame_equal(result, expected) def test_constructor_ordered_dict_nested_preserve_order(self): @@ -1762,7 +1774,7 @@ def test_constructor_empty_with_string_dtype(self): def test_constructor_empty_with_string_extension(self, nullable_string_dtype): # GH 34915 - expected = DataFrame(index=[], columns=["c1"], dtype=nullable_string_dtype) + expected = DataFrame(columns=["c1"], dtype=nullable_string_dtype) df = DataFrame(columns=["c1"], dtype=nullable_string_dtype) tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 6c6a923e363ae..f9f3868375ed5 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -1163,7 +1163,7 @@ def test_any_all_bool_only(self): ) result = df.all(bool_only=True) - expected = Series(dtype=np.bool_) + expected = Series(dtype=np.bool_, index=[]) tm.assert_series_equal(result, expected) df = DataFrame( diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index cb796e1b1ec64..f67e2125bbf54 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -1251,7 +1251,8 @@ def test_stack_timezone_aware_values(): @pytest.mark.parametrize("dropna", [True, False]) def test_stack_empty_frame(dropna): # GH 36113 - expected = Series(index=MultiIndex([[], []], [[], []]), dtype=np.float64) + levels = [np.array([], dtype=np.int64), np.array([], dtype=np.int64)] + expected = Series(dtype=np.float64, index=MultiIndex(levels=levels, codes=[[], []])) result = DataFrame(dtype=np.float64).stack(dropna=dropna) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 03b917edd357b..659703c4d6d8f 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -674,7 +674,7 @@ def test_no_args_raises(self): # but we do allow this result = gr.agg([]) - expected = DataFrame() + expected = DataFrame(columns=[]) tm.assert_frame_equal(result, expected) def test_series_named_agg_duplicates_no_raises(self): diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index dc09a2e0ea6ad..08c25fb74be83 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -103,7 +103,9 @@ def test_cython_agg_nothing_to_agg(): with pytest.raises(TypeError, match="Could not convert"): frame[["b"]].groupby(frame["a"]).mean() result = frame[["b"]].groupby(frame["a"]).mean(numeric_only=True) - expected = DataFrame([], index=frame["a"].sort_values().drop_duplicates()) + expected = DataFrame( + [], index=frame["a"].sort_values().drop_duplicates(), columns=[] + ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 6b4693b59408d..26cdfa2291021 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -683,7 +683,7 @@ def test_list_grouper_with_nat(self): [ ( "transform", - Series(name=2, dtype=np.float64, index=Index([])), + Series(name=2, dtype=np.float64), ), ( "agg", @@ -875,7 +875,7 @@ def test_groupby_with_single_column(self): df = DataFrame({"a": list("abssbab")}) tm.assert_frame_equal(df.groupby("a").get_group("a"), df.iloc[[0, 5]]) # GH 13530 - exp = DataFrame(index=Index(["a", "b", "s"], name="a")) + exp = DataFrame(index=Index(["a", "b", "s"], name="a"), columns=[]) tm.assert_frame_equal(df.groupby("a").count(), exp) tm.assert_frame_equal(df.groupby("a").sum(), exp) diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index f7e6665aad253..db088c7a2afea 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -246,7 +246,7 @@ def check(result, expected): tm.assert_frame_equal(result, expected) dfl = DataFrame(np.random.randn(5, 2), columns=list("AB")) - check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index)) + check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index, columns=[])) check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) check(dfl.iloc[4:6], dfl.iloc[[4]]) diff --git a/pandas/tests/indexing/test_na_indexing.py b/pandas/tests/indexing/test_na_indexing.py index 7e54bbc326880..5364cfe852430 100644 --- a/pandas/tests/indexing/test_na_indexing.py +++ b/pandas/tests/indexing/test_na_indexing.py @@ -34,7 +34,7 @@ def test_series_mask_boolean(values, dtype, mask, indexer_class, frame): if frame: if len(values) == 0: # Otherwise obj is an empty DataFrame with shape (0, 1) - obj = pd.DataFrame(dtype=dtype) + obj = pd.DataFrame(dtype=dtype, index=index) else: obj = obj.to_frame() diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 938056902e745..1ce507db618b9 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -100,12 +100,12 @@ def test_partial_set_empty_frame2(self): tm.assert_frame_equal(df, expected) - df = DataFrame() + df = DataFrame(index=Index([])) df["foo"] = Series(df.index) tm.assert_frame_equal(df, expected) - df = DataFrame() + df = DataFrame(index=Index([])) df["foo"] = df.index tm.assert_frame_equal(df, expected) @@ -135,7 +135,7 @@ def test_partial_set_empty_frame4(self): def test_partial_set_empty_frame5(self): df = DataFrame() - tm.assert_index_equal(df.columns, Index([], dtype=object)) + tm.assert_index_equal(df.columns, pd.RangeIndex(0)) df2 = DataFrame() df2[1] = Series([1], index=["foo"]) df.loc[:, 1] = Series([1], index=["foo"]) @@ -182,7 +182,7 @@ def test_partial_set_empty_frame_row(self): df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] result = y.reindex(columns=["A", "B", "C"]) - expected = DataFrame(columns=["A", "B", "C"], index=Index([], dtype="int64")) + expected = DataFrame(columns=["A", "B", "C"]) expected["A"] = expected["A"].astype("int64") expected["B"] = expected["B"].astype("float64") expected["C"] = expected["C"].astype("float64") diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 822e24b224052..a204132963c94 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1646,7 +1646,7 @@ def test_read_datetime_multiindex(self, request, engine, read_ext): pd.to_datetime("03/01/2020").to_pydatetime(), ], ) - expected = DataFrame([], columns=expected_column_index) + expected = DataFrame([], index=[], columns=expected_column_index) tm.assert_frame_equal(expected, actual) diff --git a/pandas/tests/io/formats/test_info.py b/pandas/tests/io/formats/test_info.py index 33c78baa1eedc..e33e1476af69a 100644 --- a/pandas/tests/io/formats/test_info.py +++ b/pandas/tests/io/formats/test_info.py @@ -37,7 +37,7 @@ def test_info_empty(): expected = textwrap.dedent( """\ <class 'pandas.core.frame.DataFrame'> - Index: 0 entries + RangeIndex: 0 entries Empty DataFrame\n""" ) assert result == expected diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 11ee41ed40ce8..d6999b32e6a81 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -152,8 +152,8 @@ def test_to_latex_empty_tabular(self): \begin{tabular}{l} \toprule Empty DataFrame - Columns: Index([], dtype='object') - Index: Index([], dtype='object') \\ + Columns: RangeIndex(start=0, stop=0, step=1) + Index: RangeIndex(start=0, stop=0, step=1) \\ \bottomrule \end{tabular} """ @@ -207,8 +207,8 @@ def test_to_latex_empty_longtable(self): \begin{longtable}{l} \toprule Empty DataFrame - Columns: Index([], dtype='object') - Index: Index([], dtype='object') \\ + Columns: RangeIndex(start=0, stop=0, step=1) + Index: RangeIndex(start=0, stop=0, step=1) \\ \end{longtable} """ ) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 2f3fc4d0fcba8..4edd08014050e 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -207,12 +207,15 @@ def test_roundtrip_empty(self, orient, convert_axes): empty_frame = DataFrame() data = empty_frame.to_json(orient=orient) result = read_json(data, orient=orient, convert_axes=convert_axes) - expected = empty_frame.copy() - - # TODO: both conditions below are probably bugs - if convert_axes: - expected.index = expected.index.astype(float) - expected.columns = expected.columns.astype(float) + if orient == "split": + idx = pd.Index([], dtype=(float if convert_axes else object)) + expected = DataFrame(index=idx, columns=idx) + elif orient in ["index", "columns"]: + # TODO: this condition is probably a bug + idx = pd.Index([], dtype=(float if convert_axes else object)) + expected = DataFrame(columns=idx) + else: + expected = empty_frame.copy() tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/dtypes/test_empty.py b/pandas/tests/io/parser/dtypes/test_empty.py index ee02af773129a..1f709a3cd8f28 100644 --- a/pandas/tests/io/parser/dtypes/test_empty.py +++ b/pandas/tests/io/parser/dtypes/test_empty.py @@ -26,7 +26,7 @@ def test_dtype_all_columns_empty(all_parsers): parser = all_parsers result = parser.read_csv(StringIO("A,B"), dtype=str) - expected = DataFrame({"A": [], "B": []}, index=[], dtype=str) + expected = DataFrame({"A": [], "B": []}, dtype=str) tm.assert_frame_equal(result, expected) @@ -38,7 +38,6 @@ def test_empty_pass_dtype(all_parsers): expected = DataFrame( {"one": np.empty(0, dtype="u1"), "two": np.empty(0, dtype=object)}, - index=Index([], dtype=object), ) tm.assert_frame_equal(result, expected) @@ -81,7 +80,6 @@ def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers): expected = DataFrame( {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, - index=Index([], dtype=object), ) tm.assert_frame_equal(result, expected) @@ -94,7 +92,6 @@ def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers): expected = DataFrame( {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, - index=Index([], dtype=object), ) tm.assert_frame_equal(result, expected) @@ -106,7 +103,6 @@ def test_empty_with_dup_column_pass_dtype_by_indexes(all_parsers): [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], axis=1, ) - expected.index = expected.index.astype(object) data = "one,one" result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) @@ -133,11 +129,11 @@ def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers): (np.float64, DataFrame(columns=["a", "b"], dtype=np.float64)), ( "category", - DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[]), + DataFrame({"a": Categorical([]), "b": Categorical([])}), ), ( {"a": "category", "b": "category"}, - DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[]), + DataFrame({"a": Categorical([]), "b": Categorical([])}), ), ("datetime64[ns]", DataFrame(columns=["a", "b"], dtype="datetime64[ns]")), ( @@ -147,28 +143,24 @@ def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers): "a": Series([], dtype="timedelta64[ns]"), "b": Series([], dtype="timedelta64[ns]"), }, - index=[], ), ), ( {"a": np.int64, "b": np.int32}, DataFrame( {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, - index=[], ), ), ( {0: np.int64, 1: np.int32}, DataFrame( {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, - index=[], ), ), ( {"a": np.int64, 1: np.int32}, DataFrame( {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, - index=[], ), ), ], diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py index f30aba3db917e..13c4216710f84 100644 --- a/pandas/tests/io/parser/test_index_col.py +++ b/pandas/tests/io/parser/test_index_col.py @@ -251,6 +251,7 @@ def test_index_col_multiindex_columns_no_data(all_parsers): ) expected = DataFrame( [], + index=Index([]), columns=MultiIndex.from_arrays( [["a1", "a2"], ["b1", "b2"]], names=["a0", "b0"] ), diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 1a8149ae41fcb..202e26952f590 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -1249,7 +1249,7 @@ def test_parse_dates_empty_string(all_parsers): ( "a\n04.15.2016", {"parse_dates": True, "index_col": 0}, - DataFrame(index=DatetimeIndex(["2016-04-15"], name="a")), + DataFrame(index=DatetimeIndex(["2016-04-15"], name="a"), columns=[]), ), ( "a,b\n04.15.2016,09.16.2013", @@ -1264,7 +1264,8 @@ def test_parse_dates_empty_string(all_parsers): DataFrame( index=MultiIndex.from_tuples( [(datetime(2016, 4, 15), datetime(2013, 9, 16))], names=["a", "b"] - ) + ), + columns=[], ), ), ], diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index 3e451239dcd40..61c493a2c368f 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -904,7 +904,7 @@ def test_skiprows_with_iterator(): expected_frames = [ DataFrame({"a": [3, 4]}), DataFrame({"a": [5, 7, 8]}, index=[2, 3, 4]), - DataFrame({"a": []}, index=[], dtype="object"), + DataFrame({"a": []}, dtype="object"), ] for i, result in enumerate(df_iter): tm.assert_frame_equal(result, expected_frames[i]) diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py index bbf159845b1d6..032cb961103df 100644 --- a/pandas/tests/io/parser/usecols/test_usecols_basic.py +++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py @@ -241,7 +241,7 @@ def test_usecols_with_integer_like_header(all_parsers, usecols, expected): def test_empty_usecols(all_parsers): data = "a,b,c\n1,2,3\n4,5,6" - expected = DataFrame() + expected = DataFrame(columns=Index([])) parser = all_parsers result = parser.read_csv(StringIO(data), usecols=set()) @@ -276,7 +276,7 @@ def test_np_array_usecols(all_parsers): } ), ), - (lambda x: False, DataFrame()), + (lambda x: False, DataFrame(columns=Index([]))), ], ) def test_callable_usecols(all_parsers, usecols, expected): diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 75683a1d96bfb..ed72b5e251114 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -899,7 +899,7 @@ def test_partition_cols_pathlib(self, tmp_path, pa, df_compat, path_type): def test_empty_dataframe(self, pa): # GH #27339 - df = pd.DataFrame() + df = pd.DataFrame(index=[], columns=[]) check_round_trip(df, pa) def test_write_with_schema(self, pa): @@ -1174,7 +1174,7 @@ def test_error_on_using_partition_cols_and_partition_on( def test_empty_dataframe(self, fp): # GH #27339 - df = pd.DataFrame() + df = pd.DataFrame(index=[], columns=[]) expected = df.copy() expected.index.name = "index" check_round_trip(df, fp, expected=expected) diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index f07a4e3b58e86..3dafe6fe61b35 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -595,5 +595,5 @@ def test_pickle_frame_v124_unpickle_130(): with open(path, "rb") as fd: df = pickle.load(fd) - expected = pd.DataFrame() + expected = pd.DataFrame(index=[], columns=[]) tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index 04f147ee40e62..55e8c4e818ce3 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -90,7 +90,7 @@ def test_raises_on_non_datetimelike_index(): xp = DataFrame() msg = ( "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, " - "but got an instance of 'Index'" + "but got an instance of 'RangeIndex'" ) with pytest.raises(TypeError, match=msg): xp.resample("A").mean() diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py index 68220855b3d7a..0d95d94782ecf 100644 --- a/pandas/tests/reshape/concat/test_empty.py +++ b/pandas/tests/reshape/concat/test_empty.py @@ -4,7 +4,7 @@ import pandas as pd from pandas import ( DataFrame, - Index, + RangeIndex, Series, concat, date_range, @@ -52,7 +52,7 @@ def test_concat_empty_series(self): res = concat([s1, s2], axis=1) exp = DataFrame( {"x": [1, 2, 3], "y": [np.nan, np.nan, np.nan]}, - index=Index([0, 1, 2], dtype="O"), + index=RangeIndex(3), ) tm.assert_frame_equal(res, exp) @@ -70,7 +70,7 @@ def test_concat_empty_series(self): exp = DataFrame( {"x": [1, 2, 3], 0: [np.nan, np.nan, np.nan]}, columns=["x", 0], - index=Index([0, 1, 2], dtype="O"), + index=RangeIndex(3), ) tm.assert_frame_equal(res, exp) @@ -238,7 +238,7 @@ def test_concat_inner_join_empty(self): # GH 15328 df_empty = DataFrame() df_a = DataFrame({"a": [1, 2]}, index=[0, 1], dtype="int64") - df_expected = DataFrame({"a": []}, index=[], dtype="int64") + df_expected = DataFrame({"a": []}, index=RangeIndex(0), dtype="int64") for how, expected in [("inner", df_expected), ("outer", df_a)]: result = concat([df_a, df_empty], axis=1, join=how) diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 4b32022e177e8..e5927aa094193 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -951,7 +951,7 @@ def test_join_empty(left_empty, how, exp): expected = DataFrame({"B": [np.nan], "A": [1], "C": [5]}) expected = expected.set_index("A") elif exp == "empty": - expected = DataFrame(index=Index([]), columns=["B", "C"], dtype="int64") + expected = DataFrame(columns=["B", "C"], dtype="int64") if how != "cross": expected = expected.rename_axis("A") diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index f9d4d4fdc19e7..fc2069c5d1e42 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -154,7 +154,7 @@ def test_merge_inner_join_empty(self): df_empty = DataFrame() df_a = DataFrame({"a": [1, 2]}, index=[0, 1], dtype="int64") result = merge(df_empty, df_a, left_index=True, right_index=True) - expected = DataFrame({"a": []}, index=[], dtype="int64") + expected = DataFrame({"a": []}, dtype="int64") tm.assert_frame_equal(result, expected) def test_merge_common(self, df, df2): @@ -461,11 +461,7 @@ def test_merge_left_empty_right_empty(self, join_type, kwarg): left = DataFrame(columns=["a", "b", "c"]) right = DataFrame(columns=["x", "y", "z"]) - exp_in = DataFrame( - columns=["a", "b", "c", "x", "y", "z"], - index=pd.Index([], dtype=object), - dtype=object, - ) + exp_in = DataFrame(columns=["a", "b", "c", "x", "y", "z"], dtype=object) result = merge(left, right, how=join_type, **kwarg) tm.assert_frame_equal(result, exp_in) @@ -487,8 +483,6 @@ def test_merge_left_empty_right_notempty(self): columns=["a", "b", "c", "x", "y", "z"], ) exp_in = exp_out[0:0] # make empty DataFrame keeping dtype - # result will have object dtype - exp_in.index = exp_in.index.astype(object) def check1(exp, kwarg): result = merge(left, right, how="inner", **kwarg) @@ -1672,7 +1666,10 @@ def test_merge_EA_dtype(self, any_numeric_ea_dtype, how, expected_data): d1 = DataFrame([(1,)], columns=["id"], dtype=any_numeric_ea_dtype) d2 = DataFrame([(2,)], columns=["id"], dtype=any_numeric_ea_dtype) result = merge(d1, d2, how=how) - expected = DataFrame(expected_data, columns=["id"], dtype=any_numeric_ea_dtype) + exp_index = RangeIndex(len(expected_data)) + expected = DataFrame( + expected_data, index=exp_index, columns=["id"], dtype=any_numeric_ea_dtype + ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -1689,7 +1686,10 @@ def test_merge_string_dtype(self, how, expected_data, any_string_dtype): d1 = DataFrame([("a",)], columns=["id"], dtype=any_string_dtype) d2 = DataFrame([("b",)], columns=["id"], dtype=any_string_dtype) result = merge(d1, d2, how=how) - expected = DataFrame(expected_data, columns=["id"], dtype=any_string_dtype) + exp_idx = RangeIndex(len(expected_data)) + expected = DataFrame( + expected_data, index=exp_idx, columns=["id"], dtype=any_string_dtype + ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 9c1a07dd3cde4..9a72a8dadf8d0 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1934,7 +1934,7 @@ def test_pivot_margins_name_unicode(self): frame, index=["foo"], aggfunc=len, margins=True, margins_name=greek ) index = Index([1, 2, 3, greek], dtype="object", name="foo") - expected = DataFrame(index=index) + expected = DataFrame(index=index, columns=[]) tm.assert_frame_equal(table, expected) def test_pivot_string_as_func(self): @@ -2107,8 +2107,8 @@ def test_pivot_table_empty_aggfunc(self, margins): result = df.pivot_table( index="A", columns="D", values="id", aggfunc=np.size, margins=margins ) - expected = DataFrame(index=Index([], dtype="int64", name="A")) - expected.columns.name = "D" + exp_cols = Index([], name="D") + expected = DataFrame(index=Index([], dtype="int64", name="A"), columns=exp_cols) tm.assert_frame_equal(result, expected) def test_pivot_table_no_column_raises(self): @@ -2342,7 +2342,7 @@ def test_pivot_duplicates(self): def test_pivot_empty(self): df = DataFrame(columns=["a", "b", "c"]) result = df.pivot(index="a", columns="b", values="c") - expected = DataFrame() + expected = DataFrame(index=[], columns=[]) tm.assert_frame_equal(result, expected, check_names=False) def test_pivot_integer_bug(self): diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py index 60ada18410415..698d66ebe7c29 100644 --- a/pandas/tests/series/methods/test_reindex.py +++ b/pandas/tests/series/methods/test_reindex.py @@ -97,7 +97,7 @@ def test_reindex_with_datetimes(): def test_reindex_corner(datetime_series): # (don't forget to fix this) I think it's fixed - empty = Series(dtype=object) + empty = Series(index=[]) empty.reindex(datetime_series.index, method="pad") # it works # corner case: pad empty series diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 8b18550dce746..054be774c2308 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -92,15 +92,15 @@ def test_unparseable_strings_with_dt64_dtype(self): # passed. (lambda idx: Series(index=idx), True), (lambda idx: Series(None, index=idx), True), - (lambda idx: Series({}, index=idx), True), - (lambda idx: Series((), index=idx), False), # creates a RangeIndex - (lambda idx: Series([], index=idx), False), # creates a RangeIndex - (lambda idx: Series((_ for _ in []), index=idx), False), # RangeIndex + (lambda idx: Series({}, index=idx), False), # creates an Index[object] + (lambda idx: Series((), index=idx), True), + (lambda idx: Series([], index=idx), True), + (lambda idx: Series((_ for _ in []), index=idx), True), (lambda idx: Series(data=None, index=idx), True), - (lambda idx: Series(data={}, index=idx), True), - (lambda idx: Series(data=(), index=idx), False), # creates a RangeIndex - (lambda idx: Series(data=[], index=idx), False), # creates a RangeIndex - (lambda idx: Series(data=(_ for _ in []), index=idx), False), # RangeIndex + (lambda idx: Series(data={}, index=idx), False), # creates an Index[object] + (lambda idx: Series(data=(), index=idx), True), + (lambda idx: Series(data=[], index=idx), True), + (lambda idx: Series(data=(_ for _ in []), index=idx), True), ], ) @pytest.mark.parametrize("empty_index", [None, []]) diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index beda123facb26..4385f71dc653f 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -128,7 +128,7 @@ def test_empty_str_methods(any_string_dtype): DataFrame(columns=[0, 1], dtype=any_string_dtype), empty.str.extract("()()", expand=False), ) - tm.assert_frame_equal(empty_df, empty.str.get_dummies()) + tm.assert_frame_equal(empty_df.set_axis([], axis=1), empty.str.get_dummies()) tm.assert_series_equal(empty_str, empty_str.str.join("")) tm.assert_series_equal(empty_int, empty.str.len()) tm.assert_series_equal(empty_object, empty_str.str.findall("a")) diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index 8417c6dd8419c..d30e3d7afcf19 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -453,9 +453,7 @@ def test_moment_functions_zero_length_pairwise(f): df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) df2["a"] = df2["a"].astype("float64") - df1_expected = DataFrame( - index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]) - ) + df1_expected = DataFrame(index=MultiIndex.from_product([df1.index, df1.columns])) df2_expected = DataFrame( index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]), columns=Index(["a"], name="foo"), diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py index 04132ced044fc..315b3003f716b 100644 --- a/pandas/tests/window/test_pairwise.py +++ b/pandas/tests/window/test_pairwise.py @@ -197,9 +197,7 @@ def test_moment_functions_zero_length_pairwise(f): df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) df2["a"] = df2["a"].astype("float64") - df1_expected = DataFrame( - index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]) - ) + df1_expected = DataFrame(index=MultiIndex.from_product([df1.index, df1.columns])) df2_expected = DataFrame( index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]), columns=Index(["a"], name="foo"),
- [x] closes #40077 - [x] closes #49572 I've looked into #49572 and it seems that the fix is reasonable simple, see included code. In short, currently if the user hasn't supplied `index` or `columns` values, then the index/columns is a `RangeIndex` if the data has lenght > 0, while they're `Index[object]` if the length is 0. After this PR, a `RangeIndex` will be used in both cases. This will simplify type inference etc. testing etc. However, this fix requires changes to a lot of tests (>500), of which I've fixed about 100 (not included in this version of the PR), so it's quite a lot of work to get this fixed up. Test fixing so far seems to be only a matter of ensuring that various empty dataframes/Series have `RangeIndex` rather than a `Index[object]`, so relatively simple, but also tedious work. I didn't get much response to #49572 from the core devs, so before I spend more time on this rather big item, could you guys chime in on if you agree that this a good thing to do? IMO having the same index dtypes for series/frame of length 0 and >0 will conceptually simplify pandas and decrease the amount of surprises that users will encounter. I've included the code that fixes the issue in this PR, as mentioned, and ATM this PR fails, because I haven't fixed the tests, but I will get them fixed if I get positive response. If you can respond either here or in #49572, I'll of course read them both.
https://api.github.com/repos/pandas-dev/pandas/pulls/49637
2022-11-11T08:40:09Z
2022-12-07T17:05:35Z
2022-12-07T17:05:35Z
2023-04-04T16:06:50Z
Backport PR #49614 on branch 1.5.x (CI: Updating website sync to new server)
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml index 48a08d4febbaf..1db8fb9a70254 100644 --- a/.github/workflows/docbuild-and-upload.yml +++ b/.github/workflows/docbuild-and-upload.yml @@ -64,22 +64,22 @@ jobs: mkdir -m 700 -p ~/.ssh echo "${{ secrets.server_ssh_key }}" > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa - echo "${{ secrets.server_ip }} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBE1Kkopomm7FHG5enATf7SgnpICZ4W2bw+Ho+afqin+w7sMcrsa0je7sbztFAV8YchDkiBKnWTG4cRT+KZgZCaY=" > ~/.ssh/known_hosts + echo "${{ secrets.server_ip }} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFjYkJBk7sos+r7yATODogQc3jUdW1aascGpyOD4bohj8dWjzwLJv/OJ/fyOQ5lmj81WKDk67tGtqNJYGL9acII=" > ~/.ssh/known_hosts if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) - name: Copy cheatsheets into site directory run: cp doc/cheatsheet/Pandas_Cheat_Sheet* web/build/ - name: Upload web - run: rsync -az --delete --exclude='pandas-docs' --exclude='docs' web/build/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas + run: rsync -az --delete --exclude='pandas-docs' --exclude='docs' web/build/ web@${{ secrets.server_ip }}:/var/www/html if: github.event_name == 'push' && github.ref == 'refs/heads/main' - name: Upload dev docs - run: rsync -az --delete doc/build/html/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas/pandas-docs/dev + run: rsync -az --delete doc/build/html/ web@${{ secrets.server_ip }}:/var/www/html/pandas-docs/dev if: github.event_name == 'push' && github.ref == 'refs/heads/main' - name: Upload prod docs - run: rsync -az --delete doc/build/html/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas/pandas-docs/version/${GITHUB_REF_NAME:1} + run: rsync -az --delete doc/build/html/ web@${{ secrets.server_ip }}:/var/www/html/pandas-docs/version/${GITHUB_REF_NAME:1} if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') - name: Move docs into site directory
Backport PR #49614: CI: Updating website sync to new server
https://api.github.com/repos/pandas-dev/pandas/pulls/49634
2022-11-11T03:07:53Z
2022-11-11T11:41:03Z
2022-11-11T11:41:03Z
2022-11-11T11:41:04Z
DEPR: Remove method and tolerance in Index.get_loc, bump xarray
diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml index 512aa13c6899a..de7e793c46d19 100644 --- a/ci/deps/actions-38-minimum_versions.yaml +++ b/ci/deps/actions-38-minimum_versions.yaml @@ -54,7 +54,7 @@ dependencies: - sqlalchemy=1.4.16 - tabulate=0.8.9 - tzdata=2022a - - xarray=0.19.0 + - xarray=0.21.0 - xlrd=2.0.1 - xlsxwriter=1.4.3 - zstandard=0.15.2 diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 8e8f61c1d503f..68065c77f7881 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -333,7 +333,7 @@ Installable with ``pip install "pandas[computation]"``. Dependency Minimum Version pip extra Notes ========================= ================== =============== ============================================================= SciPy 1.7.1 computation Miscellaneous statistical functions -xarray 0.19.0 computation pandas-like API for N-dimensional data +xarray 0.21.0 computation pandas-like API for N-dimensional data ========================= ================== =============== ============================================================= Excel files diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 0ecdde89d9013..f34dd667fdb70 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -338,6 +338,8 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+---------+ | fastparquet | 0.6.3 | X | +-----------------+-----------------+---------+ +| xarray | 0.21.0 | X | ++-----------------+-----------------+---------+ See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. @@ -520,6 +522,7 @@ Removal of prior version deprecations/changes - Removed the ``closed`` argument in :meth:`date_range` and :meth:`bdate_range` in favor of ``inclusive`` argument (:issue:`40245`) - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) - Removed the ``truediv`` keyword from :func:`eval` (:issue:`29812`) +- Removed the ``method`` and ``tolerance`` arguments in :meth:`Index.get_loc`. Use ``index.get_indexer([label], method=..., tolerance=...)`` instead (:issue:`42269`) - Removed the ``pandas.datetime`` submodule (:issue:`30489`) - Removed the ``pandas.np`` submodule (:issue:`30296`) - Removed ``pandas.util.testing`` in favor of ``pandas.testing`` (:issue:`30745`) diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index abad188f06720..9bd4b384fadb0 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -41,7 +41,7 @@ "sqlalchemy": "1.4.16", "tables": "3.6.1", "tabulate": "0.8.9", - "xarray": "0.19.0", + "xarray": "0.21.0", "xlrd": "2.0.1", "xlsxwriter": "1.4.3", "zstandard": "0.15.2", diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index ce06b6bc01581..b08da77082c53 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3429,27 +3429,13 @@ def _convert_can_do_setop(self, other) -> tuple[Index, Hashable]: # -------------------------------------------------------------------- # Indexing Methods - def get_loc(self, key, method=None, tolerance=None): + def get_loc(self, key): """ Get integer location, slice or boolean mask for requested label. Parameters ---------- key : label - method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional - * default: exact matches only. - * pad / ffill: find the PREVIOUS index value if no exact match. - * backfill / bfill: use NEXT index value if no exact match - * nearest: use the NEAREST index value if no exact match. Tied - distances are broken by preferring the larger index value. - - .. deprecated:: 1.4 - Use index.get_indexer([item], method=...) instead. - - tolerance : int or float, optional - Maximum distance from index value for inexact matches. The value of - the index at the matching location must satisfy the equation - ``abs(index[loc] - key) <= tolerance``. Returns ------- @@ -3469,46 +3455,17 @@ def get_loc(self, key, method=None, tolerance=None): >>> non_monotonic_index.get_loc('b') array([False, True, False, True]) """ - if method is None: - if tolerance is not None: - raise ValueError( - "tolerance argument only valid if using pad, " - "backfill or nearest lookups" - ) - casted_key = self._maybe_cast_indexer(key) - try: - return self._engine.get_loc(casted_key) - except KeyError as err: - raise KeyError(key) from err - except TypeError: - # If we have a listlike key, _check_indexing_error will raise - # InvalidIndexError. Otherwise we fall through and re-raise - # the TypeError. - self._check_indexing_error(key) - raise - - # GH#42269 - warnings.warn( - f"Passing method to {type(self).__name__}.get_loc is deprecated " - "and will raise in a future version. Use " - "index.get_indexer([item], method=...) instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - - if is_scalar(key) and isna(key) and not self.hasnans: - raise KeyError(key) - - if tolerance is not None: - tolerance = self._convert_tolerance(tolerance, np.asarray(key)) - - indexer = self.get_indexer([key], method=method, tolerance=tolerance) - if indexer.ndim > 1 or indexer.size > 1: - raise TypeError("get_loc requires scalar valued input") - loc = indexer.item() - if loc == -1: - raise KeyError(key) - return loc + casted_key = self._maybe_cast_indexer(key) + try: + return self._engine.get_loc(casted_key) + except KeyError as err: + raise KeyError(key) from err + except TypeError: + # If we have a listlike key, _check_indexing_error will raise + # InvalidIndexError. Otherwise we fall through and re-raise + # the TypeError. + self._check_indexing_error(key) + raise _index_shared_docs[ "get_indexer" diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index c30323338e676..784b5c8b24e32 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -556,7 +556,7 @@ def _disallow_mismatched_indexing(self, key) -> None: except TypeError as err: raise KeyError(key) from err - def get_loc(self, key, method=None, tolerance=None): + def get_loc(self, key): """ Get integer location for requested label @@ -587,8 +587,7 @@ def get_loc(self, key, method=None, tolerance=None): try: return self._partial_date_slice(reso, parsed) except KeyError as err: - if method is None: - raise KeyError(key) from err + raise KeyError(key) from err key = parsed @@ -599,10 +598,6 @@ def get_loc(self, key, method=None, tolerance=None): ) elif isinstance(key, dt.time): - if method is not None: - raise NotImplementedError( - "cannot yet lookup inexact labels when key is a time object" - ) return self.indexer_at_time(key) else: @@ -610,7 +605,7 @@ def get_loc(self, key, method=None, tolerance=None): raise KeyError(key) try: - return Index.get_loc(self, key, method, tolerance) + return Index.get_loc(self, key) except KeyError as err: raise KeyError(orig_key) from err diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 012a92793acf9..8776d78ae6d9a 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2730,7 +2730,7 @@ def _get_loc_single_level_index(self, level_index: Index, key: Hashable) -> int: else: return level_index.get_loc(key) - def get_loc(self, key, method=None): + def get_loc(self, key): """ Get location for a label or a tuple of labels. @@ -2740,7 +2740,6 @@ def get_loc(self, key, method=None): Parameters ---------- key : label or tuple of labels (one for each level) - method : None Returns ------- @@ -2772,12 +2771,6 @@ def get_loc(self, key, method=None): >>> mi.get_loc(('b', 'e')) 1 """ - if method is not None: - raise NotImplementedError( - "only the default get_loc method is " - "currently supported for MultiIndex" - ) - self._check_indexing_error(key) def _maybe_to_slice(loc): diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index ef47cb9bf1070..877bb2844e8c9 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -375,7 +375,7 @@ def _convert_tolerance(self, tolerance, target): return tolerance - def get_loc(self, key, method=None, tolerance=None): + def get_loc(self, key): """ Get integer location for requested label. @@ -421,10 +421,8 @@ def get_loc(self, key, method=None, tolerance=None): # the reso < self._resolution_obj case goes # through _get_string_slice key = self._cast_partial_indexing_scalar(parsed) - elif method is None: - raise KeyError(key) else: - key = self._cast_partial_indexing_scalar(parsed) + raise KeyError(key) elif isinstance(key, Period): self._disallow_mismatched_indexing(key) @@ -437,7 +435,7 @@ def get_loc(self, key, method=None, tolerance=None): raise KeyError(key) try: - return Index.get_loc(self, key, method, tolerance) + return Index.get_loc(self, key) except KeyError as err: raise KeyError(orig_key) from err diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index a2281c6fd9540..1937cd4254790 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -328,17 +328,15 @@ def inferred_type(self) -> str: # Indexing Methods @doc(Int64Index.get_loc) - def get_loc(self, key, method=None, tolerance=None): - if method is None and tolerance is None: - if is_integer(key) or (is_float(key) and key.is_integer()): - new_key = int(key) - try: - return self._range.index(new_key) - except ValueError as err: - raise KeyError(key) from err - self._check_indexing_error(key) - raise KeyError(key) - return super().get_loc(key, method=method, tolerance=tolerance) + def get_loc(self, key): + if is_integer(key) or (is_float(key) and key.is_integer()): + new_key = int(key) + try: + return self._range.index(new_key) + except ValueError as err: + raise KeyError(key) from err + self._check_indexing_error(key) + raise KeyError(key) def _get_indexer( self, diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 82ac2bd139b1f..54a9152670cab 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -174,7 +174,7 @@ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: # ------------------------------------------------------------------- # Indexing Methods - def get_loc(self, key, method=None, tolerance=None): + def get_loc(self, key): """ Get integer location for requested label @@ -189,7 +189,7 @@ def get_loc(self, key, method=None, tolerance=None): except TypeError as err: raise KeyError(key) from err - return Index.get_loc(self, key, method, tolerance) + return Index.get_loc(self, key) def _parse_with_reso(self, label: str): # the "with_reso" is a no-op for TimedeltaIndex diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 887766dd3fc29..04d1d8204a346 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -8,8 +8,6 @@ import numpy as np import pytest -from pandas.errors import InvalidIndexError - import pandas as pd from pandas import ( DatetimeIndex, @@ -405,75 +403,6 @@ def test_get_loc_key_unit_mismatch_not_castable(self): assert key not in dti - @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"]) - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") - def test_get_loc_method_exact_match(self, method): - idx = date_range("2000-01-01", periods=3) - assert idx.get_loc(idx[1], method) == 1 - assert idx.get_loc(idx[1].to_pydatetime(), method) == 1 - assert idx.get_loc(str(idx[1]), method) == 1 - - if method is not None: - assert idx.get_loc(idx[1], method, tolerance=pd.Timedelta("0 days")) == 1 - - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") - def test_get_loc(self): - idx = date_range("2000-01-01", periods=3) - - assert idx.get_loc("2000-01-01", method="nearest") == 0 - assert idx.get_loc("2000-01-01T12", method="nearest") == 1 - - assert idx.get_loc("2000-01-01T12", method="nearest", tolerance="1 day") == 1 - assert ( - idx.get_loc("2000-01-01T12", method="nearest", tolerance=pd.Timedelta("1D")) - == 1 - ) - assert ( - idx.get_loc( - "2000-01-01T12", method="nearest", tolerance=np.timedelta64(1, "D") - ) - == 1 - ) - assert ( - idx.get_loc("2000-01-01T12", method="nearest", tolerance=timedelta(1)) == 1 - ) - with pytest.raises(ValueError, match="unit abbreviation w/o a number"): - idx.get_loc("2000-01-01T12", method="nearest", tolerance="foo") - with pytest.raises(KeyError, match="'2000-01-01T03'"): - idx.get_loc("2000-01-01T03", method="nearest", tolerance="2 hours") - with pytest.raises( - ValueError, match="tolerance size must match target index size" - ): - idx.get_loc( - "2000-01-01", - method="nearest", - tolerance=[ - pd.Timedelta("1day").to_timedelta64(), - pd.Timedelta("1day").to_timedelta64(), - ], - ) - - assert idx.get_loc("2000", method="nearest") == slice(0, 3) - assert idx.get_loc("2000-01", method="nearest") == slice(0, 3) - - assert idx.get_loc("1999", method="nearest") == 0 - assert idx.get_loc("2001", method="nearest") == 2 - - with pytest.raises(KeyError, match="'1999'"): - idx.get_loc("1999", method="pad") - with pytest.raises(KeyError, match="'2001'"): - idx.get_loc("2001", method="backfill") - - with pytest.raises(KeyError, match="'foobar'"): - idx.get_loc("foobar") - with pytest.raises(InvalidIndexError, match=r"slice\(None, 2, None\)"): - idx.get_loc(slice(2)) - - idx = DatetimeIndex(["2000-01-01", "2000-01-04"]) - assert idx.get_loc("2000-01-02", method="nearest") == 0 - assert idx.get_loc("2000-01-03", method="nearest") == 1 - assert idx.get_loc("2000-01", method="nearest") == slice(0, 2) - def test_get_loc_time_obj(self): # time indexing idx = date_range("2000-01-01", periods=24, freq="H") @@ -486,11 +415,6 @@ def test_get_loc_time_obj(self): expected = np.array([]) tm.assert_numpy_array_equal(result, expected, check_dtype=False) - msg = "cannot yet lookup inexact labels when key is a time object" - with pytest.raises(NotImplementedError, match=msg): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - idx.get_loc(time(12, 30), method="pad") - def test_get_loc_time_obj2(self): # GH#8667 @@ -525,18 +449,6 @@ def test_get_loc_time_nat(self): expected = np.array([], dtype=np.intp) tm.assert_numpy_array_equal(loc, expected) - def test_get_loc_tz_aware(self): - # https://github.com/pandas-dev/pandas/issues/32140 - dti = date_range( - Timestamp("2019-12-12 00:00:00", tz="US/Eastern"), - Timestamp("2019-12-13 00:00:00", tz="US/Eastern"), - freq="5s", - ) - key = Timestamp("2019-12-12 10:19:25", tz="US/Eastern") - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - result = dti.get_loc(key, method="nearest") - assert result == 7433 - def test_get_loc_nat(self): # GH#20464 index = DatetimeIndex(["1/3/2000", "NaT"]) diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 4c879c8ff5736..31c5ab333ecfa 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -570,10 +570,6 @@ def test_get_loc(self, idx): with pytest.raises(KeyError, match=r"^'quux'$"): idx.get_loc("quux") - msg = "only the default get_loc method is currently supported for MultiIndex" - with pytest.raises(NotImplementedError, match=msg): - idx.get_loc("foo", method="nearest") - # 3 levels index = MultiIndex( levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))], diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py index 9811cd3ac0211..5c4596b0d9503 100644 --- a/pandas/tests/indexes/numeric/test_indexing.py +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -20,99 +20,27 @@ def index_large(): class TestGetLoc: - @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"]) - def test_get_loc(self, method): + def test_get_loc(self): index = Index([0, 1, 2]) - warn = None if method is None else FutureWarning + assert index.get_loc(1) == 1 - with tm.assert_produces_warning(warn, match="deprecated"): - assert index.get_loc(1, method=method) == 1 - - if method: - with tm.assert_produces_warning(warn, match="deprecated"): - assert index.get_loc(1, method=method, tolerance=0) == 1 - - @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"]) - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") - def test_get_loc_raises_bad_label(self, method): - index = Index([0, 1, 2]) - if method: - msg = "not supported between" - err = TypeError - else: - msg = r"\[1, 2\]" - err = InvalidIndexError - - with pytest.raises(err, match=msg): - index.get_loc([1, 2], method=method) - - @pytest.mark.parametrize( - "method,loc", [("pad", 1), ("backfill", 2), ("nearest", 1)] - ) - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") - def test_get_loc_tolerance(self, method, loc): - index = Index([0, 1, 2]) - assert index.get_loc(1.1, method) == loc - assert index.get_loc(1.1, method, tolerance=1) == loc - - @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) - def test_get_loc_outside_tolerance_raises(self, method): - index = Index([0, 1, 2]) - with pytest.raises(KeyError, match="1.1"): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - index.get_loc(1.1, method, tolerance=0.05) - - def test_get_loc_bad_tolerance_raises(self): - index = Index([0, 1, 2]) - with pytest.raises(ValueError, match="must be numeric"): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - index.get_loc(1.1, "nearest", tolerance="invalid") - - def test_get_loc_tolerance_no_method_raises(self): + def test_get_loc_raises_bad_label(self): index = Index([0, 1, 2]) - with pytest.raises(ValueError, match="tolerance .* valid if"): - index.get_loc(1.1, tolerance=1) - - def test_get_loc_raises_missized_tolerance(self): - index = Index([0, 1, 2]) - with pytest.raises(ValueError, match="tolerance size must match"): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - index.get_loc(1.1, "nearest", tolerance=[1, 1]) + with pytest.raises(InvalidIndexError, match=r"\[1, 2\]"): + index.get_loc([1, 2]) - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") def test_get_loc_float64(self): idx = Index([0.0, 1.0, 2.0], dtype=np.float64) - for method in [None, "pad", "backfill", "nearest"]: - assert idx.get_loc(1, method) == 1 - if method is not None: - assert idx.get_loc(1, method, tolerance=0) == 1 - - for method, loc in [("pad", 1), ("backfill", 2), ("nearest", 1)]: - assert idx.get_loc(1.1, method) == loc - assert idx.get_loc(1.1, method, tolerance=0.9) == loc with pytest.raises(KeyError, match="^'foo'$"): idx.get_loc("foo") with pytest.raises(KeyError, match=r"^1\.5$"): idx.get_loc(1.5) - with pytest.raises(KeyError, match=r"^1\.5$"): - idx.get_loc(1.5, method="pad", tolerance=0.1) with pytest.raises(KeyError, match="^True$"): idx.get_loc(True) with pytest.raises(KeyError, match="^False$"): idx.get_loc(False) - with pytest.raises(ValueError, match="must be numeric"): - idx.get_loc(1.4, method="nearest", tolerance="foo") - - with pytest.raises(ValueError, match="must contain numeric elements"): - idx.get_loc(1.4, method="nearest", tolerance=np.array(["foo"])) - - with pytest.raises( - ValueError, match="tolerance size must match target index size" - ): - idx.get_loc(1.4, method="nearest", tolerance=np.array([1, 2])) - def test_get_loc_na(self): idx = Index([np.nan, 1, 2], dtype=np.float64) assert idx.get_loc(1) == 1 @@ -145,13 +73,11 @@ def test_get_loc_missing_nan(self): idx.get_loc([np.nan]) @pytest.mark.parametrize("vals", [[1], [1.0], [Timestamp("2019-12-31")], ["test"]]) - @pytest.mark.parametrize("method", ["nearest", "pad", "backfill"]) - def test_get_loc_float_index_nan_with_method(self, vals, method): + def test_get_loc_float_index_nan_with_method(self, vals): # GH#39382 idx = Index(vals) with pytest.raises(KeyError, match="nan"): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - idx.get_loc(np.nan, method=method) + idx.get_loc(np.nan) @pytest.mark.parametrize("dtype", ["f8", "i8", "u8"]) def test_get_loc_numericindex_none_raises(self, dtype): diff --git a/pandas/tests/indexes/object/test_indexing.py b/pandas/tests/indexes/object/test_indexing.py index 38bd96921b991..a33173dc83569 100644 --- a/pandas/tests/indexes/object/test_indexing.py +++ b/pandas/tests/indexes/object/test_indexing.py @@ -10,20 +10,6 @@ import pandas._testing as tm -class TestGetLoc: - def test_get_loc_raises_object_nearest(self): - index = Index(["a", "c"]) - with pytest.raises(TypeError, match="unsupported operand type"): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - index.get_loc("a", method="nearest") - - def test_get_loc_raises_object_tolerance(self): - index = Index(["a", "c"]) - with pytest.raises(TypeError, match="unsupported operand type"): - with tm.assert_produces_warning(FutureWarning, match="deprecated"): - index.get_loc("a", method="pad", tolerance="invalid") - - class TestGetIndexer: @pytest.mark.parametrize( "method,expected", diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 58b77ce50293d..6cf942ad3d5d5 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -1,7 +1,4 @@ -from datetime import ( - datetime, - timedelta, -) +from datetime import datetime import re import numpy as np @@ -206,38 +203,42 @@ def test_getitem_seconds(self): for d in ["2013/01/01", "2013/01", "2013"]: tm.assert_series_equal(ser[d], ser) - def test_getitem_day(self): + @pytest.mark.parametrize( + "idx_range", + [ + date_range, + period_range, + ], + ) + def test_getitem_day(self, idx_range): # GH#6716 # Confirm DatetimeIndex and PeriodIndex works identically - didx = date_range(start="2013/01/01", freq="D", periods=400) - pidx = period_range(start="2013/01/01", freq="D", periods=400) - - for idx in [didx, pidx]: - # getitem against index should raise ValueError - values = [ - "2014", - "2013/02", - "2013/01/02", - "2013/02/01 9H", - "2013/02/01 09:00", - ] - for val in values: + # getitem against index should raise ValueError + idx = idx_range(start="2013/01/01", freq="D", periods=400) + values = [ + "2014", + "2013/02", + "2013/01/02", + "2013/02/01 9H", + "2013/02/01 09:00", + ] + for val in values: - # GH7116 - # these show deprecations as we are trying - # to slice with non-integer indexers - with pytest.raises(IndexError, match="only integers, slices"): - idx[val] + # GH7116 + # these show deprecations as we are trying + # to slice with non-integer indexers + with pytest.raises(IndexError, match="only integers, slices"): + idx[val] - ser = Series(np.random.rand(len(idx)), index=idx) - tm.assert_series_equal(ser["2013/01"], ser[0:31]) - tm.assert_series_equal(ser["2013/02"], ser[31:59]) - tm.assert_series_equal(ser["2014"], ser[365:]) + ser = Series(np.random.rand(len(idx)), index=idx) + tm.assert_series_equal(ser["2013/01"], ser[0:31]) + tm.assert_series_equal(ser["2013/02"], ser[31:59]) + tm.assert_series_equal(ser["2014"], ser[365:]) - invalid = ["2013/02/01 9H", "2013/02/01 09:00"] - for val in invalid: - with pytest.raises(KeyError, match=val): - ser[val] + invalid = ["2013/02/01 9H", "2013/02/01 09:00"] + for val in invalid: + with pytest.raises(KeyError, match=val): + ser[val] class TestGetLoc: @@ -331,62 +332,6 @@ def test_get_loc_integer(self): with pytest.raises(KeyError, match="46"): pi2.get_loc(46) - # TODO: This method came from test_period; de-dup with version above - @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"]) - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") - def test_get_loc_method(self, method): - idx = period_range("2000-01-01", periods=3) - - assert idx.get_loc(idx[1], method) == 1 - assert idx.get_loc(idx[1].to_timestamp(), method) == 1 - assert idx.get_loc(idx[1].to_timestamp().to_pydatetime(), method) == 1 - assert idx.get_loc(str(idx[1]), method) == 1 - - key = idx[1].asfreq("H", how="start") - with pytest.raises(KeyError, match=str(key)): - idx.get_loc(key, method=method) - - # TODO: This method came from test_period; de-dup with version above - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") - def test_get_loc3(self): - - idx = period_range("2000-01-01", periods=5)[::2] - assert idx.get_loc("2000-01-02T12", method="nearest", tolerance="1 day") == 1 - assert ( - idx.get_loc("2000-01-02T12", method="nearest", tolerance=Timedelta("1D")) - == 1 - ) - assert ( - idx.get_loc( - "2000-01-02T12", method="nearest", tolerance=np.timedelta64(1, "D") - ) - == 1 - ) - assert ( - idx.get_loc("2000-01-02T12", method="nearest", tolerance=timedelta(1)) == 1 - ) - - msg = "unit abbreviation w/o a number" - with pytest.raises(ValueError, match=msg): - idx.get_loc("2000-01-10", method="nearest", tolerance="foo") - - msg = "Input has different freq=None from PeriodArray\\(freq=D\\)" - with pytest.raises(ValueError, match=msg): - idx.get_loc("2000-01-10", method="nearest", tolerance="1 hour") - with pytest.raises(KeyError, match=r"^'2000-01-10'$"): - idx.get_loc("2000-01-10", method="nearest", tolerance="1 day") - with pytest.raises( - ValueError, match="list-like tolerance size must match target index size" - ): - idx.get_loc( - "2000-01-10", - method="nearest", - tolerance=[ - Timedelta("1 day").to_timedelta64(), - Timedelta("1 day").to_timedelta64(), - ], - ) - def test_get_loc_invalid_string_raises_keyerror(self): # GH#34240 pi = period_range("2000", periods=3, name="A") diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index 12aece23738ec..cc166f9f32a34 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -1,7 +1,4 @@ -from datetime import ( - datetime, - timedelta, -) +from datetime import datetime import re import numpy as np @@ -91,35 +88,9 @@ def test_get_loc_key_unit_mismatch_not_castable(self): assert key not in tdi - @pytest.mark.filterwarnings("ignore:Passing method:FutureWarning") def test_get_loc(self): idx = to_timedelta(["0 days", "1 days", "2 days"]) - for method in [None, "pad", "backfill", "nearest"]: - assert idx.get_loc(idx[1], method) == 1 - assert idx.get_loc(idx[1].to_pytimedelta(), method) == 1 - assert idx.get_loc(str(idx[1]), method) == 1 - - assert idx.get_loc(idx[1], "pad", tolerance=Timedelta(0)) == 1 - assert idx.get_loc(idx[1], "pad", tolerance=np.timedelta64(0, "s")) == 1 - assert idx.get_loc(idx[1], "pad", tolerance=timedelta(0)) == 1 - - with pytest.raises(ValueError, match="unit abbreviation w/o a number"): - idx.get_loc(idx[1], method="nearest", tolerance="foo") - - with pytest.raises(ValueError, match="tolerance size must match"): - idx.get_loc( - idx[1], - method="nearest", - tolerance=[ - Timedelta(0).to_timedelta64(), - Timedelta(0).to_timedelta64(), - ], - ) - - for method, loc in [("pad", 1), ("backfill", 2), ("nearest", 1)]: - assert idx.get_loc("1 day 1 hour", method) == loc - # GH 16909 assert idx.get_loc(idx[1].to_timedelta64()) == 1 diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index ab001d0b5a881..fa32c558eeb70 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -118,7 +118,7 @@ def test_xarray(df): @td.skip_if_no("cftime") -@td.skip_if_no("xarray", "0.10.4") +@td.skip_if_no("xarray", "0.21.0") def test_xarray_cftimeindex_nearest(): # https://github.com/pydata/xarray/issues/3751 import cftime @@ -126,10 +126,7 @@ def test_xarray_cftimeindex_nearest(): times = xarray.cftime_range("0001", periods=2) key = cftime.DatetimeGregorian(2000, 1, 1) - with tm.assert_produces_warning( - FutureWarning, match="deprecated", check_stacklevel=False - ): - result = times.get_loc(key, method="nearest") + result = times.get_indexer([key], method="nearest") expected = 1 assert result == expected diff --git a/pyproject.toml b/pyproject.toml index b649dc0c339f4..18289faefd74a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,7 @@ matplotlib = "pandas:plotting._matplotlib" test = ['hypothesis>=5.5.3', 'pytest>=6.0', 'pytest-xdist>=1.31', 'pytest-asyncio>=0.17.0'] performance = ['bottleneck>=1.3.2', 'numba>=0.53.1', 'numexpr>=2.7.1'] timezone = ['tzdata>=2022.1'] -computation = ['scipy>=1.7.1', 'xarray>=0.19.0'] +computation = ['scipy>=1.7.1', 'xarray>=0.21.0'] fss = ['fsspec>=2021.07.0'] aws = ['s3fs>=2021.08.0'] gcp = ['gcsfs>=2021.07.0', 'pandas-gbq>=0.15.0'] @@ -113,7 +113,7 @@ all = ['beautifulsoup4>=4.9.3', 'tables>=3.6.1', 'tabulate>=0.8.9', 'tzdata>=2022.1', - 'xarray>=0.19.0', + 'xarray>=0.21.0', 'xlrd>=2.0.1', 'xlsxwriter>=1.4.3', 'zstandard>=0.15.2']
Introduced in https://github.com/pandas-dev/pandas/pull/42269 Requires xarray bump as their `get_loc` usage was cleaned up in 0.21.0
https://api.github.com/repos/pandas-dev/pandas/pulls/49630
2022-11-10T22:56:24Z
2022-12-06T22:01:57Z
2022-12-06T22:01:57Z
2022-12-06T22:06:30Z
Fix accidental loss-of-precision for to_datetime(str, unit=...)
diff --git a/doc/source/whatsnew/v2.2.2.rst b/doc/source/whatsnew/v2.2.2.rst index 54084abab7817..19539918b8c8f 100644 --- a/doc/source/whatsnew/v2.2.2.rst +++ b/doc/source/whatsnew/v2.2.2.rst @@ -15,7 +15,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - :meth:`DataFrame.__dataframe__` was producing incorrect data buffers when the a column's type was a pandas nullable on with missing values (:issue:`56702`) - :meth:`DataFrame.__dataframe__` was producing incorrect data buffers when the a column's type was a pyarrow nullable on with missing values (:issue:`57664`) -- +- Fixed regression in precision of :func:`to_datetime` with string and ``unit`` input (:issue:`57051`) .. --------------------------------------------------------------------------- .. _whatsnew_222.bug_fixes: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index d320bfdbe3022..effd7f586f266 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -275,7 +275,7 @@ def array_with_unit_to_datetime( bint is_raise = errors == "raise" ndarray[int64_t] iresult tzinfo tz = None - float fval + double fval assert is_coerce or is_raise diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 9d93a05cf1761..7992b48a4b0cc 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1735,6 +1735,14 @@ def test_unit(self, cache): with pytest.raises(ValueError, match=msg): to_datetime([1], unit="D", format="%Y%m%d", cache=cache) + def test_unit_str(self, cache): + # GH 57051 + # Test that strs aren't dropping precision to 32-bit accidentally. + with tm.assert_produces_warning(FutureWarning): + res = to_datetime(["1704660000"], unit="s", origin="unix") + expected = to_datetime([1704660000], unit="s", origin="unix") + tm.assert_index_equal(res, expected) + def test_unit_array_mixed_nans(self, cache): values = [11111111111111111, 1, 1.0, iNaT, NaT, np.nan, "NaT", ""]
In Pandas 1.5.3, the `float(val)` cast was inline to the `cast_from_unit` call in `array_with_unit_to_datetime`. This caused the intermediate (unnamed) value to be a Python float. Since #50301, a temporary variable was added to avoid multiple casts, but with explicit type `cdef float`, which defines a _Cython_ float. This type is 32-bit, and causes a loss of precision, and a regression in parsing from 1.5.3. Since `cast_from_unit` takes an `object`, not a more specific Cython type, remove the explicit type from the temporary `fval` variable entirely. This will cause it to be a (64-bit) Python float, and thus not lose precision. Fixes #57051 - [x] 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). - [n/a] 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/57548
2024-02-21T12:08:47Z
2024-03-27T16:51:54Z
2024-03-27T16:51:54Z
2024-03-28T09:28:23Z
PERF: Return RangeIndex columns in str.extract when possible
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index a77e93c4ab4be..70b4364e6be11 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -175,7 +175,7 @@ Performance improvements - Performance improvement in :meth:`RangeIndex.append` when appending the same index (:issue:`57252`) - Performance improvement in :meth:`RangeIndex.take` returning a :class:`RangeIndex` instead of a :class:`Index` when possible. (:issue:`57445`) - Performance improvement in indexing operations for string dtypes (:issue:`56997`) -- +- :meth:`Series.str.extract` returns a :class:`RangeIndex` columns instead of an :class:`Index` column when possible (:issue:`?``) .. --------------------------------------------------------------------------- .. _whatsnew_300.bug_fixes: diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index fe68107a953bb..0dddfc4f4c4c1 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -3557,7 +3557,7 @@ def _get_single_group_name(regex: re.Pattern) -> Hashable: return None -def _get_group_names(regex: re.Pattern) -> list[Hashable]: +def _get_group_names(regex: re.Pattern) -> list[Hashable] | range: """ Get named groups from compiled regex. @@ -3571,8 +3571,15 @@ def _get_group_names(regex: re.Pattern) -> list[Hashable]: ------- list of column labels """ + rng = range(regex.groups) names = {v: k for k, v in regex.groupindex.items()} - return [names.get(1 + i, i) for i in range(regex.groups)] + if not names: + return rng + result: list[Hashable] = [names.get(1 + i, i) for i in rng] + arr = np.array(result) + if arr.dtype.kind == "i" and lib.is_range_indexer(arr, len(arr)): + return rng + return result def str_extractall(arr, pat, flags: int = 0) -> DataFrame: diff --git a/pandas/tests/strings/test_extract.py b/pandas/tests/strings/test_extract.py index 7ebcbdc7a8533..1dc7dbabe85b0 100644 --- a/pandas/tests/strings/test_extract.py +++ b/pandas/tests/strings/test_extract.py @@ -563,13 +563,13 @@ def test_extractall_no_matches(data, names, any_string_dtype): # one un-named group. result = s.str.extractall("(z)") - expected = DataFrame(columns=[0], index=expected_index, dtype=any_string_dtype) - tm.assert_frame_equal(result, expected) + expected = DataFrame(columns=range(1), index=expected_index, dtype=any_string_dtype) + tm.assert_frame_equal(result, expected, check_column_type=True) # two un-named groups. result = s.str.extractall("(z)(z)") - expected = DataFrame(columns=[0, 1], index=expected_index, dtype=any_string_dtype) - tm.assert_frame_equal(result, expected) + expected = DataFrame(columns=range(2), index=expected_index, dtype=any_string_dtype) + tm.assert_frame_equal(result, expected, check_column_type=True) # one named group. result = s.str.extractall("(?P<first>z)")
Retry at https://github.com/pandas-dev/pandas/pull/57465
https://api.github.com/repos/pandas-dev/pandas/pulls/57542
2024-02-20T23:28:38Z
2024-02-21T20:17:51Z
2024-02-21T20:17:51Z
2024-02-21T20:34:48Z
CLN: Use not .any() instead of comparing to 0
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 2dd6f672eca45..8552839b12d18 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -474,7 +474,7 @@ def _shallow_copy(self, values, name: Hashable = no_default): diff = values[1] - values[0] if diff != 0: maybe_range_indexer, remainder = np.divmod(values - values[0], diff) - if (remainder == 0).all() and lib.is_range_indexer( + if not remainder.any() and lib.is_range_indexer( maybe_range_indexer, len(maybe_range_indexer) ): new_range = range(values[0], values[-1] + diff, diff)
Follow up to https://github.com/pandas-dev/pandas/pull/57534 ```python In [1]: import numpy as np In [2]: zeros = np.zeros(100_000) In [4]: %timeit (zeros == 0).all() 36.4 µs ± 108 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) In [5]: %timeit not np.all(zeros) 33.6 µs ± 111 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/57541
2024-02-20T23:18:21Z
2024-02-21T00:23:00Z
2024-02-21T00:23:00Z
2024-02-21T00:23:03Z
Backport PR #57510 on branch 2.2.x (DOC: Fix xarray example)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0ec17173287f5..1dd471a09f1b1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3278,18 +3278,18 @@ def to_xarray(self): 2 lion mammal 80.5 4 3 monkey mammal NaN 4 - >>> df.to_xarray() + >>> df.to_xarray() # doctest: +SKIP <xarray.Dataset> Dimensions: (index: 4) Coordinates: - * index (index) int64 0 1 2 3 + * index (index) int64 32B 0 1 2 3 Data variables: - name (index) object 'falcon' 'parrot' 'lion' 'monkey' - class (index) object 'bird' 'bird' 'mammal' 'mammal' - max_speed (index) float64 389.0 24.0 80.5 nan - num_legs (index) int64 2 2 4 4 + name (index) object 32B 'falcon' 'parrot' 'lion' 'monkey' + class (index) object 32B 'bird' 'bird' 'mammal' 'mammal' + max_speed (index) float64 32B 389.0 24.0 80.5 nan + num_legs (index) int64 32B 2 2 4 4 - >>> df['max_speed'].to_xarray() + >>> df['max_speed'].to_xarray() # doctest: +SKIP <xarray.DataArray 'max_speed' (index: 4)> array([389. , 24. , 80.5, nan]) Coordinates: @@ -3311,7 +3311,7 @@ class (index) object 'bird' 'bird' 'mammal' 'mammal' 2018-01-02 falcon 361 parrot 15 - >>> df_multiindex.to_xarray() + >>> df_multiindex.to_xarray() # doctest: +SKIP <xarray.Dataset> Dimensions: (date: 2, animal: 2) Coordinates:
#57510
https://api.github.com/repos/pandas-dev/pandas/pulls/57538
2024-02-20T20:48:03Z
2024-02-20T21:32:46Z
2024-02-20T21:32:46Z
2024-02-20T21:32:46Z
Backport PR #57536 on branch 2.2.x (BUG: dt64 + DateOffset with milliseconds)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 85b9346aa01a5..ab62a7c7598d5 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -42,6 +42,7 @@ Fixed regressions - Fixed regression in :meth:`Series.astype` introducing decimals when converting from integer with missing values to string dtype (:issue:`57418`) - Fixed regression in :meth:`Series.pct_change` raising a ``ValueError`` for an empty :class:`Series` (:issue:`57056`) - Fixed regression in :meth:`Series.to_numpy` when dtype is given as float and the data contains NaNs (:issue:`57121`) +- Fixed regression in addition or subtraction of :class:`DateOffset` objects with millisecond components to ``datetime64`` :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`57529`) .. --------------------------------------------------------------------------- .. _whatsnew_221.bug_fixes: diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 70e1ca1c4012a..c37a4b285daef 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1458,13 +1458,22 @@ cdef class RelativeDeltaOffset(BaseOffset): "minutes", "seconds", "microseconds", + "milliseconds", } # relativedelta/_offset path only valid for base DateOffset if self._use_relativedelta and set(kwds).issubset(relativedelta_fast): + td_args = { + "days", + "hours", + "minutes", + "seconds", + "microseconds", + "milliseconds" + } td_kwds = { key: val for key, val in kwds.items() - if key in ["days", "hours", "minutes", "seconds", "microseconds"] + if key in td_args } if "weeks" in kwds: days = td_kwds.get("days", 0) @@ -1474,6 +1483,8 @@ cdef class RelativeDeltaOffset(BaseOffset): delta = Timedelta(**td_kwds) if "microseconds" in kwds: delta = delta.as_unit("us") + elif "milliseconds" in kwds: + delta = delta.as_unit("ms") else: delta = delta.as_unit("s") else: @@ -1491,6 +1502,8 @@ cdef class RelativeDeltaOffset(BaseOffset): delta = Timedelta(self._offset * self.n) if "microseconds" in kwds: delta = delta.as_unit("us") + elif "milliseconds" in kwds: + delta = delta.as_unit("ms") else: delta = delta.as_unit("s") return delta diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index dbff88dc6f4f6..a468449efd507 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1586,6 +1586,38 @@ def test_dti_add_sub_nonzero_mth_offset( expected = tm.box_expected(expected, box_with_array, False) tm.assert_equal(result, expected) + def test_dt64arr_series_add_DateOffset_with_milli(self): + # GH 57529 + dti = DatetimeIndex( + [ + "2000-01-01 00:00:00.012345678", + "2000-01-31 00:00:00.012345678", + "2000-02-29 00:00:00.012345678", + ], + dtype="datetime64[ns]", + ) + result = dti + DateOffset(milliseconds=4) + expected = DatetimeIndex( + [ + "2000-01-01 00:00:00.016345678", + "2000-01-31 00:00:00.016345678", + "2000-02-29 00:00:00.016345678", + ], + dtype="datetime64[ns]", + ) + tm.assert_index_equal(result, expected) + + result = dti + DateOffset(days=1, milliseconds=4) + expected = DatetimeIndex( + [ + "2000-01-02 00:00:00.016345678", + "2000-02-01 00:00:00.016345678", + "2000-03-01 00:00:00.016345678", + ], + dtype="datetime64[ns]", + ) + tm.assert_index_equal(result, expected) + class TestDatetime64OverflowHandling: # TODO: box + de-duplicate
Backport PR #57536: BUG: dt64 + DateOffset with milliseconds
https://api.github.com/repos/pandas-dev/pandas/pulls/57537
2024-02-20T19:51:27Z
2024-02-20T21:32:30Z
2024-02-20T21:32:29Z
2024-02-20T21:32:30Z
BUG: dt64 + DateOffset with milliseconds
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 85b9346aa01a5..ab62a7c7598d5 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -42,6 +42,7 @@ Fixed regressions - Fixed regression in :meth:`Series.astype` introducing decimals when converting from integer with missing values to string dtype (:issue:`57418`) - Fixed regression in :meth:`Series.pct_change` raising a ``ValueError`` for an empty :class:`Series` (:issue:`57056`) - Fixed regression in :meth:`Series.to_numpy` when dtype is given as float and the data contains NaNs (:issue:`57121`) +- Fixed regression in addition or subtraction of :class:`DateOffset` objects with millisecond components to ``datetime64`` :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`57529`) .. --------------------------------------------------------------------------- .. _whatsnew_221.bug_fixes: diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index f99ce7f1957c1..7301f65f3dbac 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1410,13 +1410,22 @@ cdef class RelativeDeltaOffset(BaseOffset): "minutes", "seconds", "microseconds", + "milliseconds", } # relativedelta/_offset path only valid for base DateOffset if self._use_relativedelta and set(kwds).issubset(relativedelta_fast): + td_args = { + "days", + "hours", + "minutes", + "seconds", + "microseconds", + "milliseconds" + } td_kwds = { key: val for key, val in kwds.items() - if key in ["days", "hours", "minutes", "seconds", "microseconds"] + if key in td_args } if "weeks" in kwds: days = td_kwds.get("days", 0) @@ -1426,6 +1435,8 @@ cdef class RelativeDeltaOffset(BaseOffset): delta = Timedelta(**td_kwds) if "microseconds" in kwds: delta = delta.as_unit("us") + elif "milliseconds" in kwds: + delta = delta.as_unit("ms") else: delta = delta.as_unit("s") else: @@ -1443,6 +1454,8 @@ cdef class RelativeDeltaOffset(BaseOffset): delta = Timedelta(self._offset * self.n) if "microseconds" in kwds: delta = delta.as_unit("us") + elif "milliseconds" in kwds: + delta = delta.as_unit("ms") else: delta = delta.as_unit("s") return delta diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 2dafaf277be8f..53ce93fbe4eb8 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1581,6 +1581,38 @@ def test_dti_add_sub_nonzero_mth_offset( expected = tm.box_expected(expected, box_with_array, False) tm.assert_equal(result, expected) + def test_dt64arr_series_add_DateOffset_with_milli(self): + # GH 57529 + dti = DatetimeIndex( + [ + "2000-01-01 00:00:00.012345678", + "2000-01-31 00:00:00.012345678", + "2000-02-29 00:00:00.012345678", + ], + dtype="datetime64[ns]", + ) + result = dti + DateOffset(milliseconds=4) + expected = DatetimeIndex( + [ + "2000-01-01 00:00:00.016345678", + "2000-01-31 00:00:00.016345678", + "2000-02-29 00:00:00.016345678", + ], + dtype="datetime64[ns]", + ) + tm.assert_index_equal(result, expected) + + result = dti + DateOffset(days=1, milliseconds=4) + expected = DatetimeIndex( + [ + "2000-01-02 00:00:00.016345678", + "2000-02-01 00:00:00.016345678", + "2000-03-01 00:00:00.016345678", + ], + dtype="datetime64[ns]", + ) + tm.assert_index_equal(result, expected) + class TestDatetime64OverflowHandling: # TODO: box + de-duplicate
- [ ] closes #57529 (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/57536
2024-02-20T18:54:30Z
2024-02-20T19:50:48Z
2024-02-20T19:50:47Z
2024-02-20T19:50:50Z
TST: Allow test_dti_constructor_with_non_nano_now_today to be flaky
diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 0756d490cd4fa..009723fc42360 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -1031,23 +1031,28 @@ def test_dti_constructor_with_non_nano_dtype(self, tz): result2 = DatetimeIndex(np.array(vals, dtype=object), dtype=dtype) tm.assert_index_equal(result2, expected) - def test_dti_constructor_with_non_nano_now_today(self): + def test_dti_constructor_with_non_nano_now_today(self, request): # GH#55756 now = Timestamp.now() today = Timestamp.today() result = DatetimeIndex(["now", "today"], dtype="M8[s]") assert result.dtype == "M8[s]" + diff0 = result[0] - now.as_unit("s") + diff1 = result[1] - today.as_unit("s") + assert diff1 >= pd.Timedelta(0), f"The difference is {diff0}" + assert diff0 >= pd.Timedelta(0), f"The difference is {diff0}" + # result may not exactly match [now, today] so we'll test it up to a tolerance. # (it *may* match exactly due to rounding) + # GH 57535 + request.applymarker( + pytest.mark.xfail( + reason="result may not exactly match [now, today]", strict=False + ) + ) tolerance = pd.Timedelta(seconds=1) - - diff0 = result[0] - now.as_unit("s") - assert diff0 >= pd.Timedelta(0), f"The difference is {diff0}" assert diff0 < tolerance, f"The difference is {diff0}" - - diff1 = result[1] - today.as_unit("s") - assert diff1 >= pd.Timedelta(0), f"The difference is {diff0}" assert diff1 < tolerance, f"The difference is {diff0}" def test_dti_constructor_object_float_matches_float_dtype(self):
I see this test occasionally fail e.g. https://github.com/pandas-dev/pandas/actions/runs/7977358781/job/21780077825?pr=57510 It's probably best in the long run if we can find a way to make now/today be deterministic
https://api.github.com/repos/pandas-dev/pandas/pulls/57535
2024-02-20T18:15:38Z
2024-02-20T19:53:30Z
2024-02-20T19:53:30Z
2024-02-20T19:53:32Z
PERF: Add short circuiting to RangeIndex._shallow_copy
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 20286cad58df9..2dd6f672eca45 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -22,7 +22,6 @@ index as libindex, lib, ) -from pandas._libs.algos import unique_deltas from pandas._libs.lib import no_default from pandas.compat.numpy import function as nv from pandas.util._decorators import ( @@ -469,15 +468,18 @@ def _shallow_copy(self, values, name: Hashable = no_default): if values.dtype.kind == "f": return Index(values, name=name, dtype=np.float64) - # GH 46675 & 43885: If values is equally spaced, return a - # more memory-compact RangeIndex instead of Index with 64-bit dtype - unique_diffs = unique_deltas(values) - if len(unique_diffs) == 1 and unique_diffs[0] != 0: - diff = unique_diffs[0] - new_range = range(values[0], values[-1] + diff, diff) - return type(self)._simple_new(new_range, name=name) - else: - return self._constructor._simple_new(values, name=name) + if values.dtype.kind == "i" and values.ndim == 1 and len(values) > 1: + # GH 46675 & 43885: If values is equally spaced, return a + # more memory-compact RangeIndex instead of Index with 64-bit dtype + diff = values[1] - values[0] + if diff != 0: + maybe_range_indexer, remainder = np.divmod(values - values[0], diff) + if (remainder == 0).all() and lib.is_range_indexer( + maybe_range_indexer, len(maybe_range_indexer) + ): + new_range = range(values[0], values[-1] + diff, diff) + return type(self)._simple_new(new_range, name=name) + return self._constructor._simple_new(values, name=name) def _view(self) -> Self: result = type(self)._simple_new(self._range, name=self._name)
xref https://github.com/pandas-dev/pandas/pull/57445#issuecomment-1953881838 There needs to be More Work done to attempt to return a RangeIndex, but this should help minimize that Work
https://api.github.com/repos/pandas-dev/pandas/pulls/57534
2024-02-20T18:00:38Z
2024-02-20T23:00:44Z
2024-02-20T23:00:44Z
2024-02-21T20:16:50Z
Backport PR #57489 on branch 2.2.x (REGR: astype introducing decimals when casting from int with na to string)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 6c6a37b2b2f89..85b9346aa01a5 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -39,6 +39,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) - Fixed regression in :meth:`ExtensionArray.to_numpy` raising for non-numeric masked dtypes (:issue:`56991`) - Fixed regression in :meth:`Index.join` raising ``TypeError`` when joining an empty index to a non-empty index containing mixed dtype values (:issue:`57048`) +- Fixed regression in :meth:`Series.astype` introducing decimals when converting from integer with missing values to string dtype (:issue:`57418`) - Fixed regression in :meth:`Series.pct_change` raising a ``ValueError`` for an empty :class:`Series` (:issue:`57056`) - Fixed regression in :meth:`Series.to_numpy` when dtype is given as float and the data contains NaNs (:issue:`57121`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index c483f35513a40..7656e8d986117 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -759,7 +759,7 @@ cpdef ndarray[object] ensure_string_array( out = arr.astype(str).astype(object) out[arr.isna()] = na_value return out - arr = arr.to_numpy() + arr = arr.to_numpy(dtype=object) elif not util.is_array(arr): arr = np.array(arr, dtype="object") diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 46f55fff91e41..4c8028e74ee55 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -673,3 +673,11 @@ def test_astype_timedelta64_with_np_nan(self): result = Series([Timedelta(1), np.nan], dtype="timedelta64[ns]") expected = Series([Timedelta(1), NaT], dtype="timedelta64[ns]") tm.assert_series_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_astype_int_na_string(self): + # GH#57418 + ser = Series([12, NA], dtype="Int64[pyarrow]") + result = ser.astype("string[pyarrow]") + expected = Series(["12", NA], dtype="string[pyarrow]") + tm.assert_series_equal(result, expected)
Backport PR #57489: REGR: astype introducing decimals when casting from int with na to string
https://api.github.com/repos/pandas-dev/pandas/pulls/57533
2024-02-20T17:27:01Z
2024-02-20T18:51:27Z
2024-02-20T18:51:27Z
2024-02-20T18:51:27Z
TYP: Remove None from copy deep values
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index bc5f6b2733b99..19d32f8fb9312 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6327,7 +6327,7 @@ def astype( return cast(Self, result) @final - def copy(self, deep: bool | None = True) -> Self: + def copy(self, deep: bool = True) -> Self: """ Make a copy of this object's indices and data. @@ -6460,7 +6460,7 @@ def copy(self, deep: bool | None = True) -> Self: 1 [3, 4] dtype: object """ - data = self._mgr.copy(deep=deep) # type: ignore[arg-type] + data = self._mgr.copy(deep=deep) return self._constructor_from_mgr(data, axes=data.axes).__finalize__( self, method="copy" )
- [ ] 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/57532
2024-02-20T17:11:39Z
2024-02-20T17:55:36Z
2024-02-20T17:55:36Z
2024-02-20T17:55:44Z
dsintro.rst: Add missing 'the'
diff --git a/doc/source/user_guide/dsintro.rst b/doc/source/user_guide/dsintro.rst index d1e981ee1bbdc..ebb5b0b94e418 100644 --- a/doc/source/user_guide/dsintro.rst +++ b/doc/source/user_guide/dsintro.rst @@ -111,7 +111,7 @@ However, operations such as slicing will also slice the index. .. note:: We will address array-based indexing like ``s.iloc[[4, 3, 1]]`` - in :ref:`section on indexing <indexing>`. + in the :ref:`section on indexing <indexing>`. Like a NumPy array, a pandas :class:`Series` has a single :attr:`~Series.dtype`.
dsintro.rst: Add missing 'the' to the sentence
https://api.github.com/repos/pandas-dev/pandas/pulls/57530
2024-02-20T16:37:29Z
2024-02-20T17:02:33Z
2024-02-20T17:02:33Z
2024-02-20T17:05:39Z
dsintro.rst: Clarify Series constructor information
diff --git a/doc/source/user_guide/dsintro.rst b/doc/source/user_guide/dsintro.rst index d1e981ee1bbdc..f0231c4641521 100644 --- a/doc/source/user_guide/dsintro.rst +++ b/doc/source/user_guide/dsintro.rst @@ -41,8 +41,8 @@ Here, ``data`` can be many different things: * an ndarray * a scalar value (like 5) -The passed **index** is a list of axis labels. Thus, this separates into a few -cases depending on what **data is**: +The passed **index** is a list of axis labels. The constructor's behavior +depends on **data**'s type: **From ndarray**
Clarify sentence leading into Series constructor explanation
https://api.github.com/repos/pandas-dev/pandas/pulls/57528
2024-02-20T16:23:46Z
2024-02-20T17:03:23Z
2024-02-20T17:03:23Z
2024-02-20T17:06:30Z
dsintro.rst: Add more info for first mention of ndarray
diff --git a/doc/source/user_guide/dsintro.rst b/doc/source/user_guide/dsintro.rst index d1e981ee1bbdc..de3bd8131e931 100644 --- a/doc/source/user_guide/dsintro.rst +++ b/doc/source/user_guide/dsintro.rst @@ -97,7 +97,7 @@ provided. The value will be repeated to match the length of **index**. Series is ndarray-like ~~~~~~~~~~~~~~~~~~~~~~ -:class:`Series` acts very similarly to a ``ndarray`` and is a valid argument to most NumPy functions. +:class:`Series` acts very similarly to a :class:`numpy.ndarray` and is a valid argument to most NumPy functions. However, operations such as slicing will also slice the index. .. ipython:: python
As this is the first mention of an ndarray, qualify it by adding a link to what it is.
https://api.github.com/repos/pandas-dev/pandas/pulls/57527
2024-02-20T16:19:05Z
2024-02-20T17:03:58Z
2024-02-20T17:03:58Z
2024-02-20T17:06:07Z
TYP: fix mypy failures on main in pandas/core/generic.py
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 946bf99e7c9ae..bc5f6b2733b99 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6460,7 +6460,7 @@ def copy(self, deep: bool | None = True) -> Self: 1 [3, 4] dtype: object """ - data = self._mgr.copy(deep=deep) + data = self._mgr.copy(deep=deep) # type: ignore[arg-type] return self._constructor_from_mgr(data, axes=data.axes).__finalize__( self, method="copy" )
fixed `mypy` failure on main in `pandas/core/generic.py`: ``` pandas/core/generic.py:6463: error: Argument "deep" to "copy" of "BaseBlockManager" has incompatible type "bool | None"; expected "bool | Literal['all']" [arg-type] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/57522
2024-02-20T11:45:33Z
2024-02-20T17:07:46Z
2024-02-20T17:07:46Z
2024-02-20T17:08:05Z
TST: add a test for selecting columns in DataFrame with `big-endian` dtype
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 59bdd43d48ba0..734cf5debb219 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1537,6 +1537,16 @@ def test_setitem_value_coercing_dtypes(self, indexer, idx): expected = DataFrame([[1, np.nan], [2, np.nan], ["3", np.nan]], dtype=object) tm.assert_frame_equal(df, expected) + def test_big_endian_support_selecting_columns(self): + # GH#57457 + columns = ["a"] + data = [np.array([1, 2], dtype=">f8")] + df = DataFrame(dict(zip(columns, data))) + result = df[df.columns] + dfexp = DataFrame({"a": [1, 2]}, dtype=">f8") + expected = dfexp[dfexp.columns] + tm.assert_frame_equal(result, expected) + class TestDataFrameIndexingUInt64: def test_setitem(self):
- [x] closes #57457 added a test in to check that selecting columns in DataFrame with `big-endian` dtype is supported
https://api.github.com/repos/pandas-dev/pandas/pulls/57519
2024-02-20T10:23:12Z
2024-02-20T17:11:01Z
2024-02-20T17:11:01Z
2024-02-20T17:11:09Z
Improving function definition
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 946bf99e7c9ae..e6b367ec18157 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5468,12 +5468,13 @@ def head(self, n: int = 5) -> Self: """ Return the first `n` rows. - This function returns the first `n` rows for the object based - on position. It is useful for quickly testing if your object - has the right type of data in it. + This function exhibits the same behavior as ``df[:n]``, returning the + first ``n`` rows based on position. It is useful for quickly checking + if your object has the right type of data in it. - For negative values of `n`, this function returns all rows except - the last `|n|` rows, equivalent to ``df[:n]``. + When ``n`` is positive, it returns the first ``n`` rows. For ``n`` equal to 0, + it returns an empty object. When ``n`` is negative, it returns + all rows except the last ``|n|`` rows, mirroring the behavior of ``df[:n]``. If n is larger than the number of rows, this function returns all rows.
- [x] closes #57305 - [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/57518
2024-02-20T06:42:16Z
2024-02-20T21:33:09Z
2024-02-20T21:33:09Z
2024-02-20T21:39:56Z
CI/TST: Use tmp_path for excel test
diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py index b5bb9b27258d8..f01827fa4ca2f 100644 --- a/pandas/tests/io/excel/test_odf.py +++ b/pandas/tests/io/excel/test_odf.py @@ -3,16 +3,11 @@ import numpy as np import pytest -from pandas.compat import is_platform_windows - import pandas as pd import pandas._testing as tm pytest.importorskip("odf") -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - @pytest.fixture(autouse=True) def cd_and_set_engine(monkeypatch, datapath): diff --git a/pandas/tests/io/excel/test_odswriter.py b/pandas/tests/io/excel/test_odswriter.py index 1c728ad801bc1..7843bb59f97cf 100644 --- a/pandas/tests/io/excel/test_odswriter.py +++ b/pandas/tests/io/excel/test_odswriter.py @@ -3,63 +3,62 @@ datetime, ) import re +import uuid import pytest -from pandas.compat import is_platform_windows - import pandas as pd -import pandas._testing as tm from pandas.io.excel import ExcelWriter odf = pytest.importorskip("odf") -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - @pytest.fixture def ext(): return ".ods" -def test_write_append_mode_raises(ext): +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +def test_write_append_mode_raises(tmp_excel): msg = "Append mode is not supported with odf!" - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=msg): - ExcelWriter(f, engine="odf", mode="a") + with pytest.raises(ValueError, match=msg): + ExcelWriter(tmp_excel, engine="odf", mode="a") @pytest.mark.parametrize("engine_kwargs", [None, {"kwarg": 1}]) -def test_engine_kwargs(ext, engine_kwargs): +def test_engine_kwargs(tmp_excel, engine_kwargs): # GH 42286 # GH 43445 # test for error: OpenDocumentSpreadsheet does not accept any arguments - with tm.ensure_clean(ext) as f: - if engine_kwargs is not None: - error = re.escape( - "OpenDocumentSpreadsheet() got an unexpected keyword argument 'kwarg'" - ) - with pytest.raises( - TypeError, - match=error, - ): - ExcelWriter(f, engine="odf", engine_kwargs=engine_kwargs) - else: - with ExcelWriter(f, engine="odf", engine_kwargs=engine_kwargs) as _: - pass - - -def test_book_and_sheets_consistent(ext): + if engine_kwargs is not None: + error = re.escape( + "OpenDocumentSpreadsheet() got an unexpected keyword argument 'kwarg'" + ) + with pytest.raises( + TypeError, + match=error, + ): + ExcelWriter(tmp_excel, engine="odf", engine_kwargs=engine_kwargs) + else: + with ExcelWriter(tmp_excel, engine="odf", engine_kwargs=engine_kwargs) as _: + pass + + +def test_book_and_sheets_consistent(tmp_excel): # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f) as writer: - assert writer.sheets == {} - table = odf.table.Table(name="test_name") - writer.book.spreadsheet.addElement(table) - assert writer.sheets == {"test_name": table} + with ExcelWriter(tmp_excel) as writer: + assert writer.sheets == {} + table = odf.table.Table(name="test_name") + writer.book.spreadsheet.addElement(table) + assert writer.sheets == {"test_name": table} @pytest.mark.parametrize( @@ -78,7 +77,9 @@ def test_book_and_sheets_consistent(ext): (date(2010, 10, 10), "date", "date-value", "2010-10-10"), ], ) -def test_cell_value_type(ext, value, cell_value_type, cell_value_attribute, cell_value): +def test_cell_value_type( + tmp_excel, value, cell_value_type, cell_value_attribute, cell_value +): # GH#54994 ODS: cell attributes should follow specification # http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#refTable13 from odf.namespaces import OFFICENS @@ -89,18 +90,17 @@ def test_cell_value_type(ext, value, cell_value_type, cell_value_attribute, cell table_cell_name = TableCell().qname - with tm.ensure_clean(ext) as f: - pd.DataFrame([[value]]).to_excel(f, header=False, index=False) - - with pd.ExcelFile(f) as wb: - sheet = wb._reader.get_sheet_by_index(0) - sheet_rows = sheet.getElementsByType(TableRow) - sheet_cells = [ - x - for x in sheet_rows[0].childNodes - if hasattr(x, "qname") and x.qname == table_cell_name - ] - - cell = sheet_cells[0] - assert cell.attributes.get((OFFICENS, "value-type")) == cell_value_type - assert cell.attributes.get((OFFICENS, cell_value_attribute)) == cell_value + pd.DataFrame([[value]]).to_excel(tmp_excel, header=False, index=False) + + with pd.ExcelFile(tmp_excel) as wb: + sheet = wb._reader.get_sheet_by_index(0) + sheet_rows = sheet.getElementsByType(TableRow) + sheet_cells = [ + x + for x in sheet_rows[0].childNodes + if hasattr(x, "qname") and x.qname == table_cell_name + ] + + cell = sheet_cells[0] + assert cell.attributes.get((OFFICENS, "value-type")) == cell_value_type + assert cell.attributes.get((OFFICENS, cell_value_attribute)) == cell_value diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 952026b2a50d3..5b4bbb9e686d3 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -1,12 +1,11 @@ import contextlib from pathlib import Path import re +import uuid import numpy as np import pytest -from pandas.compat import is_platform_windows - import pandas as pd from pandas import DataFrame import pandas._testing as tm @@ -19,15 +18,19 @@ openpyxl = pytest.importorskip("openpyxl") -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - @pytest.fixture def ext(): return ".xlsx" +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + def test_to_excel_styleconverter(): from openpyxl import styles @@ -61,7 +64,7 @@ def test_to_excel_styleconverter(): assert kw["protection"] == protection -def test_write_cells_merge_styled(ext): +def test_write_cells_merge_styled(tmp_excel): from pandas.io.formats.excel import ExcelCell sheet_name = "merge_styled" @@ -83,72 +86,73 @@ def test_write_cells_merge_styled(ext): ) ] - with tm.ensure_clean(ext) as path: - with _OpenpyxlWriter(path) as writer: - writer._write_cells(initial_cells, sheet_name=sheet_name) - writer._write_cells(merge_cells, sheet_name=sheet_name) + with _OpenpyxlWriter(tmp_excel) as writer: + writer._write_cells(initial_cells, sheet_name=sheet_name) + writer._write_cells(merge_cells, sheet_name=sheet_name) - wks = writer.sheets[sheet_name] - xcell_b1 = wks["B1"] - xcell_a2 = wks["A2"] - assert xcell_b1.font == openpyxl_sty_merged - assert xcell_a2.font == openpyxl_sty_merged + wks = writer.sheets[sheet_name] + xcell_b1 = wks["B1"] + xcell_a2 = wks["A2"] + assert xcell_b1.font == openpyxl_sty_merged + assert xcell_a2.font == openpyxl_sty_merged @pytest.mark.parametrize("iso_dates", [True, False]) -def test_engine_kwargs_write(ext, iso_dates): +def test_engine_kwargs_write(tmp_excel, iso_dates): # GH 42286 GH 43445 engine_kwargs = {"iso_dates": iso_dates} - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="openpyxl", engine_kwargs=engine_kwargs) as writer: - assert writer.book.iso_dates == iso_dates - # ExcelWriter won't allow us to close without writing something - DataFrame().to_excel(writer) + with ExcelWriter( + tmp_excel, engine="openpyxl", engine_kwargs=engine_kwargs + ) as writer: + assert writer.book.iso_dates == iso_dates + # ExcelWriter won't allow us to close without writing something + DataFrame().to_excel(writer) -def test_engine_kwargs_append_invalid(ext): +def test_engine_kwargs_append_invalid(tmp_excel): # GH 43445 # test whether an invalid engine kwargs actually raises - with tm.ensure_clean(ext) as f: - DataFrame(["hello", "world"]).to_excel(f) - with pytest.raises( - TypeError, - match=re.escape( - "load_workbook() got an unexpected keyword argument 'apple_banana'" - ), - ): - with ExcelWriter( - f, engine="openpyxl", mode="a", engine_kwargs={"apple_banana": "fruit"} - ) as writer: - # ExcelWriter needs us to write something to close properly - DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2") + DataFrame(["hello", "world"]).to_excel(tmp_excel) + with pytest.raises( + TypeError, + match=re.escape( + "load_workbook() got an unexpected keyword argument 'apple_banana'" + ), + ): + with ExcelWriter( + tmp_excel, + engine="openpyxl", + mode="a", + engine_kwargs={"apple_banana": "fruit"}, + ) as writer: + # ExcelWriter needs us to write something to close properly + DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2") @pytest.mark.parametrize("data_only, expected", [(True, 0), (False, "=1+1")]) -def test_engine_kwargs_append_data_only(ext, data_only, expected): +def test_engine_kwargs_append_data_only(tmp_excel, data_only, expected): # GH 43445 # tests whether the data_only engine_kwarg actually works well for # openpyxl's load_workbook - with tm.ensure_clean(ext) as f: - DataFrame(["=1+1"]).to_excel(f) - with ExcelWriter( - f, engine="openpyxl", mode="a", engine_kwargs={"data_only": data_only} - ) as writer: - assert writer.sheets["Sheet1"]["B2"].value == expected - # ExcelWriter needs us to writer something to close properly? - DataFrame().to_excel(writer, sheet_name="Sheet2") - - # ensure that data_only also works for reading - # and that formulas/values roundtrip - assert ( - pd.read_excel( - f, - sheet_name="Sheet1", - engine="openpyxl", - engine_kwargs={"data_only": data_only}, - ).iloc[0, 1] - == expected - ) + DataFrame(["=1+1"]).to_excel(tmp_excel) + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", engine_kwargs={"data_only": data_only} + ) as writer: + assert writer.sheets["Sheet1"]["B2"].value == expected + # ExcelWriter needs us to writer something to close properly? + DataFrame().to_excel(writer, sheet_name="Sheet2") + + # ensure that data_only also works for reading + # and that formulas/values roundtrip + assert ( + pd.read_excel( + tmp_excel, + sheet_name="Sheet1", + engine="openpyxl", + engine_kwargs={"data_only": data_only}, + ).iloc[0, 1] + == expected + ) @pytest.mark.parametrize("kwarg_name", ["read_only", "data_only"]) @@ -167,26 +171,25 @@ def test_engine_kwargs_append_reader(datapath, ext, kwarg_name, kwarg_value): @pytest.mark.parametrize( "mode,expected", [("w", ["baz"]), ("a", ["foo", "bar", "baz"])] ) -def test_write_append_mode(ext, mode, expected): +def test_write_append_mode(tmp_excel, mode, expected): df = DataFrame([1], columns=["baz"]) - with tm.ensure_clean(ext) as f: - wb = openpyxl.Workbook() - wb.worksheets[0].title = "foo" - wb.worksheets[0]["A1"].value = "foo" - wb.create_sheet("bar") - wb.worksheets[1]["A1"].value = "bar" - wb.save(f) + wb = openpyxl.Workbook() + wb.worksheets[0].title = "foo" + wb.worksheets[0]["A1"].value = "foo" + wb.create_sheet("bar") + wb.worksheets[1]["A1"].value = "bar" + wb.save(tmp_excel) - with ExcelWriter(f, engine="openpyxl", mode=mode) as writer: - df.to_excel(writer, sheet_name="baz", index=False) + with ExcelWriter(tmp_excel, engine="openpyxl", mode=mode) as writer: + df.to_excel(writer, sheet_name="baz", index=False) - with contextlib.closing(openpyxl.load_workbook(f)) as wb2: - result = [sheet.title for sheet in wb2.worksheets] - assert result == expected + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb2: + result = [sheet.title for sheet in wb2.worksheets] + assert result == expected - for index, cell_value in enumerate(expected): - assert wb2.worksheets[index]["A1"].value == cell_value + for index, cell_value in enumerate(expected): + assert wb2.worksheets[index]["A1"].value == cell_value @pytest.mark.parametrize( @@ -197,26 +200,25 @@ def test_write_append_mode(ext, mode, expected): ("overlay", 1, ["pear", "banana"]), ], ) -def test_if_sheet_exists_append_modes(ext, if_sheet_exists, num_sheets, expected): +def test_if_sheet_exists_append_modes(tmp_excel, if_sheet_exists, num_sheets, expected): # GH 40230 df1 = DataFrame({"fruit": ["apple", "banana"]}) df2 = DataFrame({"fruit": ["pear"]}) - with tm.ensure_clean(ext) as f: - df1.to_excel(f, engine="openpyxl", sheet_name="foo", index=False) - with ExcelWriter( - f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists - ) as writer: - df2.to_excel(writer, sheet_name="foo", index=False) + df1.to_excel(tmp_excel, engine="openpyxl", sheet_name="foo", index=False) + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists + ) as writer: + df2.to_excel(writer, sheet_name="foo", index=False) - with contextlib.closing(openpyxl.load_workbook(f)) as wb: - assert len(wb.sheetnames) == num_sheets - assert wb.sheetnames[0] == "foo" - result = pd.read_excel(wb, "foo", engine="openpyxl") - assert list(result["fruit"]) == expected - if len(wb.sheetnames) == 2: - result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl") - tm.assert_frame_equal(result, df2) + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + assert len(wb.sheetnames) == num_sheets + assert wb.sheetnames[0] == "foo" + result = pd.read_excel(wb, "foo", engine="openpyxl") + assert list(result["fruit"]) == expected + if len(wb.sheetnames) == 2: + result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl") + tm.assert_frame_equal(result, df2) @pytest.mark.parametrize( @@ -228,28 +230,29 @@ def test_if_sheet_exists_append_modes(ext, if_sheet_exists, num_sheets, expected (1, 1, ["hello", "world"], ["goodbye", "poop"]), ], ) -def test_append_overlay_startrow_startcol(ext, startrow, startcol, greeting, goodbye): +def test_append_overlay_startrow_startcol( + tmp_excel, startrow, startcol, greeting, goodbye +): df1 = DataFrame({"greeting": ["hello", "world"], "goodbye": ["goodbye", "people"]}) df2 = DataFrame(["poop"]) - with tm.ensure_clean(ext) as f: - df1.to_excel(f, engine="openpyxl", sheet_name="poo", index=False) - with ExcelWriter( - f, engine="openpyxl", mode="a", if_sheet_exists="overlay" - ) as writer: - # use startrow+1 because we don't have a header - df2.to_excel( - writer, - index=False, - header=False, - startrow=startrow + 1, - startcol=startcol, - sheet_name="poo", - ) + df1.to_excel(tmp_excel, engine="openpyxl", sheet_name="poo", index=False) + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", if_sheet_exists="overlay" + ) as writer: + # use startrow+1 because we don't have a header + df2.to_excel( + writer, + index=False, + header=False, + startrow=startrow + 1, + startcol=startcol, + sheet_name="poo", + ) - result = pd.read_excel(f, sheet_name="poo", engine="openpyxl") - expected = DataFrame({"greeting": greeting, "goodbye": goodbye}) - tm.assert_frame_equal(result, expected) + result = pd.read_excel(tmp_excel, sheet_name="poo", engine="openpyxl") + expected = DataFrame({"greeting": greeting, "goodbye": goodbye}) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -270,29 +273,27 @@ def test_append_overlay_startrow_startcol(ext, startrow, startcol, greeting, goo ), ], ) -def test_if_sheet_exists_raises(ext, if_sheet_exists, msg): +def test_if_sheet_exists_raises(tmp_excel, if_sheet_exists, msg): # GH 40230 df = DataFrame({"fruit": ["pear"]}) - with tm.ensure_clean(ext) as f: - df.to_excel(f, sheet_name="foo", engine="openpyxl") - with pytest.raises(ValueError, match=re.escape(msg)): - with ExcelWriter( - f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists - ) as writer: - df.to_excel(writer, sheet_name="foo") + df.to_excel(tmp_excel, sheet_name="foo", engine="openpyxl") + with pytest.raises(ValueError, match=re.escape(msg)): + with ExcelWriter( + tmp_excel, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists + ) as writer: + df.to_excel(writer, sheet_name="foo") -def test_to_excel_with_openpyxl_engine(ext): +def test_to_excel_with_openpyxl_engine(tmp_excel): # GH 29854 - with tm.ensure_clean(ext) as filename: - df1 = DataFrame({"A": np.linspace(1, 10, 10)}) - df2 = DataFrame({"B": np.linspace(1, 20, 10)}) - df = pd.concat([df1, df2], axis=1) - styled = df.style.map( - lambda val: f"color: {'red' if val < 0 else 'black'}" - ).highlight_max() + df1 = DataFrame({"A": np.linspace(1, 10, 10)}) + df2 = DataFrame({"B": np.linspace(1, 20, 10)}) + df = pd.concat([df1, df2], axis=1) + styled = df.style.map( + lambda val: f"color: {'red' if val < 0 else 'black'}" + ).highlight_max() - styled.to_excel(filename, engine="openpyxl") + styled.to_excel(tmp_excel, engine="openpyxl") @pytest.mark.parametrize("read_only", [True, False]) @@ -342,25 +343,24 @@ def test_read_with_bad_dimension( tm.assert_frame_equal(result, expected) -def test_append_mode_file(ext): +def test_append_mode_file(tmp_excel): # GH 39576 df = DataFrame() - with tm.ensure_clean(ext) as f: - df.to_excel(f, engine="openpyxl") + df.to_excel(tmp_excel, engine="openpyxl") - with ExcelWriter( - f, mode="a", engine="openpyxl", if_sheet_exists="new" - ) as writer: - df.to_excel(writer) + with ExcelWriter( + tmp_excel, mode="a", engine="openpyxl", if_sheet_exists="new" + ) as writer: + df.to_excel(writer) - # make sure that zip files are not concatenated by making sure that - # "docProps/app.xml" only occurs twice in the file - data = Path(f).read_bytes() - first = data.find(b"docProps/app.xml") - second = data.find(b"docProps/app.xml", first + 1) - third = data.find(b"docProps/app.xml", second + 1) - assert second != -1 and third == -1 + # make sure that zip files are not concatenated by making sure that + # "docProps/app.xml" only occurs twice in the file + data = Path(tmp_excel).read_bytes() + first = data.find(b"docProps/app.xml") + second = data.find(b"docProps/app.xml", first + 1) + third = data.find(b"docProps/app.xml", second + 1) + assert second != -1 and third == -1 # When read_only is None, use read_excel instead of a workbook @@ -401,13 +401,12 @@ def test_read_empty_with_blank_row(datapath, ext, read_only): tm.assert_frame_equal(result, expected) -def test_book_and_sheets_consistent(ext): +def test_book_and_sheets_consistent(tmp_excel): # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="openpyxl") as writer: - assert writer.sheets == {} - sheet = writer.book.create_sheet("test_name", 0) - assert writer.sheets == {"test_name": sheet} + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + assert writer.sheets == {} + sheet = writer.book.create_sheet("test_name", 0) + assert writer.sheets == {"test_name": sheet} def test_ints_spelled_with_decimals(datapath, ext): diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 2cf17913ba6e4..f0a72ba6163fa 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -11,6 +11,7 @@ import platform import re from urllib.error import URLError +import uuid from zipfile import BadZipFile import numpy as np @@ -18,7 +19,6 @@ from pandas._config import using_pyarrow_string_dtype -from pandas.compat import is_platform_windows import pandas.util._test_decorators as td import pandas as pd @@ -35,9 +35,6 @@ StringArray, ) -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"] engine_params = [ # Add any engines to test here @@ -126,6 +123,13 @@ def read_ext(engine_and_read_ext): return read_ext +@pytest.fixture +def tmp_excel(read_ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{read_ext}" + tmp.touch() + return str(tmp) + + @pytest.fixture def df_ref(datapath): """ @@ -592,7 +596,7 @@ def test_reader_dtype_str(self, read_ext, dtype, expected): expected = DataFrame(expected) tm.assert_frame_equal(actual, expected) - def test_dtype_backend(self, read_ext, dtype_backend, engine): + def test_dtype_backend(self, read_ext, dtype_backend, engine, tmp_excel): # GH#36712 if read_ext in (".xlsb", ".xls"): pytest.skip(f"No engine for filetype: '{read_ext}'") @@ -611,11 +615,10 @@ def test_dtype_backend(self, read_ext, dtype_backend, engine): "j": Series([pd.NA, pd.NA], dtype="Int64"), } ) - with tm.ensure_clean(read_ext) as file_path: - df.to_excel(file_path, sheet_name="test", index=False) - result = pd.read_excel( - file_path, sheet_name="test", dtype_backend=dtype_backend - ) + df.to_excel(tmp_excel, sheet_name="test", index=False) + result = pd.read_excel( + tmp_excel, sheet_name="test", dtype_backend=dtype_backend + ) if dtype_backend == "pyarrow": import pyarrow as pa @@ -640,26 +643,25 @@ def test_dtype_backend(self, read_ext, dtype_backend, engine): tm.assert_frame_equal(result, expected) - def test_dtype_backend_and_dtype(self, read_ext): + def test_dtype_backend_and_dtype(self, read_ext, tmp_excel): # GH#36712 if read_ext in (".xlsb", ".xls"): pytest.skip(f"No engine for filetype: '{read_ext}'") df = DataFrame({"a": [np.nan, 1.0], "b": [2.5, np.nan]}) - with tm.ensure_clean(read_ext) as file_path: - df.to_excel(file_path, sheet_name="test", index=False) - result = pd.read_excel( - file_path, - sheet_name="test", - dtype_backend="numpy_nullable", - dtype="float64", - ) + df.to_excel(tmp_excel, sheet_name="test", index=False) + result = pd.read_excel( + tmp_excel, + sheet_name="test", + dtype_backend="numpy_nullable", + dtype="float64", + ) tm.assert_frame_equal(result, df) @pytest.mark.xfail( using_pyarrow_string_dtype(), reason="infer_string takes precedence" ) - def test_dtype_backend_string(self, read_ext, string_storage): + def test_dtype_backend_string(self, read_ext, string_storage, tmp_excel): # GH#36712 if read_ext in (".xlsb", ".xls"): pytest.skip(f"No engine for filetype: '{read_ext}'") @@ -673,11 +675,10 @@ def test_dtype_backend_string(self, read_ext, string_storage): "b": np.array(["x", pd.NA], dtype=np.object_), } ) - with tm.ensure_clean(read_ext) as file_path: - df.to_excel(file_path, sheet_name="test", index=False) - result = pd.read_excel( - file_path, sheet_name="test", dtype_backend="numpy_nullable" - ) + df.to_excel(tmp_excel, sheet_name="test", index=False) + result = pd.read_excel( + tmp_excel, sheet_name="test", dtype_backend="numpy_nullable" + ) if string_storage == "python": expected = DataFrame( @@ -1705,7 +1706,7 @@ def test_ignore_chartsheets(self, request, engine, read_ext): with pd.ExcelFile("chartsheet" + read_ext) as excel: assert excel.sheet_names == ["Sheet1"] - def test_corrupt_files_closed(self, engine, read_ext): + def test_corrupt_files_closed(self, engine, tmp_excel): # GH41778 errors = (BadZipFile,) if engine is None: @@ -1719,10 +1720,9 @@ def test_corrupt_files_closed(self, engine, read_ext): errors = (CalamineError,) - with tm.ensure_clean(f"corrupt{read_ext}") as file: - Path(file).write_text("corrupt", encoding="utf-8") - with tm.assert_produces_warning(False): - try: - pd.ExcelFile(file, engine=engine) - except errors: - pass + Path(tmp_excel).write_text("corrupt", encoding="utf-8") + with tm.assert_produces_warning(False): + try: + pd.ExcelFile(tmp_excel, engine=engine) + except errors: + pass diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index e801d1c647ed1..f70e65e34c584 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -1,10 +1,10 @@ import contextlib import time +import uuid import numpy as np import pytest -from pandas.compat import is_platform_windows import pandas.util._test_decorators as td from pandas import ( @@ -21,8 +21,12 @@ # could compute styles and render to excel without jinja2, since there is no # 'template' file, but this needs the import error to delayed until render time. -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu + +@pytest.fixture +def tmp_excel(tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}.xlsx" + tmp.touch() + return str(tmp) def assert_equal_cell_styles(cell1, cell2): @@ -35,48 +39,43 @@ def assert_equal_cell_styles(cell1, cell2): assert cell1.protection.__dict__ == cell2.protection.__dict__ -def test_styler_default_values(): +def test_styler_default_values(tmp_excel): # GH 54154 openpyxl = pytest.importorskip("openpyxl") df = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 1, "B": 2, "C": 3}]) - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine="openpyxl") as writer: - df.to_excel(writer, sheet_name="custom") + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + df.to_excel(writer, sheet_name="custom") - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # Check font, spacing, indentation - assert wb["custom"].cell(1, 1).font.bold is False - assert wb["custom"].cell(1, 1).alignment.horizontal is None - assert wb["custom"].cell(1, 1).alignment.vertical is None + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # Check font, spacing, indentation + assert wb["custom"].cell(1, 1).font.bold is False + assert wb["custom"].cell(1, 1).alignment.horizontal is None + assert wb["custom"].cell(1, 1).alignment.vertical is None - # Check border - assert wb["custom"].cell(1, 1).border.bottom.color is None - assert wb["custom"].cell(1, 1).border.top.color is None - assert wb["custom"].cell(1, 1).border.left.color is None - assert wb["custom"].cell(1, 1).border.right.color is None + # Check border + assert wb["custom"].cell(1, 1).border.bottom.color is None + assert wb["custom"].cell(1, 1).border.top.color is None + assert wb["custom"].cell(1, 1).border.left.color is None + assert wb["custom"].cell(1, 1).border.right.color is None -@pytest.mark.parametrize( - "engine", - ["xlsxwriter", "openpyxl"], -) -def test_styler_to_excel_unstyled(engine): +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) +def test_styler_to_excel_unstyled(engine, tmp_excel): # compare DataFrame.to_excel and Styler.to_excel when no styles applied pytest.importorskip(engine) df = DataFrame(np.random.default_rng(2).standard_normal((2, 2))) - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine=engine) as writer: - df.to_excel(writer, sheet_name="dataframe") - df.style.to_excel(writer, sheet_name="unstyled") + with ExcelWriter(tmp_excel, engine=engine) as writer: + df.to_excel(writer, sheet_name="dataframe") + df.style.to_excel(writer, sheet_name="unstyled") - openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns): - assert len(col1) == len(col2) - for cell1, cell2 in zip(col1, col2): - assert cell1.value == cell2.value - assert_equal_cell_styles(cell1, cell2) + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns): + assert len(col1) == len(col2) + for cell1, cell2 in zip(col1, col2): + assert cell1.value == cell2.value + assert_equal_cell_styles(cell1, cell2) shared_style_params = [ @@ -149,73 +148,65 @@ def test_styler_to_excel_unstyled(engine): ] -def test_styler_custom_style(): +def test_styler_custom_style(tmp_excel): # GH 54154 css_style = "background-color: #111222" openpyxl = pytest.importorskip("openpyxl") df = DataFrame([{"A": 1, "B": 2}, {"A": 1, "B": 2}]) - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine="openpyxl") as writer: - styler = df.style.map(lambda x: css_style) - styler.to_excel(writer, sheet_name="custom", index=False) - - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # Check font, spacing, indentation - assert wb["custom"].cell(1, 1).font.bold is False - assert wb["custom"].cell(1, 1).alignment.horizontal is None - assert wb["custom"].cell(1, 1).alignment.vertical is None - - # Check border - assert wb["custom"].cell(1, 1).border.bottom.color is None - assert wb["custom"].cell(1, 1).border.top.color is None - assert wb["custom"].cell(1, 1).border.left.color is None - assert wb["custom"].cell(1, 1).border.right.color is None - - # Check background color - assert wb["custom"].cell(2, 1).fill.fgColor.index == "00111222" - assert wb["custom"].cell(3, 1).fill.fgColor.index == "00111222" - assert wb["custom"].cell(2, 2).fill.fgColor.index == "00111222" - assert wb["custom"].cell(3, 2).fill.fgColor.index == "00111222" - - -@pytest.mark.parametrize( - "engine", - ["xlsxwriter", "openpyxl"], -) + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + styler = df.style.map(lambda x: css_style) + styler.to_excel(writer, sheet_name="custom", index=False) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # Check font, spacing, indentation + assert wb["custom"].cell(1, 1).font.bold is False + assert wb["custom"].cell(1, 1).alignment.horizontal is None + assert wb["custom"].cell(1, 1).alignment.vertical is None + + # Check border + assert wb["custom"].cell(1, 1).border.bottom.color is None + assert wb["custom"].cell(1, 1).border.top.color is None + assert wb["custom"].cell(1, 1).border.left.color is None + assert wb["custom"].cell(1, 1).border.right.color is None + + # Check background color + assert wb["custom"].cell(2, 1).fill.fgColor.index == "00111222" + assert wb["custom"].cell(3, 1).fill.fgColor.index == "00111222" + assert wb["custom"].cell(2, 2).fill.fgColor.index == "00111222" + assert wb["custom"].cell(3, 2).fill.fgColor.index == "00111222" + + +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) @pytest.mark.parametrize("css, attrs, expected", shared_style_params) -def test_styler_to_excel_basic(engine, css, attrs, expected): +def test_styler_to_excel_basic(engine, css, attrs, expected, tmp_excel): pytest.importorskip(engine) df = DataFrame(np.random.default_rng(2).standard_normal((1, 1))) styler = df.style.map(lambda x: css) - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine=engine) as writer: - df.to_excel(writer, sheet_name="dataframe") - styler.to_excel(writer, sheet_name="styled") - - openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test unstyled data cell does not have expected styles - # test styled cell has expected styles - u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) - for attr in attrs: - u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr) - - if isinstance(expected, dict): - assert u_cell is None or u_cell != expected[engine] - assert s_cell == expected[engine] - else: - assert u_cell is None or u_cell != expected - assert s_cell == expected - - -@pytest.mark.parametrize( - "engine", - ["xlsxwriter", "openpyxl"], -) + with ExcelWriter(tmp_excel, engine=engine) as writer: + df.to_excel(writer, sheet_name="dataframe") + styler.to_excel(writer, sheet_name="styled") + + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # test unstyled data cell does not have expected styles + # test styled cell has expected styles + u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) + for attr in attrs: + u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr) + + if isinstance(expected, dict): + assert u_cell is None or u_cell != expected[engine] + assert s_cell == expected[engine] + else: + assert u_cell is None or u_cell != expected + assert s_cell == expected + + +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) @pytest.mark.parametrize("css, attrs, expected", shared_style_params) -def test_styler_to_excel_basic_indexes(engine, css, attrs, expected): +def test_styler_to_excel_basic_indexes(engine, css, attrs, expected, tmp_excel): pytest.importorskip(engine) df = DataFrame(np.random.default_rng(2).standard_normal((1, 1))) @@ -228,31 +219,30 @@ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected): null_styler.map_index(lambda x: "null: css;", axis=0) null_styler.map_index(lambda x: "null: css;", axis=1) - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine=engine) as writer: - null_styler.to_excel(writer, sheet_name="null_styled") - styler.to_excel(writer, sheet_name="styled") - - openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test null styled index cells does not have expected styles - # test styled cell has expected styles - ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1) - uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2) - for attr in attrs: - ui_cell, si_cell = getattr(ui_cell, attr, None), getattr(si_cell, attr) - uc_cell, sc_cell = getattr(uc_cell, attr, None), getattr(sc_cell, attr) - - if isinstance(expected, dict): - assert ui_cell is None or ui_cell != expected[engine] - assert si_cell == expected[engine] - assert uc_cell is None or uc_cell != expected[engine] - assert sc_cell == expected[engine] - else: - assert ui_cell is None or ui_cell != expected - assert si_cell == expected - assert uc_cell is None or uc_cell != expected - assert sc_cell == expected + with ExcelWriter(tmp_excel, engine=engine) as writer: + null_styler.to_excel(writer, sheet_name="null_styled") + styler.to_excel(writer, sheet_name="styled") + + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # test null styled index cells does not have expected styles + # test styled cell has expected styles + ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1) + uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2) + for attr in attrs: + ui_cell, si_cell = getattr(ui_cell, attr, None), getattr(si_cell, attr) + uc_cell, sc_cell = getattr(uc_cell, attr, None), getattr(sc_cell, attr) + + if isinstance(expected, dict): + assert ui_cell is None or ui_cell != expected[engine] + assert si_cell == expected[engine] + assert uc_cell is None or uc_cell != expected[engine] + assert sc_cell == expected[engine] + else: + assert ui_cell is None or ui_cell != expected + assert si_cell == expected + assert uc_cell is None or uc_cell != expected + assert sc_cell == expected # From https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.borders.html @@ -275,12 +265,9 @@ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected): ] -@pytest.mark.parametrize( - "engine", - ["xlsxwriter", "openpyxl"], -) +@pytest.mark.parametrize("engine", ["xlsxwriter", "openpyxl"]) @pytest.mark.parametrize("border_style", excel_border_styles) -def test_styler_to_excel_border_style(engine, border_style): +def test_styler_to_excel_border_style(engine, border_style, tmp_excel): css = f"border-left: {border_style} black thin" attrs = ["border", "left", "style"] expected = border_style @@ -289,28 +276,27 @@ def test_styler_to_excel_border_style(engine, border_style): df = DataFrame(np.random.default_rng(2).standard_normal((1, 1))) styler = df.style.map(lambda x: css) - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine=engine) as writer: - df.to_excel(writer, sheet_name="dataframe") - styler.to_excel(writer, sheet_name="styled") + with ExcelWriter(tmp_excel, engine=engine) as writer: + df.to_excel(writer, sheet_name="dataframe") + styler.to_excel(writer, sheet_name="styled") - openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test unstyled data cell does not have expected styles - # test styled cell has expected styles - u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) - for attr in attrs: - u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr) + openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + # test unstyled data cell does not have expected styles + # test styled cell has expected styles + u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) + for attr in attrs: + u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr) - if isinstance(expected, dict): - assert u_cell is None or u_cell != expected[engine] - assert s_cell == expected[engine] - else: - assert u_cell is None or u_cell != expected - assert s_cell == expected + if isinstance(expected, dict): + assert u_cell is None or u_cell != expected[engine] + assert s_cell == expected[engine] + else: + assert u_cell is None or u_cell != expected + assert s_cell == expected -def test_styler_custom_converter(): +def test_styler_custom_converter(tmp_excel): openpyxl = pytest.importorskip("openpyxl") def custom_converter(css): @@ -318,14 +304,13 @@ def custom_converter(css): df = DataFrame(np.random.default_rng(2).standard_normal((1, 1))) styler = df.style.map(lambda x: "color: #888999") - with tm.ensure_clean(".xlsx") as path: - with ExcelWriter(path, engine="openpyxl") as writer: - ExcelFormatter(styler, style_converter=custom_converter).write( - writer, sheet_name="custom" - ) - - with contextlib.closing(openpyxl.load_workbook(path)) as wb: - assert wb["custom"].cell(2, 2).font.color.value == "00111222" + with ExcelWriter(tmp_excel, engine="openpyxl") as writer: + ExcelFormatter(styler, style_converter=custom_converter).write( + writer, sheet_name="custom" + ) + + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb: + assert wb["custom"].cell(2, 2).font.color.value == "00111222" @pytest.mark.single_cpu diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 7d958d2d35920..ca5c98f49f09c 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -7,11 +7,11 @@ from io import BytesIO import os import re +import uuid import numpy as np import pytest -from pandas.compat import is_platform_windows from pandas.compat._constants import PY310 from pandas.compat._optional import import_optional_dependency import pandas.util._test_decorators as td @@ -35,9 +35,6 @@ ) from pandas.io.excel._util import _writers -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - def get_exp_unit(path: str) -> str: return "ns" @@ -57,12 +54,13 @@ def merge_cells(request): @pytest.fixture -def path(ext): +def tmp_excel(ext, tmp_path): """ Fixture to open file for use in each test case. """ - with tm.ensure_clean(ext) as file_path: - yield file_path + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) @pytest.fixture @@ -96,16 +94,15 @@ class TestRoundTrip: "header,expected", [(None, [np.nan] * 4), (0, {"Unnamed: 0": [np.nan] * 3})], ) - def test_read_one_empty_col_no_header(self, ext, header, expected): + def test_read_one_empty_col_no_header(self, tmp_excel, header, expected): # xref gh-12292 filename = "no_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) - with tm.ensure_clean(ext) as path: - df.to_excel(path, sheet_name=filename, index=False, header=False) - result = pd.read_excel( - path, sheet_name=filename, usecols=[0], header=header - ) + df.to_excel(tmp_excel, sheet_name=filename, index=False, header=False) + result = pd.read_excel( + tmp_excel, sheet_name=filename, usecols=[0], header=header + ) expected = DataFrame(expected) tm.assert_frame_equal(result, expected) @@ -113,47 +110,43 @@ def test_read_one_empty_col_no_header(self, ext, header, expected): "header,expected_extra", [(None, [0]), (0, [])], ) - def test_read_one_empty_col_with_header(self, ext, header, expected_extra): + def test_read_one_empty_col_with_header(self, tmp_excel, header, expected_extra): filename = "with_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) - with tm.ensure_clean(ext) as path: - df.to_excel(path, sheet_name="with_header", index=False, header=True) - result = pd.read_excel( - path, sheet_name=filename, usecols=[0], header=header - ) + df.to_excel(tmp_excel, sheet_name="with_header", index=False, header=True) + result = pd.read_excel( + tmp_excel, sheet_name=filename, usecols=[0], header=header + ) expected = DataFrame(expected_extra + [np.nan] * 4) tm.assert_frame_equal(result, expected) - def test_set_column_names_in_parameter(self, ext): + def test_set_column_names_in_parameter(self, tmp_excel): # GH 12870 : pass down column names associated with # keyword argument names refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"]) - with tm.ensure_clean(ext) as pth: - with ExcelWriter(pth) as writer: - refdf.to_excel( - writer, sheet_name="Data_no_head", header=False, index=False - ) - refdf.to_excel(writer, sheet_name="Data_with_head", index=False) + with ExcelWriter(tmp_excel) as writer: + refdf.to_excel(writer, sheet_name="Data_no_head", header=False, index=False) + refdf.to_excel(writer, sheet_name="Data_with_head", index=False) - refdf.columns = ["A", "B"] + refdf.columns = ["A", "B"] - with ExcelFile(pth) as reader: - xlsdf_no_head = pd.read_excel( - reader, sheet_name="Data_no_head", header=None, names=["A", "B"] - ) - xlsdf_with_head = pd.read_excel( - reader, - sheet_name="Data_with_head", - index_col=None, - names=["A", "B"], - ) + with ExcelFile(tmp_excel) as reader: + xlsdf_no_head = pd.read_excel( + reader, sheet_name="Data_no_head", header=None, names=["A", "B"] + ) + xlsdf_with_head = pd.read_excel( + reader, + sheet_name="Data_with_head", + index_col=None, + names=["A", "B"], + ) - tm.assert_frame_equal(xlsdf_no_head, refdf) - tm.assert_frame_equal(xlsdf_with_head, refdf) + tm.assert_frame_equal(xlsdf_no_head, refdf) + tm.assert_frame_equal(xlsdf_with_head, refdf) - def test_creating_and_reading_multiple_sheets(self, ext): + def test_creating_and_reading_multiple_sheets(self, tmp_excel): # see gh-9450 # # Test reading multiple sheets, from a runtime @@ -167,124 +160,126 @@ def tdf(col_sheet_name): dfs = [tdf(s) for s in sheets] dfs = dict(zip(sheets, dfs)) - with tm.ensure_clean(ext) as pth: - with ExcelWriter(pth) as ew: - for sheetname, df in dfs.items(): - df.to_excel(ew, sheet_name=sheetname) + with ExcelWriter(tmp_excel) as ew: + for sheetname, df in dfs.items(): + df.to_excel(ew, sheet_name=sheetname) - dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0) + dfs_returned = pd.read_excel(tmp_excel, sheet_name=sheets, index_col=0) - for s in sheets: - tm.assert_frame_equal(dfs[s], dfs_returned[s]) + for s in sheets: + tm.assert_frame_equal(dfs[s], dfs_returned[s]) - def test_read_excel_multiindex_empty_level(self, ext): + def test_read_excel_multiindex_empty_level(self, tmp_excel): # see gh-12453 - with tm.ensure_clean(ext) as path: - df = DataFrame( - { - ("One", "x"): {0: 1}, - ("Two", "X"): {0: 3}, - ("Two", "Y"): {0: 7}, - ("Zero", ""): {0: 0}, - } - ) + df = DataFrame( + { + ("One", "x"): {0: 1}, + ("Two", "X"): {0: 3}, + ("Two", "Y"): {0: 7}, + ("Zero", ""): {0: 0}, + } + ) - expected = DataFrame( - { - ("One", "x"): {0: 1}, - ("Two", "X"): {0: 3}, - ("Two", "Y"): {0: 7}, - ("Zero", "Unnamed: 4_level_1"): {0: 0}, - } - ) + expected = DataFrame( + { + ("One", "x"): {0: 1}, + ("Two", "X"): {0: 3}, + ("Two", "Y"): {0: 7}, + ("Zero", "Unnamed: 4_level_1"): {0: 0}, + } + ) - df.to_excel(path) - actual = pd.read_excel(path, header=[0, 1], index_col=0) - tm.assert_frame_equal(actual, expected) + df.to_excel(tmp_excel) + actual = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) + tm.assert_frame_equal(actual, expected) - df = DataFrame( - { - ("Beg", ""): {0: 0}, - ("Middle", "x"): {0: 1}, - ("Tail", "X"): {0: 3}, - ("Tail", "Y"): {0: 7}, - } - ) + df = DataFrame( + { + ("Beg", ""): {0: 0}, + ("Middle", "x"): {0: 1}, + ("Tail", "X"): {0: 3}, + ("Tail", "Y"): {0: 7}, + } + ) - expected = DataFrame( - { - ("Beg", "Unnamed: 1_level_1"): {0: 0}, - ("Middle", "x"): {0: 1}, - ("Tail", "X"): {0: 3}, - ("Tail", "Y"): {0: 7}, - } - ) + expected = DataFrame( + { + ("Beg", "Unnamed: 1_level_1"): {0: 0}, + ("Middle", "x"): {0: 1}, + ("Tail", "X"): {0: 3}, + ("Tail", "Y"): {0: 7}, + } + ) - df.to_excel(path) - actual = pd.read_excel(path, header=[0, 1], index_col=0) - tm.assert_frame_equal(actual, expected) + df.to_excel(tmp_excel) + actual = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) + tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("c_idx_names", ["a", None]) @pytest.mark.parametrize("r_idx_names", ["b", None]) @pytest.mark.parametrize("c_idx_levels", [1, 3]) @pytest.mark.parametrize("r_idx_levels", [1, 3]) def test_excel_multindex_roundtrip( - self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, request + self, + tmp_excel, + c_idx_names, + r_idx_names, + c_idx_levels, + r_idx_levels, ): # see gh-4679 - with tm.ensure_clean(ext) as pth: - # Empty name case current read in as - # unnamed levels, not Nones. - check_names = bool(r_idx_names) or r_idx_levels <= 1 + # Empty name case current read in as + # unnamed levels, not Nones. + check_names = bool(r_idx_names) or r_idx_levels <= 1 - if c_idx_levels == 1: - columns = Index(list("abcde")) - else: - columns = MultiIndex.from_arrays( - [range(5) for _ in range(c_idx_levels)], - names=[f"{c_idx_names}-{i}" for i in range(c_idx_levels)], - ) - if r_idx_levels == 1: - index = Index(list("ghijk")) - else: - index = MultiIndex.from_arrays( - [range(5) for _ in range(r_idx_levels)], - names=[f"{r_idx_names}-{i}" for i in range(r_idx_levels)], - ) - df = DataFrame( - 1.1 * np.ones((5, 5)), - columns=columns, - index=index, + if c_idx_levels == 1: + columns = Index(list("abcde")) + else: + columns = MultiIndex.from_arrays( + [range(5) for _ in range(c_idx_levels)], + names=[f"{c_idx_names}-{i}" for i in range(c_idx_levels)], ) - df.to_excel(pth) - - act = pd.read_excel( - pth, - index_col=list(range(r_idx_levels)), - header=list(range(c_idx_levels)), + if r_idx_levels == 1: + index = Index(list("ghijk")) + else: + index = MultiIndex.from_arrays( + [range(5) for _ in range(r_idx_levels)], + names=[f"{r_idx_names}-{i}" for i in range(r_idx_levels)], ) - tm.assert_frame_equal(df, act, check_names=check_names) + df = DataFrame( + 1.1 * np.ones((5, 5)), + columns=columns, + index=index, + ) + df.to_excel(tmp_excel) - df.iloc[0, :] = np.nan - df.to_excel(pth) + act = pd.read_excel( + tmp_excel, + index_col=list(range(r_idx_levels)), + header=list(range(c_idx_levels)), + ) + tm.assert_frame_equal(df, act, check_names=check_names) - act = pd.read_excel( - pth, - index_col=list(range(r_idx_levels)), - header=list(range(c_idx_levels)), - ) - tm.assert_frame_equal(df, act, check_names=check_names) - - df.iloc[-1, :] = np.nan - df.to_excel(pth) - act = pd.read_excel( - pth, - index_col=list(range(r_idx_levels)), - header=list(range(c_idx_levels)), - ) - tm.assert_frame_equal(df, act, check_names=check_names) + df.iloc[0, :] = np.nan + df.to_excel(tmp_excel) + + act = pd.read_excel( + tmp_excel, + index_col=list(range(r_idx_levels)), + header=list(range(c_idx_levels)), + ) + tm.assert_frame_equal(df, act, check_names=check_names) + + df.iloc[-1, :] = np.nan + df.to_excel(tmp_excel) + act = pd.read_excel( + tmp_excel, + index_col=list(range(r_idx_levels)), + header=list(range(c_idx_levels)), + ) + tm.assert_frame_equal(df, act, check_names=check_names) - def test_read_excel_parse_dates(self, ext): + def test_read_excel_parse_dates(self, tmp_excel): # see gh-11544, gh-12051 df = DataFrame( {"col": [1, 2, 3], "date_strings": date_range("2012-01-01", periods=3)} @@ -292,34 +287,33 @@ def test_read_excel_parse_dates(self, ext): df2 = df.copy() df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") - with tm.ensure_clean(ext) as pth: - df2.to_excel(pth) + df2.to_excel(tmp_excel) - res = pd.read_excel(pth, index_col=0) - tm.assert_frame_equal(df2, res) + res = pd.read_excel(tmp_excel, index_col=0) + tm.assert_frame_equal(df2, res) - res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0) - tm.assert_frame_equal(df, res) + res = pd.read_excel(tmp_excel, parse_dates=["date_strings"], index_col=0) + tm.assert_frame_equal(df, res) - date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y") - with tm.assert_produces_warning( - FutureWarning, - match="use 'date_format' instead", - raise_on_extra_warnings=False, - ): - res = pd.read_excel( - pth, - parse_dates=["date_strings"], - date_parser=date_parser, - index_col=0, - ) - tm.assert_frame_equal(df, res) + date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y") + with tm.assert_produces_warning( + FutureWarning, + match="use 'date_format' instead", + raise_on_extra_warnings=False, + ): res = pd.read_excel( - pth, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0 + tmp_excel, + parse_dates=["date_strings"], + date_parser=date_parser, + index_col=0, ) - tm.assert_frame_equal(df, res) + tm.assert_frame_equal(df, res) + res = pd.read_excel( + tmp_excel, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0 + ) + tm.assert_frame_equal(df, res) - def test_multiindex_interval_datetimes(self, ext): + def test_multiindex_interval_datetimes(self, tmp_excel): # GH 30986 midx = MultiIndex.from_arrays( [ @@ -330,9 +324,8 @@ def test_multiindex_interval_datetimes(self, ext): ] ) df = DataFrame(range(4), index=midx) - with tm.ensure_clean(ext) as pth: - df.to_excel(pth) - result = pd.read_excel(pth, index_col=[0, 1]) + df.to_excel(tmp_excel) + result = pd.read_excel(tmp_excel, index_col=[0, 1]) expected = DataFrame( range(4), MultiIndex.from_arrays( @@ -373,7 +366,7 @@ def test_multiindex_interval_datetimes(self, ext): ) @pytest.mark.usefixtures("set_engine") class TestExcelWriter: - def test_excel_sheet_size(self, path): + def test_excel_sheet_size(self, tmp_excel): # GH 26080 breaking_row_count = 2**20 + 1 breaking_col_count = 2**14 + 1 @@ -385,16 +378,16 @@ def test_excel_sheet_size(self, path): msg = "sheet is too large" with pytest.raises(ValueError, match=msg): - row_df.to_excel(path) + row_df.to_excel(tmp_excel) with pytest.raises(ValueError, match=msg): - col_df.to_excel(path) + col_df.to_excel(tmp_excel) - def test_excel_sheet_by_name_raise(self, path): + def test_excel_sheet_by_name_raise(self, tmp_excel): gt = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) - gt.to_excel(path) + gt.to_excel(tmp_excel) - with ExcelFile(path) as xl: + with ExcelFile(tmp_excel) as xl: df = pd.read_excel(xl, sheet_name=0, index_col=0) tm.assert_frame_equal(gt, df) @@ -403,80 +396,84 @@ def test_excel_sheet_by_name_raise(self, path): with pytest.raises(ValueError, match=msg): pd.read_excel(xl, "0") - def test_excel_writer_context_manager(self, frame, path): - with ExcelWriter(path) as writer: + def test_excel_writer_context_manager(self, frame, tmp_excel): + with ExcelWriter(tmp_excel) as writer: frame.to_excel(writer, sheet_name="Data1") frame2 = frame.copy() frame2.columns = frame.columns[::-1] frame2.to_excel(writer, sheet_name="Data2") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0) found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0) tm.assert_frame_equal(found_df, frame) tm.assert_frame_equal(found_df2, frame2) - def test_roundtrip(self, frame, path): + def test_roundtrip(self, frame, tmp_excel): frame = frame.copy() frame.iloc[:5, frame.columns.get_loc("A")] = np.nan - frame.to_excel(path, sheet_name="test1") - frame.to_excel(path, sheet_name="test1", columns=["A", "B"]) - frame.to_excel(path, sheet_name="test1", header=False) - frame.to_excel(path, sheet_name="test1", index=False) + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) # test roundtrip - frame.to_excel(path, sheet_name="test1") - recons = pd.read_excel(path, sheet_name="test1", index_col=0) + frame.to_excel(tmp_excel, sheet_name="test1") + recons = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) - frame.to_excel(path, sheet_name="test1", index=False) - recons = pd.read_excel(path, sheet_name="test1", index_col=None) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) + recons = pd.read_excel(tmp_excel, sheet_name="test1", index_col=None) recons.index = frame.index tm.assert_frame_equal(frame, recons) - frame.to_excel(path, sheet_name="test1", na_rep="NA") - recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"]) + frame.to_excel(tmp_excel, sheet_name="test1", na_rep="NA") + recons = pd.read_excel( + tmp_excel, sheet_name="test1", index_col=0, na_values=["NA"] + ) tm.assert_frame_equal(frame, recons) # GH 3611 - frame.to_excel(path, sheet_name="test1", na_rep="88") - recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"]) + frame.to_excel(tmp_excel, sheet_name="test1", na_rep="88") + recons = pd.read_excel( + tmp_excel, sheet_name="test1", index_col=0, na_values=["88"] + ) tm.assert_frame_equal(frame, recons) - frame.to_excel(path, sheet_name="test1", na_rep="88") + frame.to_excel(tmp_excel, sheet_name="test1", na_rep="88") recons = pd.read_excel( - path, sheet_name="test1", index_col=0, na_values=[88, 88.0] + tmp_excel, sheet_name="test1", index_col=0, na_values=[88, 88.0] ) tm.assert_frame_equal(frame, recons) # GH 6573 - frame.to_excel(path, sheet_name="Sheet1") - recons = pd.read_excel(path, index_col=0) + frame.to_excel(tmp_excel, sheet_name="Sheet1") + recons = pd.read_excel(tmp_excel, index_col=0) tm.assert_frame_equal(frame, recons) - frame.to_excel(path, sheet_name="0") - recons = pd.read_excel(path, index_col=0) + frame.to_excel(tmp_excel, sheet_name="0") + recons = pd.read_excel(tmp_excel, index_col=0) tm.assert_frame_equal(frame, recons) # GH 8825 Pandas Series should provide to_excel method s = frame["A"] - s.to_excel(path) - recons = pd.read_excel(path, index_col=0) + s.to_excel(tmp_excel) + recons = pd.read_excel(tmp_excel, index_col=0) tm.assert_frame_equal(s.to_frame(), recons) - def test_mixed(self, frame, path): + def test_mixed(self, frame, tmp_excel): mixed_frame = frame.copy() mixed_frame["foo"] = "bar" - mixed_frame.to_excel(path, sheet_name="test1") - with ExcelFile(path) as reader: + mixed_frame.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(mixed_frame, recons) - def test_ts_frame(self, path): - unit = get_exp_unit(path) + def test_ts_frame(self, tmp_excel): + unit = get_exp_unit(tmp_excel) df = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), columns=Index(list("ABCD")), @@ -490,74 +487,74 @@ def test_ts_frame(self, path): expected = df[:] expected.index = expected.index.as_unit(unit) - df.to_excel(path, sheet_name="test1") - with ExcelFile(path) as reader: + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) - def test_basics_with_nan(self, frame, path): + def test_basics_with_nan(self, frame, tmp_excel): frame = frame.copy() frame.iloc[:5, frame.columns.get_loc("A")] = np.nan - frame.to_excel(path, sheet_name="test1") - frame.to_excel(path, sheet_name="test1", columns=["A", "B"]) - frame.to_excel(path, sheet_name="test1", header=False) - frame.to_excel(path, sheet_name="test1", index=False) + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) @pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64]) - def test_int_types(self, np_type, path): + def test_int_types(self, np_type, tmp_excel): # Test np.int values read come back as int # (rather than float which is Excel's format). df = DataFrame( np.random.default_rng(2).integers(-10, 10, size=(10, 2)), dtype=np_type ) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) int_frame = df.astype(np.int64) tm.assert_frame_equal(int_frame, recons) - recons2 = pd.read_excel(path, sheet_name="test1", index_col=0) + recons2 = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) tm.assert_frame_equal(int_frame, recons2) @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64]) - def test_float_types(self, np_type, path): + def test_float_types(self, np_type, tmp_excel): # Test np.float values read come back as float. df = DataFrame(np.random.default_rng(2).random(10), dtype=np_type) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np_type ) tm.assert_frame_equal(df, recons) - def test_bool_types(self, path): + def test_bool_types(self, tmp_excel): # Test np.bool_ values read come back as float. df = DataFrame([1, 0, True, False], dtype=np.bool_) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.bool_ ) tm.assert_frame_equal(df, recons) - def test_inf_roundtrip(self, path): + def test_inf_roundtrip(self, tmp_excel): df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)]) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(df, recons) - def test_sheets(self, frame, path): + def test_sheets(self, frame, tmp_excel): # freq doesn't round-trip - unit = get_exp_unit(path) + unit = get_exp_unit(tmp_excel) tsframe = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), columns=Index(list("ABCD")), @@ -572,16 +569,16 @@ def test_sheets(self, frame, path): frame = frame.copy() frame.iloc[:5, frame.columns.get_loc("A")] = np.nan - frame.to_excel(path, sheet_name="test1") - frame.to_excel(path, sheet_name="test1", columns=["A", "B"]) - frame.to_excel(path, sheet_name="test1", header=False) - frame.to_excel(path, sheet_name="test1", index=False) + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) # Test writing to separate sheets - with ExcelWriter(path) as writer: + with ExcelWriter(tmp_excel) as writer: frame.to_excel(writer, sheet_name="test1") tsframe.to_excel(writer, sheet_name="test2") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) recons = pd.read_excel(reader, sheet_name="test2", index_col=0) @@ -590,39 +587,39 @@ def test_sheets(self, frame, path): assert "test1" == reader.sheet_names[0] assert "test2" == reader.sheet_names[1] - def test_colaliases(self, frame, path): + def test_colaliases(self, frame, tmp_excel): frame = frame.copy() frame.iloc[:5, frame.columns.get_loc("A")] = np.nan - frame.to_excel(path, sheet_name="test1") - frame.to_excel(path, sheet_name="test1", columns=["A", "B"]) - frame.to_excel(path, sheet_name="test1", header=False) - frame.to_excel(path, sheet_name="test1", index=False) + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) # column aliases col_aliases = Index(["AA", "X", "Y", "Z"]) - frame.to_excel(path, sheet_name="test1", header=col_aliases) - with ExcelFile(path) as reader: + frame.to_excel(tmp_excel, sheet_name="test1", header=col_aliases) + with ExcelFile(tmp_excel) as reader: rs = pd.read_excel(reader, sheet_name="test1", index_col=0) xp = frame.copy() xp.columns = col_aliases tm.assert_frame_equal(xp, rs) - def test_roundtrip_indexlabels(self, merge_cells, frame, path): + def test_roundtrip_indexlabels(self, merge_cells, frame, tmp_excel): frame = frame.copy() frame.iloc[:5, frame.columns.get_loc("A")] = np.nan - frame.to_excel(path, sheet_name="test1") - frame.to_excel(path, sheet_name="test1", columns=["A", "B"]) - frame.to_excel(path, sheet_name="test1", header=False) - frame.to_excel(path, sheet_name="test1", index=False) + frame.to_excel(tmp_excel, sheet_name="test1") + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", index=False) # test index_label df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0 df.to_excel( - path, sheet_name="test1", index_label=["test"], merge_cells=merge_cells + tmp_excel, sheet_name="test1", index_label=["test"], merge_cells=merge_cells ) - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) @@ -631,12 +628,12 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path): df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0 df.to_excel( - path, + tmp_excel, sheet_name="test1", index_label=["test", "dummy", "dummy2"], merge_cells=merge_cells, ) - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) @@ -645,9 +642,9 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path): df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0 df.to_excel( - path, sheet_name="test1", index_label="test", merge_cells=merge_cells + tmp_excel, sheet_name="test1", index_label="test", merge_cells=merge_cells ) - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype( np.int64 ) @@ -655,7 +652,7 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path): tm.assert_frame_equal(df, recons.astype(bool)) frame.to_excel( - path, + tmp_excel, sheet_name="test1", columns=["A", "B", "C", "D"], index=False, @@ -665,25 +662,25 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path): df = frame.copy() df = df.set_index(["A", "B"]) - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(df, recons) - def test_excel_roundtrip_indexname(self, merge_cells, path): + def test_excel_roundtrip_indexname(self, merge_cells, tmp_excel): df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))) df.index.name = "foo" - df.to_excel(path, merge_cells=merge_cells) + df.to_excel(tmp_excel, merge_cells=merge_cells) - with ExcelFile(path) as xf: + with ExcelFile(tmp_excel) as xf: result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0) tm.assert_frame_equal(result, df) assert result.index.name == "foo" - def test_excel_roundtrip_datetime(self, merge_cells, path): + def test_excel_roundtrip_datetime(self, merge_cells, tmp_excel): # datetime.date, not sure what to test here exactly - unit = get_exp_unit(path) + unit = get_exp_unit(tmp_excel) # freq does not round-trip tsframe = DataFrame( @@ -697,20 +694,20 @@ def test_excel_roundtrip_datetime(self, merge_cells, path): tsf = tsframe.copy() tsf.index = [x.date() for x in tsframe.index] - tsf.to_excel(path, sheet_name="test1", merge_cells=merge_cells) + tsf.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = tsframe[:] expected.index = expected.index.as_unit(unit) tm.assert_frame_equal(expected, recons) - def test_excel_date_datetime_format(self, ext, path): + def test_excel_date_datetime_format(self, ext, tmp_excel, tmp_path): # see gh-4133 # # Excel output format strings - unit = get_exp_unit(path) + unit = get_exp_unit(tmp_excel) df = DataFrame( [ @@ -730,22 +727,23 @@ def test_excel_date_datetime_format(self, ext, path): ) df_expected = df_expected.astype(f"M8[{unit}]") - with tm.ensure_clean(ext) as filename2: - with ExcelWriter(path) as writer1: - df.to_excel(writer1, sheet_name="test1") + filename2 = tmp_path / f"tmp2{ext}" + filename2.touch() + with ExcelWriter(tmp_excel) as writer1: + df.to_excel(writer1, sheet_name="test1") - with ExcelWriter( - filename2, - date_format="DD.MM.YYYY", - datetime_format="DD.MM.YYYY HH-MM-SS", - ) as writer2: - df.to_excel(writer2, sheet_name="test1") + with ExcelWriter( + filename2, + date_format="DD.MM.YYYY", + datetime_format="DD.MM.YYYY HH-MM-SS", + ) as writer2: + df.to_excel(writer2, sheet_name="test1") - with ExcelFile(path) as reader1: - rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) + with ExcelFile(tmp_excel) as reader1: + rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) - with ExcelFile(filename2) as reader2: - rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) + with ExcelFile(filename2) as reader2: + rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) tm.assert_frame_equal(rs1, rs2) @@ -753,7 +751,7 @@ def test_excel_date_datetime_format(self, ext, path): # we need to use df_expected to check the result. tm.assert_frame_equal(rs2, df_expected) - def test_to_excel_interval_no_labels(self, path, using_infer_string): + def test_to_excel_interval_no_labels(self, tmp_excel, using_infer_string): # see gh-19242 # # Test writing Interval without labels. @@ -767,12 +765,12 @@ def test_to_excel_interval_no_labels(self, path, using_infer_string): str if not using_infer_string else "string[pyarrow_numpy]" ) - df.to_excel(path, sheet_name="test1") - with ExcelFile(path) as reader: + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) - def test_to_excel_interval_labels(self, path): + def test_to_excel_interval_labels(self, tmp_excel): # see gh-19242 # # Test writing Interval with labels. @@ -786,12 +784,12 @@ def test_to_excel_interval_labels(self, path): df["new"] = intervals expected["new"] = pd.Series(list(intervals)) - df.to_excel(path, sheet_name="test1") - with ExcelFile(path) as reader: + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) - def test_to_excel_timedelta(self, path): + def test_to_excel_timedelta(self, tmp_excel): # see gh-19242, gh-9155 # # Test writing timedelta to xls. @@ -807,12 +805,12 @@ def test_to_excel_timedelta(self, path): lambda x: timedelta(seconds=x).total_seconds() / 86400 ) - df.to_excel(path, sheet_name="test1") - with ExcelFile(path) as reader: + df.to_excel(tmp_excel, sheet_name="test1") + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(expected, recons) - def test_to_excel_periodindex(self, path): + def test_to_excel_periodindex(self, tmp_excel): # xp has a PeriodIndex df = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), @@ -821,28 +819,28 @@ def test_to_excel_periodindex(self, path): ) xp = df.resample("ME").mean().to_period("M") - xp.to_excel(path, sheet_name="sht1") + xp.to_excel(tmp_excel, sheet_name="sht1") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: rs = pd.read_excel(reader, sheet_name="sht1", index_col=0) tm.assert_frame_equal(xp, rs.to_period("M")) - def test_to_excel_multiindex(self, merge_cells, frame, path): + def test_to_excel_multiindex(self, merge_cells, frame, tmp_excel): arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index - frame.to_excel(path, sheet_name="test1", header=False) - frame.to_excel(path, sheet_name="test1", columns=["A", "B"]) + frame.to_excel(tmp_excel, sheet_name="test1", header=False) + frame.to_excel(tmp_excel, sheet_name="test1", columns=["A", "B"]) # round trip - frame.to_excel(path, sheet_name="test1", merge_cells=merge_cells) - with ExcelFile(path) as reader: + frame.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + with ExcelFile(tmp_excel) as reader: df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(frame, df) # GH13511 - def test_to_excel_multiindex_nan_label(self, merge_cells, path): + def test_to_excel_multiindex_nan_label(self, merge_cells, tmp_excel): df = DataFrame( { "A": [None, 2, 3], @@ -852,14 +850,14 @@ def test_to_excel_multiindex_nan_label(self, merge_cells, path): ) df = df.set_index(["A", "B"]) - df.to_excel(path, merge_cells=merge_cells) - df1 = pd.read_excel(path, index_col=[0, 1]) + df.to_excel(tmp_excel, merge_cells=merge_cells) + df1 = pd.read_excel(tmp_excel, index_col=[0, 1]) tm.assert_frame_equal(df, df1) # Test for Issue 11328. If column indices are integers, make # sure they are handled correctly for either setting of # merge_cells - def test_to_excel_multiindex_cols(self, merge_cells, frame, path): + def test_to_excel_multiindex_cols(self, merge_cells, frame, tmp_excel): arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index @@ -871,8 +869,8 @@ def test_to_excel_multiindex_cols(self, merge_cells, frame, path): header = 0 # round trip - frame.to_excel(path, sheet_name="test1", merge_cells=merge_cells) - with ExcelFile(path) as reader: + frame.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + with ExcelFile(tmp_excel) as reader: df = pd.read_excel( reader, sheet_name="test1", header=header, index_col=[0, 1] ) @@ -881,9 +879,9 @@ def test_to_excel_multiindex_cols(self, merge_cells, frame, path): frame.columns = [".".join(map(str, q)) for q in zip(*fm)] tm.assert_frame_equal(frame, df) - def test_to_excel_multiindex_dates(self, merge_cells, path): + def test_to_excel_multiindex_dates(self, merge_cells, tmp_excel): # try multiindex with dates - unit = get_exp_unit(path) + unit = get_exp_unit(tmp_excel) tsframe = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), columns=Index(list("ABCD")), @@ -897,14 +895,14 @@ def test_to_excel_multiindex_dates(self, merge_cells, path): names=["time", "foo"], ) - tsframe.to_excel(path, sheet_name="test1", merge_cells=merge_cells) - with ExcelFile(path) as reader: + tsframe.to_excel(tmp_excel, sheet_name="test1", merge_cells=merge_cells) + with ExcelFile(tmp_excel) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) tm.assert_frame_equal(tsframe, recons) assert recons.index.names == ("time", "foo") - def test_to_excel_multiindex_no_write_index(self, path): + def test_to_excel_multiindex_no_write_index(self, tmp_excel): # Test writing and re-reading a MI without the index. GH 5616. # Initial non-MI frame. @@ -916,37 +914,37 @@ def test_to_excel_multiindex_no_write_index(self, path): frame2.index = multi_index # Write out to Excel without the index. - frame2.to_excel(path, sheet_name="test1", index=False) + frame2.to_excel(tmp_excel, sheet_name="test1", index=False) # Read it back in. - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: frame3 = pd.read_excel(reader, sheet_name="test1") # Test that it is the same as the initial frame. tm.assert_frame_equal(frame1, frame3) - def test_to_excel_empty_multiindex(self, path): + def test_to_excel_empty_multiindex(self, tmp_excel): # GH 19543. expected = DataFrame([], columns=[0, 1, 2]) df = DataFrame([], index=MultiIndex.from_tuples([], names=[0, 1]), columns=[2]) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: result = pd.read_excel(reader, sheet_name="test1") tm.assert_frame_equal( result, expected, check_index_type=False, check_dtype=False ) - def test_to_excel_float_format(self, path): + def test_to_excel_float_format(self, tmp_excel): df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], index=["A", "B"], columns=["X", "Y", "Z"], ) - df.to_excel(path, sheet_name="test1", float_format="%.2f") + df.to_excel(tmp_excel, sheet_name="test1", float_format="%.2f") - with ExcelFile(path) as reader: + with ExcelFile(tmp_excel) as reader: result = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = DataFrame( @@ -956,7 +954,7 @@ def test_to_excel_float_format(self, path): ) tm.assert_frame_equal(result, expected) - def test_to_excel_output_encoding(self, ext): + def test_to_excel_output_encoding(self, tmp_excel): # Avoid mixed inferred_type. df = DataFrame( [["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]], @@ -964,28 +962,22 @@ def test_to_excel_output_encoding(self, ext): columns=["X\u0193", "Y", "Z"], ) - with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename: - df.to_excel(filename, sheet_name="TestSheet") - result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0) - tm.assert_frame_equal(result, df) - - def test_to_excel_unicode_filename(self, ext): - with tm.ensure_clean("\u0192u." + ext) as filename: - try: - with open(filename, "wb"): - pass - except UnicodeEncodeError: - pytest.skip("No unicode file names on this system") + df.to_excel(tmp_excel, sheet_name="TestSheet") + result = pd.read_excel(tmp_excel, sheet_name="TestSheet", index_col=0) + tm.assert_frame_equal(result, df) - df = DataFrame( - [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], - index=["A", "B"], - columns=["X", "Y", "Z"], - ) - df.to_excel(filename, sheet_name="test1", float_format="%.2f") + def test_to_excel_unicode_filename(self, ext, tmp_path): + filename = tmp_path / f"\u0192u.{ext}" + filename.touch() + df = DataFrame( + [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + df.to_excel(filename, sheet_name="test1", float_format="%.2f") - with ExcelFile(filename) as reader: - result = pd.read_excel(reader, sheet_name="test1", index_col=0) + with ExcelFile(filename) as reader: + result = pd.read_excel(reader, sheet_name="test1", index_col=0) expected = DataFrame( [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], @@ -998,12 +990,14 @@ def test_to_excel_unicode_filename(self, ext): @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3]) @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3]) def test_excel_010_hemstring( - self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, path + self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, tmp_excel ): def roundtrip(data, header=True, parser_hdr=0, index=True): - data.to_excel(path, header=header, merge_cells=merge_cells, index=index) + data.to_excel( + tmp_excel, header=header, merge_cells=merge_cells, index=index + ) - with ExcelFile(path) as xf: + with ExcelFile(tmp_excel) as xf: return pd.read_excel( xf, sheet_name=xf.sheet_names[0], header=parser_hdr ) @@ -1066,56 +1060,56 @@ def roundtrip(data, header=True, parser_hdr=0, index=True): for c in range(len(res.columns)): assert res.iloc[r, c] is not np.nan - def test_duplicated_columns(self, path): + def test_duplicated_columns(self, tmp_excel): # see gh-5235 df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"]) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") expected = DataFrame( [[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"] ) # By default, we mangle. - result = pd.read_excel(path, sheet_name="test1", index_col=0) + result = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) tm.assert_frame_equal(result, expected) # see gh-11007, gh-10970 df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"]) - df.to_excel(path, sheet_name="test1") + df.to_excel(tmp_excel, sheet_name="test1") - result = pd.read_excel(path, sheet_name="test1", index_col=0) + result = pd.read_excel(tmp_excel, sheet_name="test1", index_col=0) expected = DataFrame( [[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"] ) tm.assert_frame_equal(result, expected) # see gh-10982 - df.to_excel(path, sheet_name="test1", index=False, header=False) - result = pd.read_excel(path, sheet_name="test1", header=None) + df.to_excel(tmp_excel, sheet_name="test1", index=False, header=False) + result = pd.read_excel(tmp_excel, sheet_name="test1", header=None) expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]) tm.assert_frame_equal(result, expected) - def test_swapped_columns(self, path): + def test_swapped_columns(self, tmp_excel): # Test for issue #5427. write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) - write_frame.to_excel(path, sheet_name="test1", columns=["B", "A"]) + write_frame.to_excel(tmp_excel, sheet_name="test1", columns=["B", "A"]) - read_frame = pd.read_excel(path, sheet_name="test1", header=0) + read_frame = pd.read_excel(tmp_excel, sheet_name="test1", header=0) tm.assert_series_equal(write_frame["A"], read_frame["A"]) tm.assert_series_equal(write_frame["B"], read_frame["B"]) - def test_invalid_columns(self, path): + def test_invalid_columns(self, tmp_excel): # see gh-10982 write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]}) with pytest.raises(KeyError, match="Not all names specified"): - write_frame.to_excel(path, sheet_name="test1", columns=["B", "C"]) + write_frame.to_excel(tmp_excel, sheet_name="test1", columns=["B", "C"]) with pytest.raises( KeyError, match="'passes columns are not ALL present dataframe'" ): - write_frame.to_excel(path, sheet_name="test1", columns=["C", "D"]) + write_frame.to_excel(tmp_excel, sheet_name="test1", columns=["C", "D"]) @pytest.mark.parametrize( "to_excel_index,read_excel_index_col", @@ -1124,81 +1118,88 @@ def test_invalid_columns(self, path): (False, None), # Dont include index in write to file ], ) - def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col): + def test_write_subset_columns( + self, tmp_excel, to_excel_index, read_excel_index_col + ): # GH 31677 write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]}) write_frame.to_excel( - path, sheet_name="col_subset_bug", columns=["A", "B"], index=to_excel_index + tmp_excel, + sheet_name="col_subset_bug", + columns=["A", "B"], + index=to_excel_index, ) expected = write_frame[["A", "B"]] read_frame = pd.read_excel( - path, sheet_name="col_subset_bug", index_col=read_excel_index_col + tmp_excel, sheet_name="col_subset_bug", index_col=read_excel_index_col ) tm.assert_frame_equal(expected, read_frame) - def test_comment_arg(self, path): + def test_comment_arg(self, tmp_excel): # see gh-18735 # # Test the comment argument functionality to pd.read_excel. # Create file to read in. df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) - df.to_excel(path, sheet_name="test_c") + df.to_excel(tmp_excel, sheet_name="test_c") # Read file without comment arg. - result1 = pd.read_excel(path, sheet_name="test_c", index_col=0) + result1 = pd.read_excel(tmp_excel, sheet_name="test_c", index_col=0) result1.iloc[1, 0] = None result1.iloc[1, 1] = None result1.iloc[2, 1] = None - result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0) + result2 = pd.read_excel( + tmp_excel, sheet_name="test_c", comment="#", index_col=0 + ) tm.assert_frame_equal(result1, result2) - def test_comment_default(self, path): + def test_comment_default(self, tmp_excel): # Re issue #18735 # Test the comment argument default to pd.read_excel # Create file to read in df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) - df.to_excel(path, sheet_name="test_c") + df.to_excel(tmp_excel, sheet_name="test_c") # Read file with default and explicit comment=None - result1 = pd.read_excel(path, sheet_name="test_c") - result2 = pd.read_excel(path, sheet_name="test_c", comment=None) + result1 = pd.read_excel(tmp_excel, sheet_name="test_c") + result2 = pd.read_excel(tmp_excel, sheet_name="test_c", comment=None) tm.assert_frame_equal(result1, result2) - def test_comment_used(self, path): + def test_comment_used(self, tmp_excel): # see gh-18735 # # Test the comment argument is working as expected when used. # Create file to read in. df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]}) - df.to_excel(path, sheet_name="test_c") + df.to_excel(tmp_excel, sheet_name="test_c") # Test read_frame_comment against manually produced expected output. expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]}) - result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0) + result = pd.read_excel(tmp_excel, sheet_name="test_c", comment="#", index_col=0) tm.assert_frame_equal(result, expected) - def test_comment_empty_line(self, path): + def test_comment_empty_line(self, tmp_excel): # Re issue #18735 # Test that pd.read_excel ignores commented lines at the end of file df = DataFrame({"a": ["1", "#2"], "b": ["2", "3"]}) - df.to_excel(path, index=False) + df.to_excel(tmp_excel, index=False) # Test that all-comment lines at EoF are ignored expected = DataFrame({"a": [1], "b": [2]}) - result = pd.read_excel(path, comment="#") + result = pd.read_excel(tmp_excel, comment="#") tm.assert_frame_equal(result, expected) - def test_datetimes(self, path): + def test_datetimes(self, tmp_excel): # Test writing and reading datetimes. For issue #9139. (xref #9185) - unit = get_exp_unit(path) + unit = get_exp_unit(tmp_excel) datetimes = [ datetime(2013, 1, 13, 1, 2, 3), datetime(2013, 1, 13, 2, 45, 56), @@ -1214,8 +1215,8 @@ def test_datetimes(self, path): ] write_frame = DataFrame({"A": datetimes}) - write_frame.to_excel(path, sheet_name="Sheet1") - read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0) + write_frame.to_excel(tmp_excel, sheet_name="Sheet1") + read_frame = pd.read_excel(tmp_excel, sheet_name="Sheet1", header=0) expected = write_frame.astype(f"M8[{unit}]") tm.assert_series_equal(expected["A"], read_frame["A"]) @@ -1233,7 +1234,7 @@ def test_bytes_io(self, engine): reread_df = pd.read_excel(bio, index_col=0) tm.assert_frame_equal(df, reread_df) - def test_engine_kwargs(self, engine, path): + def test_engine_kwargs(self, engine, tmp_excel): # GH#52368 df = DataFrame([{"A": 1, "B": 2}, {"A": 3, "B": 4}]) @@ -1253,19 +1254,19 @@ def test_engine_kwargs(self, engine, path): ] = "Workbook.__init__() got an unexpected keyword argument 'foo'" # Handle change in error message for openpyxl (write and append mode) - if engine == "openpyxl" and not os.path.exists(path): + if engine == "openpyxl" and not os.path.exists(tmp_excel): msgs[ "openpyxl" ] = r"load_workbook() got an unexpected keyword argument 'foo'" with pytest.raises(TypeError, match=re.escape(msgs[engine])): df.to_excel( - path, + tmp_excel, engine=engine, engine_kwargs={"foo": "bar"}, ) - def test_write_lists_dict(self, path): + def test_write_lists_dict(self, tmp_excel): # see gh-8188. df = DataFrame( { @@ -1274,8 +1275,8 @@ def test_write_lists_dict(self, path): "str": ["apple", "banana", "cherry"], } ) - df.to_excel(path, sheet_name="Sheet1") - read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0) + df.to_excel(tmp_excel, sheet_name="Sheet1") + read = pd.read_excel(tmp_excel, sheet_name="Sheet1", header=0, index_col=0) expected = df.copy() expected.mixed = expected.mixed.apply(str) @@ -1283,32 +1284,32 @@ def test_write_lists_dict(self, path): tm.assert_frame_equal(read, expected) - def test_render_as_column_name(self, path): + def test_render_as_column_name(self, tmp_excel): # see gh-34331 df = DataFrame({"render": [1, 2], "data": [3, 4]}) - df.to_excel(path, sheet_name="Sheet1") - read = pd.read_excel(path, "Sheet1", index_col=0) + df.to_excel(tmp_excel, sheet_name="Sheet1") + read = pd.read_excel(tmp_excel, "Sheet1", index_col=0) expected = df tm.assert_frame_equal(read, expected) - def test_true_and_false_value_options(self, path): + def test_true_and_false_value_options(self, tmp_excel): # see gh-13347 df = DataFrame([["foo", "bar"]], columns=["col1", "col2"], dtype=object) with option_context("future.no_silent_downcasting", True): expected = df.replace({"foo": True, "bar": False}).astype("bool") - df.to_excel(path) + df.to_excel(tmp_excel) read_frame = pd.read_excel( - path, true_values=["foo"], false_values=["bar"], index_col=0 + tmp_excel, true_values=["foo"], false_values=["bar"], index_col=0 ) tm.assert_frame_equal(read_frame, expected) - def test_freeze_panes(self, path): + def test_freeze_panes(self, tmp_excel): # see gh-15160 expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"]) - expected.to_excel(path, sheet_name="Sheet1", freeze_panes=(1, 1)) + expected.to_excel(tmp_excel, sheet_name="Sheet1", freeze_panes=(1, 1)) - result = pd.read_excel(path, index_col=0) + result = pd.read_excel(tmp_excel, index_col=0) tm.assert_frame_equal(result, expected) def test_path_path_lib(self, engine, ext): @@ -1323,7 +1324,7 @@ def test_path_path_lib(self, engine, ext): result = tm.round_trip_pathlib(writer, reader, path=f"foo{ext}") tm.assert_frame_equal(result, df) - def test_merged_cell_custom_objects(self, path): + def test_merged_cell_custom_objects(self, tmp_excel): # see GH-27006 mi = MultiIndex.from_tuples( [ @@ -1332,8 +1333,8 @@ def test_merged_cell_custom_objects(self, path): ] ) expected = DataFrame(np.ones((2, 2), dtype="int64"), columns=mi) - expected.to_excel(path) - result = pd.read_excel(path, header=[0, 1], index_col=0) + expected.to_excel(tmp_excel) + result = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) # need to convert PeriodIndexes to standard Indexes for assert equal expected.columns = expected.columns.set_levels( [[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]], @@ -1342,56 +1343,51 @@ def test_merged_cell_custom_objects(self, path): tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [None, object]) - def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path): + def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, tmp_excel): # GH 27008, GH 7056 tz = tz_aware_fixture data = pd.Timestamp("2019", tz=tz) df = DataFrame([data], dtype=dtype) with pytest.raises(ValueError, match="Excel does not support"): - df.to_excel(path) + df.to_excel(tmp_excel) data = data.to_pydatetime() df = DataFrame([data], dtype=dtype) with pytest.raises(ValueError, match="Excel does not support"): - df.to_excel(path) + df.to_excel(tmp_excel) - def test_excel_duplicate_columns_with_names(self, path): + def test_excel_duplicate_columns_with_names(self, tmp_excel): # GH#39695 df = DataFrame({"A": [0, 1], "B": [10, 11]}) - df.to_excel(path, columns=["A", "B", "A"], index=False) + df.to_excel(tmp_excel, columns=["A", "B", "A"], index=False) - result = pd.read_excel(path) + result = pd.read_excel(tmp_excel) expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"]) tm.assert_frame_equal(result, expected) - def test_if_sheet_exists_raises(self, ext): + def test_if_sheet_exists_raises(self, tmp_excel): # GH 40230 msg = "if_sheet_exists is only valid in append mode (mode='a')" - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=re.escape(msg)): - ExcelWriter(f, if_sheet_exists="replace") + with pytest.raises(ValueError, match=re.escape(msg)): + ExcelWriter(tmp_excel, if_sheet_exists="replace") - def test_excel_writer_empty_frame(self, engine, ext): + def test_excel_writer_empty_frame(self, engine, tmp_excel): # GH#45793 - with tm.ensure_clean(ext) as path: - with ExcelWriter(path, engine=engine) as writer: - DataFrame().to_excel(writer) - result = pd.read_excel(path) - expected = DataFrame() - tm.assert_frame_equal(result, expected) - - def test_to_excel_empty_frame(self, engine, ext): + with ExcelWriter(tmp_excel, engine=engine) as writer: + DataFrame().to_excel(writer) + result = pd.read_excel(tmp_excel) + expected = DataFrame() + tm.assert_frame_equal(result, expected) + + def test_to_excel_empty_frame(self, engine, tmp_excel): # GH#45793 - with tm.ensure_clean(ext) as path: - DataFrame().to_excel(path, engine=engine) - result = pd.read_excel(path) - expected = DataFrame() - tm.assert_frame_equal(result, expected) - - def test_to_excel_raising_warning_when_cell_character_exceed_limit( - self, path, engine - ): + DataFrame().to_excel(tmp_excel, engine=engine) + result = pd.read_excel(tmp_excel) + expected = DataFrame() + tm.assert_frame_equal(result, expected) + + def test_to_excel_raising_warning_when_cell_character_exceed_limit(self): # GH#56954 df = DataFrame({"A": ["a" * 32768]}) msg = "Cell contents too long, truncated to 32767 characters" @@ -1410,22 +1406,21 @@ class TestExcelWriterEngineTests: pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")), ], ) - def test_ExcelWriter_dispatch(self, klass, ext): - with tm.ensure_clean(ext) as path: - with ExcelWriter(path) as writer: - if ext == ".xlsx" and bool( - import_optional_dependency("xlsxwriter", errors="ignore") - ): - # xlsxwriter has preference over openpyxl if both installed - assert isinstance(writer, _XlsxWriter) - else: - assert isinstance(writer, klass) + def test_ExcelWriter_dispatch(self, klass, ext, tmp_excel): + with ExcelWriter(tmp_excel) as writer: + if ext == ".xlsx" and bool( + import_optional_dependency("xlsxwriter", errors="ignore") + ): + # xlsxwriter has preference over openpyxl if both installed + assert isinstance(writer, _XlsxWriter) + else: + assert isinstance(writer, klass) def test_ExcelWriter_dispatch_raises(self): with pytest.raises(ValueError, match="No engine"): ExcelWriter("nothing") - def test_register_writer(self): + def test_register_writer(self, tmp_path): class DummyClass(ExcelWriter): called_save = False called_write_cells = False @@ -1457,38 +1452,41 @@ def assert_called_and_reset(cls): register_writer(DummyClass) with option_context("io.excel.xlsx.writer", "dummy"): - path = "something.xlsx" - with tm.ensure_clean(path) as filepath: - with ExcelWriter(filepath) as writer: - assert isinstance(writer, DummyClass) - df = DataFrame( - ["a"], - columns=Index(["b"], name="foo"), - index=Index(["c"], name="bar"), - ) - df.to_excel(filepath) + filepath = tmp_path / "something.xlsx" + filepath.touch() + with ExcelWriter(filepath) as writer: + assert isinstance(writer, DummyClass) + df = DataFrame( + ["a"], + columns=Index(["b"], name="foo"), + index=Index(["c"], name="bar"), + ) + df.to_excel(filepath) DummyClass.assert_called_and_reset() - with tm.ensure_clean("something.xls") as filepath: - df.to_excel(filepath, engine="dummy") + filepath2 = tmp_path / "something2.xlsx" + filepath2.touch() + df.to_excel(filepath2, engine="dummy") DummyClass.assert_called_and_reset() @td.skip_if_no("xlrd") @td.skip_if_no("openpyxl") class TestFSPath: - def test_excelfile_fspath(self): - with tm.ensure_clean("foo.xlsx") as path: - df = DataFrame({"A": [1, 2]}) - df.to_excel(path) - with ExcelFile(path) as xl: - result = os.fspath(xl) - assert result == path - - def test_excelwriter_fspath(self): - with tm.ensure_clean("foo.xlsx") as path: - with ExcelWriter(path) as writer: - assert os.fspath(writer) == str(path) + def test_excelfile_fspath(self, tmp_path): + path = tmp_path / "foo.xlsx" + path.touch() + df = DataFrame({"A": [1, 2]}) + df.to_excel(path) + with ExcelFile(path) as xl: + result = os.fspath(xl) + assert result == str(path) + + def test_excelwriter_fspath(self, tmp_path): + path = tmp_path / "foo.xlsx" + path.touch() + with ExcelWriter(path) as writer: + assert os.fspath(writer) == str(path) @pytest.mark.parametrize("klass", _writers.values()) diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index edabbad93acbc..c49cbaf7fb26c 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -3,8 +3,6 @@ import numpy as np import pytest -from pandas.compat import is_platform_windows - import pandas as pd import pandas._testing as tm @@ -13,9 +11,6 @@ xlrd = pytest.importorskip("xlrd") -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - @pytest.fixture def read_ext_xlrd(): diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index 529367761fc02..b2e6c845e5019 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -1,86 +1,86 @@ import contextlib +import uuid import pytest -from pandas.compat import is_platform_windows - from pandas import DataFrame -import pandas._testing as tm from pandas.io.excel import ExcelWriter xlsxwriter = pytest.importorskip("xlsxwriter") -if is_platform_windows(): - pytestmark = pytest.mark.single_cpu - @pytest.fixture def ext(): return ".xlsx" -def test_column_format(ext): +@pytest.fixture +def tmp_excel(ext, tmp_path): + tmp = tmp_path / f"{uuid.uuid4()}{ext}" + tmp.touch() + return str(tmp) + + +def test_column_format(tmp_excel): # Test that column formats are applied to cells. Test for issue #9167. # Applicable to xlsxwriter only. openpyxl = pytest.importorskip("openpyxl") - with tm.ensure_clean(ext) as path: - frame = DataFrame({"A": [123456, 123456], "B": [123456, 123456]}) - - with ExcelWriter(path) as writer: - frame.to_excel(writer) + frame = DataFrame({"A": [123456, 123456], "B": [123456, 123456]}) - # Add a number format to col B and ensure it is applied to cells. - num_format = "#,##0" - write_workbook = writer.book - write_worksheet = write_workbook.worksheets()[0] - col_format = write_workbook.add_format({"num_format": num_format}) - write_worksheet.set_column("B:B", None, col_format) + with ExcelWriter(tmp_excel) as writer: + frame.to_excel(writer) - with contextlib.closing(openpyxl.load_workbook(path)) as read_workbook: - try: - read_worksheet = read_workbook["Sheet1"] - except TypeError: - # compat - read_worksheet = read_workbook.get_sheet_by_name(name="Sheet1") + # Add a number format to col B and ensure it is applied to cells. + num_format = "#,##0" + write_workbook = writer.book + write_worksheet = write_workbook.worksheets()[0] + col_format = write_workbook.add_format({"num_format": num_format}) + write_worksheet.set_column("B:B", None, col_format) - # Get the number format from the cell. + with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as read_workbook: try: - cell = read_worksheet["B2"] + read_worksheet = read_workbook["Sheet1"] except TypeError: # compat - cell = read_worksheet.cell("B2") + read_worksheet = read_workbook.get_sheet_by_name(name="Sheet1") - try: - read_num_format = cell.number_format - except AttributeError: - read_num_format = cell.style.number_format._format_code + # Get the number format from the cell. + try: + cell = read_worksheet["B2"] + except TypeError: + # compat + cell = read_worksheet.cell("B2") + + try: + read_num_format = cell.number_format + except AttributeError: + read_num_format = cell.style.number_format._format_code - assert read_num_format == num_format + assert read_num_format == num_format -def test_write_append_mode_raises(ext): +def test_write_append_mode_raises(tmp_excel): msg = "Append mode is not supported with xlsxwriter!" - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=msg): - ExcelWriter(f, engine="xlsxwriter", mode="a") + with pytest.raises(ValueError, match=msg): + ExcelWriter(tmp_excel, engine="xlsxwriter", mode="a") @pytest.mark.parametrize("nan_inf_to_errors", [True, False]) -def test_engine_kwargs(ext, nan_inf_to_errors): +def test_engine_kwargs(tmp_excel, nan_inf_to_errors): # GH 42286 engine_kwargs = {"options": {"nan_inf_to_errors": nan_inf_to_errors}} - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="xlsxwriter", engine_kwargs=engine_kwargs) as writer: - assert writer.book.nan_inf_to_errors == nan_inf_to_errors + with ExcelWriter( + tmp_excel, engine="xlsxwriter", engine_kwargs=engine_kwargs + ) as writer: + assert writer.book.nan_inf_to_errors == nan_inf_to_errors -def test_book_and_sheets_consistent(ext): +def test_book_and_sheets_consistent(tmp_excel): # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="xlsxwriter") as writer: - assert writer.sheets == {} - sheet = writer.book.add_worksheet("test_name") - assert writer.sheets == {"test_name": sheet} + with ExcelWriter(tmp_excel, engine="xlsxwriter") as writer: + assert writer.sheets == {} + sheet = writer.book.add_worksheet("test_name") + assert writer.sheets == {"test_name": sheet}
- [ ] closes #57511 (Replace xxxx with the GitHub issue number) `tm.ensure_clean` doesn't ensure files are unique if the same name is passed, but `tmp_path` ensures a test gets a unique temp path.
https://api.github.com/repos/pandas-dev/pandas/pulls/57516
2024-02-20T01:19:25Z
2024-02-20T23:32:50Z
2024-02-20T23:32:50Z
2024-02-20T23:32:53Z
Backport PR #57488 on branch 2.2.x (REGR: query raising for all NaT in object column)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index e1da0af59b3b8..6c6a37b2b2f89 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -27,6 +27,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.loc` which was unnecessarily throwing "incompatible dtype warning" when expanding with partial row indexer and multiple columns (see `PDEP6 <https://pandas.pydata.org/pdeps/0006-ban-upcasting.html>`_) (:issue:`56503`) - Fixed regression in :meth:`DataFrame.map` with ``na_action="ignore"`` not being respected for NumPy nullable and :class:`ArrowDtypes` (:issue:`57316`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) +- Fixed regression in :meth:`DataFrame.query` with all ``NaT`` column with object dtype (:issue:`57068`) - Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) - Fixed regression in :meth:`DataFrame.sort_index` not producing a stable sort for a index with duplicates (:issue:`57151`) - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 62dd0c3bf0161..0ec17173287f5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -657,7 +657,7 @@ def _get_cleaned_column_resolvers(self) -> dict[Hashable, Series]: return { clean_column_name(k): Series( - v, copy=False, index=self.index, name=k + v, copy=False, index=self.index, name=k, dtype=self.dtypes[k] ).__finalize__(self) for k, v in zip(self.columns, self._iter_column_arrays()) if not isinstance(k, int) diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index a498296e09c52..2c807c72582c5 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -1415,3 +1415,11 @@ def test_query_ea_equality_comparison(self, dtype, engine): } ) tm.assert_frame_equal(result, expected) + + def test_all_nat_in_object(self): + # GH#57068 + now = pd.Timestamp.now("UTC") # noqa: F841 + df = DataFrame({"a": pd.to_datetime([None, None], utc=True)}, dtype=object) + result = df.query("a > @now") + expected = DataFrame({"a": []}, dtype=object) + tm.assert_frame_equal(result, expected)
Backport PR #57488: REGR: query raising for all NaT in object column
https://api.github.com/repos/pandas-dev/pandas/pulls/57515
2024-02-19T23:36:40Z
2024-02-20T01:20:20Z
2024-02-20T01:20:20Z
2024-02-20T01:20:21Z
CoW: Clean up some copy usage
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 55421090d4202..f3a82e268c732 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -378,7 +378,7 @@ def eval( try: target = env.target if isinstance(target, NDFrame): - target = target.copy(deep=None) + target = target.copy(deep=False) else: target = target.copy() except AttributeError as err: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7614951566bf9..f41e03b2129f0 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7488,7 +7488,7 @@ def replace( if not self.size: if inplace: return None - return self.copy(deep=None) + return self.copy(deep=False) if is_dict_like(to_replace): if is_dict_like(value): # {'A' : NA} -> {'A' : 0} @@ -10281,7 +10281,7 @@ def shift( fill_value = lib.no_default if periods == 0: - return self.copy(deep=None) + return self.copy(deep=False) if is_list_like(periods) and isinstance(self, ABCSeries): return self.to_frame().shift( diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 3cb7c72431613..f154054526898 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -702,7 +702,7 @@ def _combine(self, blocks: list[Block], index: Index | None = None) -> Self: def nblocks(self) -> int: return len(self.blocks) - def copy(self, deep: bool | None | Literal["all"] = True) -> Self: + def copy(self, deep: bool | Literal["all"] = True) -> Self: """ Make deep or shallow copy of BlockManager @@ -716,7 +716,6 @@ def copy(self, deep: bool | None | Literal["all"] = True) -> Self: ------- BlockManager """ - deep = deep if deep is not None else False # this preserves the notion of view copying of axes if deep: # hit in e.g. tests.io.json.test_pandas diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py index 07447ab827cec..a4cb1e6bea9c9 100644 --- a/pandas/tests/copy_view/test_internals.py +++ b/pandas/tests/copy_view/test_internals.py @@ -70,7 +70,7 @@ def test_iset_splits_blocks_inplace(locs, arr, dtype): ) arr = arr.astype(dtype) df_orig = df.copy() - df2 = df.copy(deep=None) # Trigger a CoW (if enabled, otherwise makes copy) + df2 = df.copy(deep=False) # Trigger a CoW (if enabled, otherwise makes copy) df2._mgr.iset(locs, arr, inplace=True) tm.assert_frame_equal(df, df_orig) diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index e96899d155c54..05207e13c8547 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1243,7 +1243,7 @@ def test_interpolate_creates_copy(): def test_isetitem(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) df_orig = df.copy() - df2 = df.copy(deep=None) # Trigger a CoW + df2 = df.copy(deep=False) # Trigger a CoW df2.isetitem(1, np.array([-1, -2, -3])) # This is inplace assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
- [ ] 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/57513
2024-02-19T23:03:27Z
2024-02-19T23:56:31Z
2024-02-19T23:56:31Z
2024-02-20T00:05:58Z
DOC: Fix xarray example
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 02d173e7543e6..3289d0e34aec4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3120,18 +3120,18 @@ def to_xarray(self): 2 lion mammal 80.5 4 3 monkey mammal NaN 4 - >>> df.to_xarray() + >>> df.to_xarray() # doctest: +SKIP <xarray.Dataset> Dimensions: (index: 4) Coordinates: - * index (index) int64 0 1 2 3 + * index (index) int64 32B 0 1 2 3 Data variables: - name (index) object 'falcon' 'parrot' 'lion' 'monkey' - class (index) object 'bird' 'bird' 'mammal' 'mammal' - max_speed (index) float64 389.0 24.0 80.5 nan - num_legs (index) int64 2 2 4 4 + name (index) object 32B 'falcon' 'parrot' 'lion' 'monkey' + class (index) object 32B 'bird' 'bird' 'mammal' 'mammal' + max_speed (index) float64 32B 389.0 24.0 80.5 nan + num_legs (index) int64 32B 2 2 4 4 - >>> df["max_speed"].to_xarray() + >>> df["max_speed"].to_xarray() # doctest: +SKIP <xarray.DataArray 'max_speed' (index: 4)> array([389. , 24. , 80.5, nan]) Coordinates: @@ -3157,7 +3157,7 @@ class (index) object 'bird' 'bird' 'mammal' 'mammal' 2018-01-02 falcon 361 parrot 15 - >>> df_multiindex.to_xarray() + >>> df_multiindex.to_xarray() # doctest: +SKIP <xarray.Dataset> Dimensions: (date: 2, animal: 2) Coordinates:
- [ ] 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/57510
2024-02-19T22:11:36Z
2024-02-20T18:51:06Z
2024-02-20T18:51:06Z
2024-02-20T20:48:10Z
Backport PR #57490 on branch 2.2.x (DOC: Add a few deprecation notes)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 2245359fd8eac..df0251d141984 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -169,6 +169,9 @@ def is_sparse(arr) -> bool: """ Check whether an array-like is a 1-D pandas sparse array. + .. deprecated:: 2.1.0 + Use isinstance(dtype, pd.SparseDtype) instead. + Check that the one-dimensional array-like is a pandas sparse array. Returns True if it is a pandas sparse array, not another type of sparse array. @@ -295,6 +298,9 @@ def is_datetime64tz_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of a DatetimeTZDtype dtype. + .. deprecated:: 2.1.0 + Use isinstance(dtype, pd.DatetimeTZDtype) instead. + Parameters ---------- arr_or_dtype : array-like or dtype @@ -381,6 +387,9 @@ def is_period_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Period dtype. + .. deprecated:: 2.2.0 + Use isinstance(dtype, pd.Period) instead. + Parameters ---------- arr_or_dtype : array-like or dtype @@ -424,6 +433,9 @@ def is_interval_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Interval dtype. + .. deprecated:: 2.2.0 + Use isinstance(dtype, pd.IntervalDtype) instead. + Parameters ---------- arr_or_dtype : array-like or dtype @@ -470,6 +482,9 @@ def is_categorical_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Categorical dtype. + .. deprecated:: 2.2.0 + Use isinstance(dtype, pd.CategoricalDtype) instead. + Parameters ---------- arr_or_dtype : array-like or dtype
Backport PR #57490: DOC: Add a few deprecation notes
https://api.github.com/repos/pandas-dev/pandas/pulls/57509
2024-02-19T20:15:32Z
2024-02-19T22:12:25Z
2024-02-19T22:12:25Z
2024-02-19T22:12:25Z
Backport PR #57486 on branch 2.2.x (CI: Run excel tests on single cpu for windows)
diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py index f01827fa4ca2f..b5bb9b27258d8 100644 --- a/pandas/tests/io/excel/test_odf.py +++ b/pandas/tests/io/excel/test_odf.py @@ -3,11 +3,16 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd import pandas._testing as tm pytest.importorskip("odf") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture(autouse=True) def cd_and_set_engine(monkeypatch, datapath): diff --git a/pandas/tests/io/excel/test_odswriter.py b/pandas/tests/io/excel/test_odswriter.py index 271353a173d2a..1c728ad801bc1 100644 --- a/pandas/tests/io/excel/test_odswriter.py +++ b/pandas/tests/io/excel/test_odswriter.py @@ -6,6 +6,8 @@ import pytest +from pandas.compat import is_platform_windows + import pandas as pd import pandas._testing as tm @@ -13,6 +15,9 @@ odf = pytest.importorskip("odf") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def ext(): diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 2df9ec9e53516..e53b5830ec6a4 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd from pandas import DataFrame import pandas._testing as tm @@ -17,6 +19,9 @@ openpyxl = pytest.importorskip("openpyxl") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def ext(): diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 15712f36da4ca..8da8535952dcf 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -18,6 +18,7 @@ from pandas._config import using_pyarrow_string_dtype +from pandas.compat import is_platform_windows import pandas.util._test_decorators as td import pandas as pd @@ -34,6 +35,9 @@ StringArray, ) +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"] engine_params = [ # Add any engines to test here diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 3ca8637885639..89615172688d7 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows import pandas.util._test_decorators as td from pandas import ( @@ -20,6 +21,9 @@ # could compute styles and render to excel without jinja2, since there is no # 'template' file, but this needs the import error to delayed until render time. +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + def assert_equal_cell_styles(cell1, cell2): # TODO: should find a better way to check equality diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 8c003723c1c71..292eab2d88152 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -11,6 +11,7 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows from pandas.compat._constants import PY310 from pandas.compat._optional import import_optional_dependency import pandas.util._test_decorators as td @@ -34,6 +35,9 @@ ) from pandas.io.excel._util import _writers +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + def get_exp_unit(path: str) -> str: return "ns" diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index 6d5008ca9ee68..066393d91eead 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd import pandas._testing as tm @@ -11,6 +13,9 @@ xlrd = pytest.importorskip("xlrd") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture(params=[".xls"]) def read_ext_xlrd(request): diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index 94f6bdfaf069c..529367761fc02 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -2,6 +2,8 @@ import pytest +from pandas.compat import is_platform_windows + from pandas import DataFrame import pandas._testing as tm @@ -9,6 +11,9 @@ xlsxwriter = pytest.importorskip("xlsxwriter") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def ext():
Backport PR #57486: CI: Run excel tests on single cpu for windows
https://api.github.com/repos/pandas-dev/pandas/pulls/57507
2024-02-19T17:34:17Z
2024-02-19T20:15:56Z
2024-02-19T20:15:56Z
2024-02-19T20:15:56Z
DOC: Fix PR01 errors in multiple files (#57438)
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 231d40e17c0c0..04c3ff3a42971 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -1477,7 +1477,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.DatetimeIndex.std\ pandas.ExcelFile\ pandas.ExcelFile.parse\ - pandas.Grouper\ pandas.HDFStore.append\ pandas.HDFStore.put\ pandas.Index.get_indexer_for\ @@ -1538,21 +1537,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.api.types.is_float\ pandas.api.types.is_hashable\ pandas.api.types.is_integer\ - pandas.core.groupby.DataFrameGroupBy.cummax\ - pandas.core.groupby.DataFrameGroupBy.cummin\ - pandas.core.groupby.DataFrameGroupBy.cumprod\ - pandas.core.groupby.DataFrameGroupBy.cumsum\ - pandas.core.groupby.DataFrameGroupBy.filter\ - pandas.core.groupby.DataFrameGroupBy.pct_change\ - pandas.core.groupby.DataFrameGroupBy.rolling\ - pandas.core.groupby.SeriesGroupBy.cummax\ - pandas.core.groupby.SeriesGroupBy.cummin\ - pandas.core.groupby.SeriesGroupBy.cumprod\ - pandas.core.groupby.SeriesGroupBy.cumsum\ pandas.core.groupby.SeriesGroupBy.filter\ - pandas.core.groupby.SeriesGroupBy.nunique\ - pandas.core.groupby.SeriesGroupBy.pct_change\ - pandas.core.groupby.SeriesGroupBy.rolling\ pandas.core.resample.Resampler.max\ pandas.core.resample.Resampler.min\ pandas.core.resample.Resampler.quantile\ diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index dfe145783c4a3..c90ae4d590b45 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -723,15 +723,22 @@ def nunique(self, dropna: bool = True) -> Series | DataFrame: """ Return number of unique elements in the group. + Parameters + ---------- + dropna : bool, default True + Don't include NaN in the counts. + Returns ------- Series Number of unique values within each group. - Examples + See Also -------- - For SeriesGroupby: + core.resample.Resampler.nunique : Method nunique for Resampler. + Examples + -------- >>> lst = ["a", "a", "b", "b"] >>> ser = pd.Series([1, 2, 3, 3], index=lst) >>> ser @@ -744,25 +751,6 @@ def nunique(self, dropna: bool = True) -> Series | DataFrame: a 2 b 1 dtype: int64 - - For Resampler: - - >>> ser = pd.Series( - ... [1, 2, 3, 3], - ... index=pd.DatetimeIndex( - ... ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"] - ... ), - ... ) - >>> ser - 2023-01-01 1 - 2023-01-15 2 - 2023-02-01 3 - 2023-02-15 3 - dtype: int64 - >>> ser.resample("MS").nunique() - 2023-01-01 2 - 2023-02-01 1 - Freq: MS, dtype: int64 """ ids, ngroups = self._grouper.group_info val = self.obj._values @@ -1942,6 +1930,10 @@ def filter(self, func, dropna: bool = True, *args, **kwargs) -> DataFrame: dropna : bool Drop groups that do not pass the filter. True by default; if False, groups that evaluate False are filled with NaNs. + *args + Additional positional arguments to pass to `func`. + **kwargs + Additional keyword arguments to pass to `func`. Returns ------- diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 103f7b55c0550..7c9fe0df9d022 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -4672,6 +4672,14 @@ def cumprod(self, *args, **kwargs) -> NDFrameT: """ Cumulative product for each group. + Parameters + ---------- + *args : tuple + Positional arguments to be passed to `func`. + **kwargs : dict + Additional/specific keyword arguments to be passed to the function, + such as `numeric_only` and `skipna`. + Returns ------- Series or DataFrame @@ -4722,6 +4730,14 @@ def cumsum(self, *args, **kwargs) -> NDFrameT: """ Cumulative sum for each group. + Parameters + ---------- + *args : tuple + Positional arguments to be passed to `func`. + **kwargs : dict + Additional/specific keyword arguments to be passed to the function, + such as `numeric_only` and `skipna`. + Returns ------- Series or DataFrame @@ -4776,6 +4792,14 @@ def cummin( """ Cumulative min for each group. + Parameters + ---------- + numeric_only : bool, default False + Include only `float`, `int` or `boolean` data. + **kwargs : dict, optional + Additional keyword arguments to be passed to the function, such as `skipna`, + to control whether NA/null values are ignored. + Returns ------- Series or DataFrame @@ -4838,6 +4862,14 @@ def cummax( """ Cumulative max for each group. + Parameters + ---------- + numeric_only : bool, default False + Include only `float`, `int` or `boolean` data. + **kwargs : dict, optional + Additional keyword arguments to be passed to the function, such as `skipna`, + to control whether NA/null values are ignored. + Returns ------- Series or DataFrame @@ -5134,6 +5166,32 @@ def pct_change( """ Calculate pct_change of each value to previous entry in group. + Parameters + ---------- + periods : int, default 1 + Periods to shift for calculating percentage change. Comparing with + a period of 1 means adjacent elements are compared, whereas a period + of 2 compares every other element. + + fill_method : FillnaOptions or None, default None + Specifies how to handle missing values after the initial shift + operation necessary for percentage change calculation. Users are + encouraged to handle missing values manually in future versions. + Valid options are: + - A FillnaOptions value ('ffill', 'bfill') for forward or backward filling. + - None to avoid filling. + Note: Usage is discouraged due to impending deprecation. + + limit : int or None, default None + The maximum number of consecutive NA values to fill, based on the chosen + `fill_method`. Address NaN values prior to using `pct_change` as this + parameter is nearing deprecation. + + freq : str, pandas offset object, or None, default None + The frequency increment for time series data (e.g., 'M' for month-end). + If None, the frequency is inferred from the index. Relevant for time + series data only. + Returns ------- Series or DataFrame diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index b5e4881ffc29c..9179bec86f660 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -68,6 +68,10 @@ class Grouper: Parameters ---------- + *args + Currently unused, reserved for future use. + **kwargs + Dictionary of the keyword arguments to pass to Grouper. key : str, defaults to None Groupby key, which selects the grouping column of the target. level : name/number, defaults to None diff --git a/pandas/core/resample.py b/pandas/core/resample.py index e60dcdb10e653..4147437114b2f 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -59,7 +59,6 @@ NDFrame, _shared_docs, ) -from pandas.core.groupby.generic import SeriesGroupBy from pandas.core.groupby.groupby import ( BaseGroupBy, GroupBy, @@ -1358,8 +1357,38 @@ def ohlc(self): return self._downsample("ohlc") @final - @doc(SeriesGroupBy.nunique) def nunique(self): + """ + Return number of unique elements in the group. + + Returns + ------- + Series + Number of unique values within each group. + + See Also + -------- + core.groupby.SeriesGroupBy.nunique : Method nunique for SeriesGroupBy. + + Examples + -------- + >>> ser = pd.Series( + ... [1, 2, 3, 3], + ... index=pd.DatetimeIndex( + ... ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"] + ... ), + ... ) + >>> ser + 2023-01-01 1 + 2023-01-15 2 + 2023-02-01 3 + 2023-02-15 3 + dtype: int64 + >>> ser.resample("MS").nunique() + 2023-01-01 2 + 2023-02-01 1 + Freq: MS, dtype: int64 + """ return self._downsample("nunique") @final
Fixed PR01 errors (#57438) and added parameter descriptions for: - `pandas.Grouper` - `pandas.core.groupby.DataFrameGroupBy.cummax` - `pandas.core.groupby.DataFrameGroupBy.cummin` - `pandas.core.groupby.DataFrameGroupBy.cumprod` - `pandas.core.groupby.DataFrameGroupBy.cumsum` - `pandas.core.groupby.DataFrameGroupBy.filter` - `pandas.core.groupby.DataFrameGroupBy.pct_change` - `pandas.core.groupby.DataFrameGroupBy.rolling` - `pandas.core.groupby.SeriesGroupBy.nunique` - `pandas.core.groupby.SeriesGroupBy.cummax` - `pandas.core.groupby.SeriesGroupBy.cummin` - `pandas.core.groupby.SeriesGroupBy.cumprod` - `pandas.core.groupby.SeriesGroupBy.cumsum` - `pandas.core.groupby.SeriesGroupBy.cumprod` Fixed functions also removed from code_checks.sh
https://api.github.com/repos/pandas-dev/pandas/pulls/57504
2024-02-19T10:55:45Z
2024-02-21T01:37:56Z
2024-02-21T01:37:56Z
2024-02-21T01:38:03Z
Bump pandas-dev/github-doc-previewer from 0.3.1 to 0.3.2
diff --git a/.github/workflows/comment-commands.yml b/.github/workflows/comment-commands.yml index da9f6ac8bff78..62956f5825782 100644 --- a/.github/workflows/comment-commands.yml +++ b/.github/workflows/comment-commands.yml @@ -24,7 +24,7 @@ jobs: concurrency: group: ${{ github.actor }}-preview-docs steps: - - uses: pandas-dev/github-doc-previewer@v0.3.1 + - uses: pandas-dev/github-doc-previewer@v0.3.2 with: previewer-server: "https://pandas.pydata.org/preview" artifact-job: "Doc Build and Upload"
Bumps [pandas-dev/github-doc-previewer](https://github.com/pandas-dev/github-doc-previewer) from 0.3.1 to 0.3.2. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/pandas-dev/github-doc-previewer/releases">pandas-dev/github-doc-previewer's releases</a>.</em></p> <blockquote> <h2>v0.3.2</h2> <p>github-docs-previewer 0.3.2</p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/pandas-dev/github-doc-previewer/commit/7a1ea7e96d1a24578ec35eedd4256a7d80c3fef8"><code>7a1ea7e</code></a> Increasing the number of CI jobs that are fetched from github (from 30 to 100)</li> <li><a href="https://github.com/pandas-dev/github-doc-previewer/commit/890a0d2e14a3cbeebbfccc3afed35e03bf2a4481"><code>890a0d2</code></a> Fix typo in installation url, and update version for next release</li> <li>See full diff in <a href="https://github.com/pandas-dev/github-doc-previewer/compare/v0.3.1...v0.3.2">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=pandas-dev/github-doc-previewer&package-manager=github_actions&previous-version=0.3.1&new-version=0.3.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/pandas-dev/pandas/pulls/57503
2024-02-19T08:04:45Z
2024-02-19T23:41:24Z
2024-02-19T23:41:24Z
2024-02-19T23:41:26Z
Fix for small typo
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index e96a905367f69..aa6dbe54645e7 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1544,7 +1544,7 @@ class DateOffset(RelativeDeltaOffset, metaclass=OffsetMeta): Standard kind of date increment used for a date range. Works exactly like the keyword argument form of relativedelta. - Note that the positional argument form of relativedelata is not + Note that the positional argument form of relativedelta is not supported. Use of the keyword n is discouraged-- you would be better off specifying n in the keywords you use, but regardless it is there for you. n is needed for DateOffset subclasses.
Just a very small fix for a typo I noticed.
https://api.github.com/repos/pandas-dev/pandas/pulls/57502
2024-02-19T07:13:05Z
2024-02-19T07:34:52Z
2024-02-19T07:34:52Z
2024-02-19T08:16:16Z
DOC: Add whatsnew line for #57485
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 54b0d5f93dfa3..e1da0af59b3b8 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -33,6 +33,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.to_json` converting nullable integers to floats (:issue:`57224`) - Fixed regression in :meth:`DataFrame.to_sql` when ``method="multi"`` is passed and the dialect type is not Oracle (:issue:`57310`) - Fixed regression in :meth:`DataFrame.transpose` with nullable extension dtypes not having F-contiguous data potentially causing exceptions when used (:issue:`57315`) +- Fixed regression in :meth:`DataFrame.update` emitting incorrect warnings about downcasting (:issue:`57124`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) - Fixed regression in :meth:`ExtensionArray.to_numpy` raising for non-numeric masked dtypes (:issue:`56991`)
- [ ] 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. Ref: https://github.com/pandas-dev/pandas/pull/57485#issuecomment-1951354802 cc @phofl
https://api.github.com/repos/pandas-dev/pandas/pulls/57497
2024-02-19T03:16:28Z
2024-02-19T09:50:19Z
2024-02-19T09:50:19Z
2024-02-19T22:18:28Z
Backport PR #57474 on branch 2.2.x (REGR: DataFrame.transpose resulting in not contiguous data on nullable EAs)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 8c8db76ccc3d0..e1da0af59b3b8 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -32,6 +32,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) - Fixed regression in :meth:`DataFrame.to_json` converting nullable integers to floats (:issue:`57224`) - Fixed regression in :meth:`DataFrame.to_sql` when ``method="multi"`` is passed and the dialect type is not Oracle (:issue:`57310`) +- Fixed regression in :meth:`DataFrame.transpose` with nullable extension dtypes not having F-contiguous data potentially causing exceptions when used (:issue:`57315`) - Fixed regression in :meth:`DataFrame.update` emitting incorrect warnings about downcasting (:issue:`57124`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 0bc0d9f8d7a7d..320d8cb10b8c2 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -1621,13 +1621,24 @@ def transpose_homogeneous_masked_arrays( same dtype. The caller is responsible for ensuring validity of input data. """ masked_arrays = list(masked_arrays) + dtype = masked_arrays[0].dtype + values = [arr._data.reshape(1, -1) for arr in masked_arrays] - transposed_values = np.concatenate(values, axis=0) + transposed_values = np.concatenate( + values, + axis=0, + out=np.empty( + (len(masked_arrays), len(masked_arrays[0])), + order="F", + dtype=dtype.numpy_dtype, + ), + ) masks = [arr._mask.reshape(1, -1) for arr in masked_arrays] - transposed_masks = np.concatenate(masks, axis=0) + transposed_masks = np.concatenate( + masks, axis=0, out=np.empty_like(transposed_values, dtype=bool) + ) - dtype = masked_arrays[0].dtype arr_type = dtype.construct_array_type() transposed_arrays: list[BaseMaskedArray] = [] for i in range(transposed_values.shape[1]): diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index d0caa071fae1c..3e74094f266d1 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -3,6 +3,7 @@ import pandas.util._test_decorators as td +import pandas as pd from pandas import ( DataFrame, DatetimeIndex, @@ -190,3 +191,19 @@ def test_transpose_not_inferring_dt_mixed_blocks(self): dtype=object, ) tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype1", ["Int64", "Float64"]) + @pytest.mark.parametrize("dtype2", ["Int64", "Float64"]) + def test_transpose(self, dtype1, dtype2): + # GH#57315 - transpose should have F contiguous blocks + df = DataFrame( + { + "a": pd.array([1, 1, 2], dtype=dtype1), + "b": pd.array([3, 4, 5], dtype=dtype2), + } + ) + result = df.T + for blk in result._mgr.blocks: + # When dtypes are unequal, we get NumPy object array + data = blk.values._data if dtype1 == dtype2 else blk.values + assert data.flags["F_CONTIGUOUS"]
…uous data on nullable EAs - [ ] 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/57496
2024-02-19T03:09:19Z
2024-02-19T09:51:13Z
2024-02-19T09:51:13Z
2024-02-19T22:25:29Z
DOC: Add a few deprecation notes
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 8eee15e13791a..15c51b98aea0b 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -168,6 +168,9 @@ def is_sparse(arr) -> bool: """ Check whether an array-like is a 1-D pandas sparse array. + .. deprecated:: 2.1.0 + Use isinstance(dtype, pd.SparseDtype) instead. + Check that the one-dimensional array-like is a pandas sparse array. Returns True if it is a pandas sparse array, not another type of sparse array. @@ -294,6 +297,9 @@ def is_datetime64tz_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of a DatetimeTZDtype dtype. + .. deprecated:: 2.1.0 + Use isinstance(dtype, pd.DatetimeTZDtype) instead. + Parameters ---------- arr_or_dtype : array-like or dtype @@ -380,6 +386,9 @@ def is_period_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Period dtype. + .. deprecated:: 2.2.0 + Use isinstance(dtype, pd.Period) instead. + Parameters ---------- arr_or_dtype : array-like or dtype @@ -423,6 +432,9 @@ def is_interval_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Interval dtype. + .. deprecated:: 2.2.0 + Use isinstance(dtype, pd.IntervalDtype) instead. + Parameters ---------- arr_or_dtype : array-like or dtype @@ -469,6 +481,9 @@ def is_categorical_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Categorical dtype. + .. deprecated:: 2.2.0 + Use isinstance(dtype, pd.CategoricalDtype) instead. + Parameters ---------- arr_or_dtype : array-like or dtype
- [ ] closes #57382 (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/57490
2024-02-18T21:40:39Z
2024-02-19T20:15:24Z
2024-02-19T20:15:24Z
2024-02-19T20:31:06Z
REGR: astype introducing decimals when casting from int with na to string
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 54b0d5f93dfa3..e3efb008be6a9 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -37,6 +37,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) - Fixed regression in :meth:`ExtensionArray.to_numpy` raising for non-numeric masked dtypes (:issue:`56991`) - Fixed regression in :meth:`Index.join` raising ``TypeError`` when joining an empty index to a non-empty index containing mixed dtype values (:issue:`57048`) +- Fixed regression in :meth:`Series.astype` introducing decimals when converting from integer with missing values to string dtype (:issue:`57418`) - Fixed regression in :meth:`Series.pct_change` raising a ``ValueError`` for an empty :class:`Series` (:issue:`57056`) - Fixed regression in :meth:`Series.to_numpy` when dtype is given as float and the data contains NaNs (:issue:`57121`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 3146b31a2e7e8..00668576d5d53 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -759,7 +759,7 @@ cpdef ndarray[object] ensure_string_array( out = arr.astype(str).astype(object) out[arr.isna()] = na_value return out - arr = arr.to_numpy() + arr = arr.to_numpy(dtype=object) elif not util.is_array(arr): arr = np.array(arr, dtype="object") diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 2588f195aab7e..4b2122e25f819 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -667,3 +667,11 @@ def test_astype_timedelta64_with_np_nan(self): result = Series([Timedelta(1), np.nan], dtype="timedelta64[ns]") expected = Series([Timedelta(1), NaT], dtype="timedelta64[ns]") tm.assert_series_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_astype_int_na_string(self): + # GH#57418 + ser = Series([12, NA], dtype="Int64[pyarrow]") + result = ser.astype("string[pyarrow]") + expected = Series(["12", NA], dtype="string[pyarrow]") + tm.assert_series_equal(result, expected)
… - [ ] closes #57418 (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/57489
2024-02-18T21:05:47Z
2024-02-20T17:26:52Z
2024-02-20T17:26:52Z
2024-02-20T17:27:00Z
REGR: query raising for all NaT in object column
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 54b0d5f93dfa3..6bf2f21c37d38 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -27,6 +27,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.loc` which was unnecessarily throwing "incompatible dtype warning" when expanding with partial row indexer and multiple columns (see `PDEP6 <https://pandas.pydata.org/pdeps/0006-ban-upcasting.html>`_) (:issue:`56503`) - Fixed regression in :meth:`DataFrame.map` with ``na_action="ignore"`` not being respected for NumPy nullable and :class:`ArrowDtypes` (:issue:`57316`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) +- Fixed regression in :meth:`DataFrame.query` with all ``NaT`` column with object dtype (:issue:`57068`) - Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) - Fixed regression in :meth:`DataFrame.sort_index` not producing a stable sort for a index with duplicates (:issue:`57151`) - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7614951566bf9..c6196fa1a084d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -597,7 +597,7 @@ def _get_cleaned_column_resolvers(self) -> dict[Hashable, Series]: return { clean_column_name(k): Series( - v, copy=False, index=self.index, name=k + v, copy=False, index=self.index, name=k, dtype=self.dtypes[k] ).__finalize__(self) for k, v in zip(self.columns, self._iter_column_arrays()) if not isinstance(k, int) diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 0e29db3ca85df..d2e36eb6147e7 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -1415,3 +1415,11 @@ def test_query_ea_equality_comparison(self, dtype, engine): } ) tm.assert_frame_equal(result, expected) + + def test_all_nat_in_object(self): + # GH#57068 + now = pd.Timestamp.now("UTC") # noqa: F841 + df = DataFrame({"a": pd.to_datetime([None, None], utc=True)}, dtype=object) + result = df.query("a > @now") + expected = DataFrame({"a": []}, dtype=object) + tm.assert_frame_equal(result, expected)
- [ ] closes #57068 (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/57488
2024-02-18T20:19:14Z
2024-02-19T23:36:11Z
2024-02-19T23:36:11Z
2024-02-19T23:36:44Z
CoW: Track references in unstack if there is no copy
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index ff358e8ba346c..d02af0f12c467 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -35,6 +35,7 @@ factorize, unique, ) +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.arrays.categorical import factorize_from_iterable from pandas.core.construction import ensure_wrapped_if_datetimelike from pandas.core.frame import DataFrame @@ -231,20 +232,31 @@ def arange_result(self) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.bool_]]: return new_values, mask.any(0) # TODO: in all tests we have mask.any(0).all(); can we rely on that? - def get_result(self, values, value_columns, fill_value) -> DataFrame: + def get_result(self, obj, value_columns, fill_value) -> DataFrame: + values = obj._values if values.ndim == 1: values = values[:, np.newaxis] if value_columns is None and values.shape[1] != 1: # pragma: no cover raise ValueError("must pass column labels for multi-column data") - values, _ = self.get_new_values(values, fill_value) + new_values, _ = self.get_new_values(values, fill_value) columns = self.get_new_columns(value_columns) index = self.new_index - return self.constructor( - values, index=index, columns=columns, dtype=values.dtype + result = self.constructor( + new_values, index=index, columns=columns, dtype=new_values.dtype, copy=False ) + if isinstance(values, np.ndarray): + base, new_base = values.base, new_values.base + elif isinstance(values, NDArrayBackedExtensionArray): + base, new_base = values._ndarray.base, new_values._ndarray.base + else: + base, new_base = 1, 2 # type: ignore[assignment] + if base is new_base: + # We can only get here if one of the dimensions is size 1 + result._mgr.add_references(obj._mgr) + return result def get_new_values(self, values, fill_value=None): if values.ndim == 1: @@ -532,9 +544,7 @@ def unstack( unstacker = _Unstacker( obj.index, level=level, constructor=obj._constructor_expanddim, sort=sort ) - return unstacker.get_result( - obj._values, value_columns=None, fill_value=fill_value - ) + return unstacker.get_result(obj, value_columns=None, fill_value=fill_value) def _unstack_frame( @@ -550,7 +560,7 @@ def _unstack_frame( return obj._constructor_from_mgr(mgr, axes=mgr.axes) else: return unstacker.get_result( - obj._values, value_columns=obj.columns, fill_value=fill_value + obj, value_columns=obj.columns, fill_value=fill_value ) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 99250dc929997..fb4c2e8d655e6 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2701,3 +2701,16 @@ def test_pivot_table_with_margins_and_numeric_column_names(self): index=Index(["a", "b", "All"], name=0), ) tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("m", [1, 10]) + def test_unstack_shares_memory(self, m): + # GH#56633 + levels = np.arange(m) + index = MultiIndex.from_product([levels] * 2) + values = np.arange(m * m * 100).reshape(m * m, 100) + df = DataFrame(values, index, np.arange(100)) + df_orig = df.copy() + result = df.unstack(sort=False) + assert np.shares_memory(df._values, result._values) is (m == 1) + result.iloc[0, 0] = -1 + tm.assert_frame_equal(df, df_orig)
- [ ] xref #56633 - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. cc @jorisvandenbossche @rhshadrach @rhshadrach was correct, we can get there without making a copy. it's a special case, but nevertheless
https://api.github.com/repos/pandas-dev/pandas/pulls/57487
2024-02-18T16:59:29Z
2024-04-01T18:36:06Z
2024-04-01T18:36:06Z
2024-04-02T16:18:07Z
CI: Run excel tests on single cpu for windows
diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py index f01827fa4ca2f..b5bb9b27258d8 100644 --- a/pandas/tests/io/excel/test_odf.py +++ b/pandas/tests/io/excel/test_odf.py @@ -3,11 +3,16 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd import pandas._testing as tm pytest.importorskip("odf") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture(autouse=True) def cd_and_set_engine(monkeypatch, datapath): diff --git a/pandas/tests/io/excel/test_odswriter.py b/pandas/tests/io/excel/test_odswriter.py index 271353a173d2a..1c728ad801bc1 100644 --- a/pandas/tests/io/excel/test_odswriter.py +++ b/pandas/tests/io/excel/test_odswriter.py @@ -6,6 +6,8 @@ import pytest +from pandas.compat import is_platform_windows + import pandas as pd import pandas._testing as tm @@ -13,6 +15,9 @@ odf = pytest.importorskip("odf") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def ext(): diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index c20c6daf92931..952026b2a50d3 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd from pandas import DataFrame import pandas._testing as tm @@ -17,6 +19,9 @@ openpyxl = pytest.importorskip("openpyxl") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def ext(): diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index e4a8791396ee2..2cf17913ba6e4 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -18,6 +18,7 @@ from pandas._config import using_pyarrow_string_dtype +from pandas.compat import is_platform_windows import pandas.util._test_decorators as td import pandas as pd @@ -34,6 +35,9 @@ StringArray, ) +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"] engine_params = [ # Add any engines to test here diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 58b297e4520bb..e801d1c647ed1 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows import pandas.util._test_decorators as td from pandas import ( @@ -20,6 +21,9 @@ # could compute styles and render to excel without jinja2, since there is no # 'template' file, but this needs the import error to delayed until render time. +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + def assert_equal_cell_styles(cell1, cell2): # TODO: should find a better way to check equality diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 3352164b2f980..7d958d2d35920 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -11,6 +11,7 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows from pandas.compat._constants import PY310 from pandas.compat._optional import import_optional_dependency import pandas.util._test_decorators as td @@ -34,6 +35,9 @@ ) from pandas.io.excel._util import _writers +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + def get_exp_unit(path: str) -> str: return "ns" diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index c49cbaf7fb26c..edabbad93acbc 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd import pandas._testing as tm @@ -11,6 +13,9 @@ xlrd = pytest.importorskip("xlrd") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def read_ext_xlrd(): diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index 94f6bdfaf069c..529367761fc02 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -2,6 +2,8 @@ import pytest +from pandas.compat import is_platform_windows + from pandas import DataFrame import pandas._testing as tm @@ -9,6 +11,9 @@ xlsxwriter = pytest.importorskip("xlsxwriter") +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + @pytest.fixture def ext():
I don't want to debug windows builds but we should get ci green again
https://api.github.com/repos/pandas-dev/pandas/pulls/57486
2024-02-18T15:18:33Z
2024-02-19T17:33:47Z
2024-02-19T17:33:47Z
2024-02-19T22:13:47Z
REGR: DataFrame.update emits spurious warning about downcasting
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index ca4fef4f57fb6..8c8db76ccc3d0 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -32,6 +32,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) - Fixed regression in :meth:`DataFrame.to_json` converting nullable integers to floats (:issue:`57224`) - Fixed regression in :meth:`DataFrame.to_sql` when ``method="multi"`` is passed and the dialect type is not Oracle (:issue:`57310`) +- Fixed regression in :meth:`DataFrame.update` emitting incorrect warnings about downcasting (:issue:`57124`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) - Fixed regression in :meth:`ExtensionArray.to_numpy` raising for non-numeric masked dtypes (:issue:`56991`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b531ddc418df1..c09989fe87fb0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8962,6 +8962,7 @@ def update( 1 2 500.0 2 3 6.0 """ + if not PYPY and using_copy_on_write(): if sys.getrefcount(self) <= REF_COUNT: warnings.warn( @@ -9010,7 +9011,17 @@ def update( if mask.all(): continue - self.loc[:, col] = self[col].where(mask, that) + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="Downcasting behavior", + category=FutureWarning, + ) + # GH#57124 - `that` might get upcasted because of NA values, and then + # downcasted in where because of the mask. Ignoring the warning + # is a stopgap, will replace with a new implementation of update + # in 3.0. + self.loc[:, col] = self[col].where(mask, that) # ---------------------------------------------------------------------- # Data reshaping diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index 20ba550beeb30..8af1798aa8e00 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -48,16 +48,18 @@ def test_update(self): def test_update_dtypes(self): # gh 3016 df = DataFrame( - [[1.0, 2.0, False, True], [4.0, 5.0, True, False]], - columns=["A", "B", "bool1", "bool2"], + [[1.0, 2.0, 1, False, True], [4.0, 5.0, 2, True, False]], + columns=["A", "B", "int", "bool1", "bool2"], ) - other = DataFrame([[45, 45]], index=[0], columns=["A", "B"]) + other = DataFrame( + [[45, 45, 3, True]], index=[0], columns=["A", "B", "int", "bool1"] + ) df.update(other) expected = DataFrame( - [[45.0, 45.0, False, True], [4.0, 5.0, True, False]], - columns=["A", "B", "bool1", "bool2"], + [[45.0, 45.0, 3, True, True], [4.0, 5.0, 2, True, False]], + columns=["A", "B", "int", "bool1", "bool2"], ) tm.assert_frame_equal(df, expected)
- [x] closes #57124 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This is meant as a stopgap - I plan to finish up #55634 for 3.0 which will avoid any upcasting/downcasting altogether. However I do no like the idea of that PR being put in a patch version since it is an entirely new approach to `DataFrame.update`. I think this can't go in main because the warning and downcasting behavior has already been removed there.
https://api.github.com/repos/pandas-dev/pandas/pulls/57485
2024-02-18T13:10:51Z
2024-02-18T15:13:56Z
2024-02-18T15:13:56Z
2024-02-19T03:16:52Z
Backport PR #57454 on branch 2.2.x (Release the gil in take for axis=1)
diff --git a/pandas/_libs/algos_take_helper.pxi.in b/pandas/_libs/algos_take_helper.pxi.in index 88c3abba506a3..385727fad3c50 100644 --- a/pandas/_libs/algos_take_helper.pxi.in +++ b/pandas/_libs/algos_take_helper.pxi.in @@ -184,6 +184,17 @@ def take_2d_axis1_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values, fv = fill_value + {{if c_type_in == c_type_out != "object"}} + with nogil: + for i in range(n): + for j in range(k): + idx = indexer[j] + if idx == -1: + out[i, j] = fv + else: + out[i, j] = values[i, idx] + + {{else}} for i in range(n): for j in range(k): idx = indexer[j] @@ -195,6 +206,7 @@ def take_2d_axis1_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values, {{else}} out[i, j] = values[i, idx] {{endif}} + {{endif}} @cython.wraparound(False)
Backport PR #57454: Release the gil in take for axis=1
https://api.github.com/repos/pandas-dev/pandas/pulls/57484
2024-02-18T11:43:48Z
2024-02-18T12:35:55Z
2024-02-18T12:35:55Z
2024-02-18T12:35:55Z
CLN remove dataframe api consortium entrypoint
diff --git a/.github/workflows/package-checks.yml b/.github/workflows/package-checks.yml index d59ddf272f705..28c56ec7ff03b 100644 --- a/.github/workflows/package-checks.yml +++ b/.github/workflows/package-checks.yml @@ -24,7 +24,7 @@ jobs: runs-on: ubuntu-22.04 strategy: matrix: - extra: ["test", "performance", "computation", "fss", "aws", "gcp", "excel", "parquet", "feather", "hdf5", "spss", "postgresql", "mysql", "sql-other", "html", "xml", "plot", "output-formatting", "clipboard", "compression", "consortium-standard", "all"] + extra: ["test", "performance", "computation", "fss", "aws", "gcp", "excel", "parquet", "feather", "hdf5", "spss", "postgresql", "mysql", "sql-other", "html", "xml", "plot", "output-formatting", "clipboard", "compression", "all"] fail-fast: false name: Install Extras - ${{ matrix.extra }} concurrency: diff --git a/ci/deps/actions-311-downstream_compat.yaml b/ci/deps/actions-311-downstream_compat.yaml index 8751cfd52f97d..efd790d77afbb 100644 --- a/ci/deps/actions-311-downstream_compat.yaml +++ b/ci/deps/actions-311-downstream_compat.yaml @@ -74,5 +74,4 @@ dependencies: - pip: - adbc-driver-postgresql>=0.8.0 - adbc-driver-sqlite>=0.8.0 - - dataframe-api-compat>=0.1.7 - tzdata>=2022.7 diff --git a/ci/deps/actions-39-minimum_versions.yaml b/ci/deps/actions-39-minimum_versions.yaml index d59da897c0d33..94cb21d1621b6 100644 --- a/ci/deps/actions-39-minimum_versions.yaml +++ b/ci/deps/actions-39-minimum_versions.yaml @@ -62,5 +62,4 @@ dependencies: - pip: - adbc-driver-postgresql==0.8.0 - adbc-driver-sqlite==0.8.0 - - dataframe-api-compat==0.1.7 - tzdata==2022.7 diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 33ce6f0218b98..77e273d8c81fe 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -417,14 +417,3 @@ Dependency Minimum Version pip extra Notes ========================= ================== =============== ============================================================= Zstandard 0.19.0 compression Zstandard compression ========================= ================== =============== ============================================================= - -Consortium Standard -^^^^^^^^^^^^^^^^^^^ - -Installable with ``pip install "pandas[consortium-standard]"`` - -========================= ================== =================== ============================================================= -Dependency Minimum Version pip extra Notes -========================= ================== =================== ============================================================= -dataframe-api-compat 0.1.7 consortium-standard Consortium Standard-compatible implementation based on pandas -========================= ================== =================== ============================================================= diff --git a/environment.yml b/environment.yml index 36d1bf27a4cd2..3528f12c66a8b 100644 --- a/environment.yml +++ b/environment.yml @@ -117,6 +117,5 @@ dependencies: - pip: - adbc-driver-postgresql>=0.8.0 - adbc-driver-sqlite>=0.8.0 - - dataframe-api-compat>=0.1.7 - typing_extensions; python_version<"3.11" - tzdata>=2022.7 diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 3a438b76b1263..ddd9b591d3e83 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -24,7 +24,6 @@ "bs4": "4.11.2", "blosc": "1.21.3", "bottleneck": "1.3.6", - "dataframe-api-compat": "0.1.7", "fastparquet": "2023.04.0", "fsspec": "2022.11.0", "html5lib": "1.1", diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 660979540691e..60999ccd726bf 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -938,21 +938,6 @@ def __dataframe__( return PandasDataFrameXchg(self, allow_copy=allow_copy) - def __dataframe_consortium_standard__( - self, *, api_version: str | None = None - ) -> Any: - """ - Provide entry point to the Consortium DataFrame Standard API. - - This is developed and maintained outside of pandas. - Please report any issues to https://github.com/data-apis/dataframe-api-compat. - """ - dataframe_api_compat = import_optional_dependency("dataframe_api_compat") - convert_to_standard_compliant_dataframe = ( - dataframe_api_compat.pandas_standard.convert_to_standard_compliant_dataframe - ) - return convert_to_standard_compliant_dataframe(self, api_version=api_version) - def __arrow_c_stream__(self, requested_schema=None): """ Export the pandas DataFrame as an Arrow C stream PyCapsule. diff --git a/pandas/core/series.py b/pandas/core/series.py index 1672c29f15763..99833e6ea8e4e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -33,7 +33,6 @@ from pandas._libs.lib import is_range_indexer from pandas.compat import PYPY from pandas.compat._constants import REF_COUNT -from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv from pandas.errors import ( ChainedAssignmentError, @@ -845,22 +844,6 @@ def __array__(self, dtype: npt.DTypeLike | None = None) -> np.ndarray: # ---------------------------------------------------------------------- - def __column_consortium_standard__(self, *, api_version: str | None = None) -> Any: - """ - Provide entry point to the Consortium DataFrame Standard API. - - This is developed and maintained outside of pandas. - Please report any issues to https://github.com/data-apis/dataframe-api-compat. - """ - dataframe_api_compat = import_optional_dependency("dataframe_api_compat") - return ( - dataframe_api_compat.pandas_standard.convert_to_standard_compliant_column( - self, api_version=api_version - ) - ) - - # ---------------------------------------------------------------------- - # indexers @property def axes(self) -> list[Index]: diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index 7186056f90299..824e550e0f03b 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -306,25 +306,6 @@ def test_from_obscure_array(dtype, box): tm.assert_index_equal(result, expected) -def test_dataframe_consortium() -> None: - """ - Test some basic methods of the dataframe consortium standard. - - Full testing is done at https://github.com/data-apis/dataframe-api-compat, - this is just to check that the entry point works as expected. - """ - pytest.importorskip("dataframe_api_compat") - df_pd = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) - df = df_pd.__dataframe_consortium_standard__() - result_1 = df.get_column_names() - expected_1 = ["a", "b"] - assert result_1 == expected_1 - - ser = Series([1, 2, 3], name="a") - col = ser.__column_consortium_standard__() - assert col.name == "a" - - def test_xarray_coerce_unit(): # GH44053 xr = pytest.importorskip("xarray") diff --git a/pyproject.toml b/pyproject.toml index 93b4491449e8d..5d1f56ee3597e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,14 +84,12 @@ plot = ['matplotlib>=3.6.3'] output-formatting = ['jinja2>=3.1.2', 'tabulate>=0.9.0'] clipboard = ['PyQt5>=5.15.9', 'qtpy>=2.3.0'] compression = ['zstandard>=0.19.0'] -consortium-standard = ['dataframe-api-compat>=0.1.7'] all = ['adbc-driver-postgresql>=0.8.0', 'adbc-driver-sqlite>=0.8.0', 'beautifulsoup4>=4.11.2', # blosc only available on conda (https://github.com/Blosc/python-blosc/issues/297) #'blosc>=1.21.3', 'bottleneck>=1.3.6', - 'dataframe-api-compat>=0.1.7', 'fastparquet>=2023.04.0', 'fsspec>=2022.11.0', 'gcsfs>=2022.11.0', diff --git a/requirements-dev.txt b/requirements-dev.txt index 96c497d35b958..40c7403cb88e8 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -85,6 +85,5 @@ requests pygments adbc-driver-postgresql>=0.8.0 adbc-driver-sqlite>=0.8.0 -dataframe-api-compat>=0.1.7 typing_extensions; python_version<"3.11" tzdata>=2022.7
Discussed privately In short: - I'm no longer involved in the project - nobody in pandas has much interest in leading the effort - pandas devs are already carrying out enough (mostly unpaid) maintenance, let's not add to it The Consortium is more than welcome to work on this, but outside of pandas
https://api.github.com/repos/pandas-dev/pandas/pulls/57482
2024-02-18T09:01:11Z
2024-02-19T18:27:57Z
2024-02-19T18:27:57Z
2024-02-19T18:27:57Z
CI: update pyright
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 91ca35ce33c49..375c74f29e63a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -129,7 +129,7 @@ repos: types: [python] stages: [manual] additional_dependencies: &pyright_dependencies - - pyright@1.1.347 + - pyright@1.1.350 - id: pyright # note: assumes python env is setup and activated name: pyright reportGeneralTypeIssues diff --git a/pandas/_testing/_hypothesis.py b/pandas/_testing/_hypothesis.py index f9f653f636c4c..4e584781122a3 100644 --- a/pandas/_testing/_hypothesis.py +++ b/pandas/_testing/_hypothesis.py @@ -54,8 +54,8 @@ DATETIME_NO_TZ = st.datetimes() DATETIME_JAN_1_1900_OPTIONAL_TZ = st.datetimes( - min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), # pyright: ignore[reportGeneralTypeIssues] - max_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), # pyright: ignore[reportGeneralTypeIssues] + min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), # pyright: ignore[reportArgumentType] + max_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), # pyright: ignore[reportArgumentType] timezones=st.one_of(st.none(), dateutil_timezones(), pytz_timezones()), ) diff --git a/pandas/conftest.py b/pandas/conftest.py index 254d605e13460..a4e0894372c45 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1404,7 +1404,7 @@ def fixed_now_ts() -> Timestamp: """ Fixture emits fixed Timestamp.now() """ - return Timestamp( # pyright: ignore[reportGeneralTypeIssues] + return Timestamp( # pyright: ignore[reportReturnType] year=2021, month=1, day=1, hour=12, minute=4, second=13, microsecond=22 ) diff --git a/pandas/core/_numba/kernels/mean_.py b/pandas/core/_numba/kernels/mean_.py index f415804781753..4ed9e8cb2bf50 100644 --- a/pandas/core/_numba/kernels/mean_.py +++ b/pandas/core/_numba/kernels/mean_.py @@ -107,7 +107,7 @@ def sliding_mean( neg_ct, compensation_add, num_consecutive_same_value, - prev_value, # pyright: ignore[reportGeneralTypeIssues] + prev_value, # pyright: ignore[reportArgumentType] ) else: for j in range(start[i - 1], s): @@ -132,7 +132,7 @@ def sliding_mean( neg_ct, compensation_add, num_consecutive_same_value, - prev_value, # pyright: ignore[reportGeneralTypeIssues] + prev_value, # pyright: ignore[reportArgumentType] ) if nobs >= min_periods and nobs > 0: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 4194ffcee2e44..0bb5fbb48e1fd 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -358,13 +358,13 @@ def __array__(self, dtype: NpDtype | None = None) -> np.ndarray: return self._ndarray @overload - def __getitem__(self, item: ScalarIndexer) -> DTScalarOrNaT: + def __getitem__(self, key: ScalarIndexer) -> DTScalarOrNaT: ... @overload def __getitem__( self, - item: SequenceIndexer | PositionalIndexerTuple, + key: SequenceIndexer | PositionalIndexerTuple, ) -> Self: ... diff --git a/pandas/core/base.py b/pandas/core/base.py index a3a86cb9ce410..7a3d6cb866ea5 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1165,7 +1165,7 @@ def _memory_usage(self, deep: bool = False) -> int: 24 """ if hasattr(self.array, "memory_usage"): - return self.array.memory_usage( # pyright: ignore[reportGeneralTypeIssues] + return self.array.memory_usage( # pyright: ignore[reportAttributeAccessIssue] deep=deep, ) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 55421090d4202..77d2e1e800a94 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -394,7 +394,7 @@ def eval( if inplace and isinstance(target, NDFrame): target.loc[:, assigner] = ret else: - target[assigner] = ret # pyright: ignore[reportGeneralTypeIssues] + target[assigner] = ret # pyright: ignore[reportIndexIssue] except (TypeError, IndexError) as err: raise ValueError("Cannot assign expression output to target") from err diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index bd4e5182b24bf..02189dd10e5b8 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -264,7 +264,7 @@ def is_nested_list_like(obj: object) -> bool: is_list_like(obj) and hasattr(obj, "__len__") # need PEP 724 to handle these typing errors - and len(obj) > 0 # pyright: ignore[reportGeneralTypeIssues] + and len(obj) > 0 # pyright: ignore[reportArgumentType] and all(is_list_like(item) for item in obj) # type: ignore[attr-defined] ) diff --git a/pandas/io/xml.py b/pandas/io/xml.py index 2038733bee808..377856eb204a6 100644 --- a/pandas/io/xml.py +++ b/pandas/io/xml.py @@ -678,8 +678,8 @@ def get_data_from_filepath( 2. file-like object (e.g. open file object, StringIO) """ filepath_or_buffer = stringify_path(filepath_or_buffer) # type: ignore[arg-type] - with get_handle( # pyright: ignore[reportGeneralTypeIssues] - filepath_or_buffer, # pyright: ignore[reportGeneralTypeIssues] + with get_handle( # pyright: ignore[reportCallIssue] + filepath_or_buffer, # pyright: ignore[reportArgumentType] "r", encoding=encoding, compression=compression, diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index a15e2054205f7..4f6fc0f3d8de3 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -368,7 +368,7 @@ def decorator(decorated: F) -> F: continue if hasattr(docstring, "_docstring_components"): docstring_components.extend( - docstring._docstring_components # pyright: ignore[reportGeneralTypeIssues] + docstring._docstring_components # pyright: ignore[reportAttributeAccessIssue] ) elif isinstance(docstring, str) or docstring.__doc__: docstring_components.append(docstring) diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index 178284c7d75b6..1c2d6e2d38ab2 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -443,7 +443,7 @@ def validate_insert_loc(loc: int, length: int) -> int: loc += length if not 0 <= loc <= length: raise IndexError(f"loc must be an integer between -{length} and {length}") - return loc # pyright: ignore[reportGeneralTypeIssues] + return loc # pyright: ignore[reportReturnType] def check_dtype_backend(dtype_backend) -> None: diff --git a/pyproject.toml b/pyproject.toml index 93b4491449e8d..5f4c7a4dc16e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -734,14 +734,22 @@ reportUntypedNamedTuple = true reportUnusedImport = true disableBytesTypePromotions = true # disable subset of "basic" +reportArgumentType = false +reportAssignmentType = false +reportAttributeAccessIssue = false +reportCallIssue = false reportGeneralTypeIssues = false +reportIndexIssue = false reportMissingModuleSource = false +reportOperatorIssue = false reportOptionalCall = false reportOptionalIterable = false reportOptionalMemberAccess = false reportOptionalOperand = false reportOptionalSubscript = false reportPrivateImportUsage = false +reportRedeclaration = false +reportReturnType = false reportUnboundVariable = false [tool.coverage.run] diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index 1589988603506..9103d4d533cf3 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -1,6 +1,14 @@ { "typeCheckingMode": "off", + "reportArgumentType": true, + "reportAssignmentType": true, + "reportAttributeAccessIssue": true, + "reportCallIssue": true, "reportGeneralTypeIssues": true, + "reportIndexIssue": true, + "reportOperatorIssue": true, + "reportRedeclaration": true, + "reportReturnType": true, "useLibraryCodeForTypes": false, "analyzeUnannotatedFunctions": false, "disableBytesTypePromotions": true, @@ -63,7 +71,6 @@ "pandas/core/indexes/period.py", "pandas/core/indexing.py", "pandas/core/internals/api.py", - "pandas/core/internals/array_manager.py", "pandas/core/internals/blocks.py", "pandas/core/internals/construction.py", "pandas/core/internals/managers.py",
Pyright 1.1.348 split `reportGeneralTypeIssues` into multiple sub-rules up. Hopefully, this might make it easier to enable some of them more gradually.
https://api.github.com/repos/pandas-dev/pandas/pulls/57481
2024-02-18T03:29:59Z
2024-02-19T23:31:32Z
2024-02-19T23:31:32Z
2024-04-07T10:59:15Z
PERF: Improve performance for fillna with datetime
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 4194ffcee2e44..77f554d24bfb7 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -649,7 +649,7 @@ def _validation_error_message(self, value, allow_listlike: bool = False) -> str: def _validate_listlike(self, value, allow_object: bool = False): if isinstance(value, type(self)): - if self.dtype.kind in "mM" and not allow_object: + if self.dtype.kind in "mM" and not allow_object and self.unit != value.unit: # type: ignore[attr-defined] # error: "DatetimeLikeArrayMixin" has no attribute "as_unit" value = value.as_unit(self.unit, round_ok=False) # type: ignore[attr-defined] return value diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7614951566bf9..665ff18868884 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6958,7 +6958,7 @@ def fillna( "with dict/Series column " "by column" ) - result = self.copy(deep=False) + result = self if inplace else self.copy(deep=False) for k, v in value.items(): if k not in result: continue
- [ ] 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/57479
2024-02-18T00:21:26Z
2024-02-20T17:25:20Z
2024-02-20T17:25:20Z
2024-02-25T18:15:18Z
PERF: Improve performance for astype is view
diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index bdb16aa202297..d351d13fdfeb6 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -257,6 +257,11 @@ def astype_is_view(dtype: DtypeObj, new_dtype: DtypeObj) -> bool: ------- True if new data is a view or not guaranteed to be a copy, False otherwise """ + if dtype.kind in "iufb" and dtype.kind == new_dtype.kind: + # fastpath for numeric dtypes + if hasattr(dtype, "itemsize") and hasattr(new_dtype, "itemsize"): + return dtype.itemsize == new_dtype.itemsize # pyright: ignore[reportAttributeAccessIssue] + if isinstance(dtype, np.dtype) and not isinstance(new_dtype, np.dtype): new_dtype, dtype = dtype, new_dtype
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This came up in asvs, it wasn't much but we can do better
https://api.github.com/repos/pandas-dev/pandas/pulls/57478
2024-02-17T23:16:27Z
2024-03-18T16:47:46Z
2024-03-18T16:47:46Z
2024-03-18T20:56:52Z
CoW: Remove remaining cow occurrences from tests
diff --git a/pandas/conftest.py b/pandas/conftest.py index 254d605e13460..47316a4ba3526 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1987,14 +1987,6 @@ def indexer_ial(request): return request.param -@pytest.fixture -def using_copy_on_write() -> bool: - """ - Fixture to check if Copy-on-Write is enabled. - """ - return True - - @pytest.fixture def using_infer_string() -> bool: """ diff --git a/pandas/tests/copy_view/test_functions.py b/pandas/tests/copy_view/test_functions.py index 56e4b186350f2..eeb19103f7bd5 100644 --- a/pandas/tests/copy_view/test_functions.py +++ b/pandas/tests/copy_view/test_functions.py @@ -12,189 +12,142 @@ from pandas.tests.copy_view.util import get_array -def test_concat_frames(using_copy_on_write): +def test_concat_frames(): df = DataFrame({"b": ["a"] * 3}) df2 = DataFrame({"a": ["a"] * 3}) df_orig = df.copy() result = concat([df, df2], axis=1) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "b"), get_array(df, "b")) - assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) - else: - assert not np.shares_memory(get_array(result, "b"), get_array(df, "b")) - assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) result.iloc[0, 0] = "d" - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(df, "b")) - assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) result.iloc[0, 1] = "d" - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a")) + assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a")) tm.assert_frame_equal(df, df_orig) -def test_concat_frames_updating_input(using_copy_on_write): +def test_concat_frames_updating_input(): df = DataFrame({"b": ["a"] * 3}) df2 = DataFrame({"a": ["a"] * 3}) result = concat([df, df2], axis=1) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "b"), get_array(df, "b")) - assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) - else: - assert not np.shares_memory(get_array(result, "b"), get_array(df, "b")) - assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) expected = result.copy() df.iloc[0, 0] = "d" - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(df, "b")) - assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df2, "a")) df2.iloc[0, 0] = "d" - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a")) + assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a")) tm.assert_frame_equal(result, expected) -def test_concat_series(using_copy_on_write): +def test_concat_series(): ser = Series([1, 2], name="a") ser2 = Series([3, 4], name="b") ser_orig = ser.copy() ser2_orig = ser2.copy() result = concat([ser, ser2], axis=1) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), ser.values) - assert np.shares_memory(get_array(result, "b"), ser2.values) - else: - assert not np.shares_memory(get_array(result, "a"), ser.values) - assert not np.shares_memory(get_array(result, "b"), ser2.values) + assert np.shares_memory(get_array(result, "a"), ser.values) + assert np.shares_memory(get_array(result, "b"), ser2.values) result.iloc[0, 0] = 100 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), ser.values) - assert np.shares_memory(get_array(result, "b"), ser2.values) + assert not np.shares_memory(get_array(result, "a"), ser.values) + assert np.shares_memory(get_array(result, "b"), ser2.values) result.iloc[0, 1] = 1000 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), ser2.values) + assert not np.shares_memory(get_array(result, "b"), ser2.values) tm.assert_series_equal(ser, ser_orig) tm.assert_series_equal(ser2, ser2_orig) -def test_concat_frames_chained(using_copy_on_write): +def test_concat_frames_chained(): df1 = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]}) df2 = DataFrame({"c": [4, 5, 6]}) df3 = DataFrame({"d": [4, 5, 6]}) result = concat([concat([df1, df2], axis=1), df3], axis=1) expected = result.copy() - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "c"), get_array(df2, "c")) - assert np.shares_memory(get_array(result, "d"), get_array(df3, "d")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "c"), get_array(df2, "c")) - assert not np.shares_memory(get_array(result, "d"), get_array(df3, "d")) + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "c"), get_array(df2, "c")) + assert np.shares_memory(get_array(result, "d"), get_array(df3, "d")) df1.iloc[0, 0] = 100 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) tm.assert_frame_equal(result, expected) -def test_concat_series_chained(using_copy_on_write): +def test_concat_series_chained(): ser1 = Series([1, 2, 3], name="a") ser2 = Series([4, 5, 6], name="c") ser3 = Series([4, 5, 6], name="d") result = concat([concat([ser1, ser2], axis=1), ser3], axis=1) expected = result.copy() - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(ser1, "a")) - assert np.shares_memory(get_array(result, "c"), get_array(ser2, "c")) - assert np.shares_memory(get_array(result, "d"), get_array(ser3, "d")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(ser1, "a")) - assert not np.shares_memory(get_array(result, "c"), get_array(ser2, "c")) - assert not np.shares_memory(get_array(result, "d"), get_array(ser3, "d")) + assert np.shares_memory(get_array(result, "a"), get_array(ser1, "a")) + assert np.shares_memory(get_array(result, "c"), get_array(ser2, "c")) + assert np.shares_memory(get_array(result, "d"), get_array(ser3, "d")) ser1.iloc[0] = 100 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(ser1, "a")) + assert not np.shares_memory(get_array(result, "a"), get_array(ser1, "a")) tm.assert_frame_equal(result, expected) -def test_concat_series_updating_input(using_copy_on_write): +def test_concat_series_updating_input(): ser = Series([1, 2], name="a") ser2 = Series([3, 4], name="b") expected = DataFrame({"a": [1, 2], "b": [3, 4]}) result = concat([ser, ser2], axis=1) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(ser, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(ser, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(ser, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) ser.iloc[0] = 100 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(ser, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) + assert not np.shares_memory(get_array(result, "a"), get_array(ser, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) tm.assert_frame_equal(result, expected) ser2.iloc[0] = 1000 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) + assert not np.shares_memory(get_array(result, "b"), get_array(ser2, "b")) tm.assert_frame_equal(result, expected) -def test_concat_mixed_series_frame(using_copy_on_write): +def test_concat_mixed_series_frame(): df = DataFrame({"a": [1, 2, 3], "c": 1}) ser = Series([4, 5, 6], name="d") result = concat([df, ser], axis=1) expected = result.copy() - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df, "a")) - assert np.shares_memory(get_array(result, "c"), get_array(df, "c")) - assert np.shares_memory(get_array(result, "d"), get_array(ser, "d")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df, "a")) - assert not np.shares_memory(get_array(result, "c"), get_array(df, "c")) - assert not np.shares_memory(get_array(result, "d"), get_array(ser, "d")) + assert np.shares_memory(get_array(result, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(result, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(result, "d"), get_array(ser, "d")) ser.iloc[0] = 100 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "d"), get_array(ser, "d")) + assert not np.shares_memory(get_array(result, "d"), get_array(ser, "d")) df.iloc[0, 0] = 100 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(result, "a"), get_array(df, "a")) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("copy", [True, None, False]) -def test_concat_copy_keyword(using_copy_on_write, copy): +def test_concat_copy_keyword(copy): df = DataFrame({"a": [1, 2]}) df2 = DataFrame({"b": [1.5, 2.5]}) result = concat([df, df2], axis=1, copy=copy) - if using_copy_on_write or copy is False: - assert np.shares_memory(get_array(df, "a"), get_array(result, "a")) - assert np.shares_memory(get_array(df2, "b"), get_array(result, "b")) - else: - assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) - assert not np.shares_memory(get_array(df2, "b"), get_array(result, "b")) + assert np.shares_memory(get_array(df, "a"), get_array(result, "a")) + assert np.shares_memory(get_array(df2, "b"), get_array(result, "b")) @pytest.mark.parametrize( @@ -204,7 +157,7 @@ def test_concat_copy_keyword(using_copy_on_write, copy): lambda df1, df2, **kwargs: merge(df1, df2, **kwargs), ], ) -def test_merge_on_key(using_copy_on_write, func): +def test_merge_on_key(func): df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]}) df2 = DataFrame({"key": ["a", "b", "c"], "b": [4, 5, 6]}) df1_orig = df1.copy() @@ -212,28 +165,22 @@ def test_merge_on_key(using_copy_on_write, func): result = func(df1, df2, on="key") - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) - assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) - assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) + assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) result.iloc[0, 1] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) result.iloc[0, 2] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) tm.assert_frame_equal(df1, df1_orig) tm.assert_frame_equal(df2, df2_orig) -def test_merge_on_index(using_copy_on_write): +def test_merge_on_index(): df1 = DataFrame({"a": [1, 2, 3]}) df2 = DataFrame({"b": [4, 5, 6]}) df1_orig = df1.copy() @@ -241,21 +188,15 @@ def test_merge_on_index(using_copy_on_write): result = merge(df1, df2, left_index=True, right_index=True) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) result.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) result.iloc[0, 1] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) tm.assert_frame_equal(df1, df1_orig) tm.assert_frame_equal(df2, df2_orig) @@ -267,7 +208,7 @@ def test_merge_on_index(using_copy_on_write): (lambda df1, df2, **kwargs: merge(df1, df2, on="key", **kwargs), "left"), ], ) -def test_merge_on_key_enlarging_one(using_copy_on_write, func, how): +def test_merge_on_key_enlarging_one(func, how): df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]}) df2 = DataFrame({"key": ["a", "b"], "b": [4, 5]}) df1_orig = df1.copy() @@ -275,45 +216,36 @@ def test_merge_on_key_enlarging_one(using_copy_on_write, func, how): result = func(df1, df2, how=how) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) - assert df2._mgr._has_no_reference(1) - assert df2._mgr._has_no_reference(0) - assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) is ( - how == "left" - ) - assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert df2._mgr._has_no_reference(1) + assert df2._mgr._has_no_reference(0) + assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) is ( + how == "left" + ) + assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) if how == "left": result.iloc[0, 1] = 0 else: result.iloc[0, 2] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) tm.assert_frame_equal(df1, df1_orig) tm.assert_frame_equal(df2, df2_orig) @pytest.mark.parametrize("copy", [True, None, False]) -def test_merge_copy_keyword(using_copy_on_write, copy): +def test_merge_copy_keyword(copy): df = DataFrame({"a": [1, 2]}) df2 = DataFrame({"b": [3, 4.5]}) result = df.merge(df2, copy=copy, left_index=True, right_index=True) - if using_copy_on_write or copy is False: - assert np.shares_memory(get_array(df, "a"), get_array(result, "a")) - assert np.shares_memory(get_array(df2, "b"), get_array(result, "b")) - else: - assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) - assert not np.shares_memory(get_array(df2, "b"), get_array(result, "b")) + assert np.shares_memory(get_array(df, "a"), get_array(result, "a")) + assert np.shares_memory(get_array(df2, "b"), get_array(result, "b")) -def test_join_on_key(using_copy_on_write): +def test_join_on_key(): df_index = Index(["a", "b", "c"], name="key") df1 = DataFrame({"a": [1, 2, 3]}, index=df_index.copy(deep=True)) @@ -324,29 +256,23 @@ def test_join_on_key(using_copy_on_write): result = df1.join(df2, on="key") - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) - assert np.shares_memory(get_array(result.index), get_array(df1.index)) - assert not np.shares_memory(get_array(result.index), get_array(df2.index)) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(result.index), get_array(df1.index)) + assert not np.shares_memory(get_array(result.index), get_array(df2.index)) result.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) result.iloc[0, 1] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) tm.assert_frame_equal(df1, df1_orig) tm.assert_frame_equal(df2, df2_orig) -def test_join_multiple_dataframes_on_key(using_copy_on_write): +def test_join_multiple_dataframes_on_key(): df_index = Index(["a", "b", "c"], name="key") df1 = DataFrame({"a": [1, 2, 3]}, index=df_index.copy(deep=True)) @@ -360,36 +286,24 @@ def test_join_multiple_dataframes_on_key(using_copy_on_write): result = df1.join(dfs_list) - if using_copy_on_write: - assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) - assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) - assert np.shares_memory(get_array(result.index), get_array(df1.index)) - assert not np.shares_memory( - get_array(result.index), get_array(dfs_list[0].index) - ) - assert not np.shares_memory( - get_array(result.index), get_array(dfs_list[1].index) - ) - else: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert not np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) - assert not np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) + assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) + assert np.shares_memory(get_array(result.index), get_array(df1.index)) + assert not np.shares_memory(get_array(result.index), get_array(dfs_list[0].index)) + assert not np.shares_memory(get_array(result.index), get_array(dfs_list[1].index)) result.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) - assert np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) - assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) + assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) result.iloc[0, 1] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) - assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) + assert not np.shares_memory(get_array(result, "b"), get_array(dfs_list[0], "b")) + assert np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) result.iloc[0, 2] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) + assert not np.shares_memory(get_array(result, "c"), get_array(dfs_list[1], "c")) tm.assert_frame_equal(df1, df1_orig) for df, df_orig in zip(dfs_list, dfs_list_orig): diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 73919997fa7fd..e96899d155c54 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -16,7 +16,7 @@ from pandas.tests.copy_view.util import get_array -def test_copy(using_copy_on_write): +def test_copy(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_copy = df.copy() @@ -28,49 +28,36 @@ def test_copy(using_copy_on_write): # the deep copy doesn't share memory assert not np.shares_memory(get_array(df_copy, "a"), get_array(df, "a")) - if using_copy_on_write: - assert not df_copy._mgr.blocks[0].refs.has_reference() - assert not df_copy._mgr.blocks[1].refs.has_reference() + assert not df_copy._mgr.blocks[0].refs.has_reference() + assert not df_copy._mgr.blocks[1].refs.has_reference() # mutating copy doesn't mutate original df_copy.iloc[0, 0] = 0 assert df.iloc[0, 0] == 1 -def test_copy_shallow(using_copy_on_write): +def test_copy_shallow(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_copy = df.copy(deep=False) # the shallow copy also makes a shallow copy of the index - if using_copy_on_write: - assert df_copy.index is not df.index - assert df_copy.columns is not df.columns - assert df_copy.index.is_(df.index) - assert df_copy.columns.is_(df.columns) - else: - assert df_copy.index is df.index - assert df_copy.columns is df.columns + assert df_copy.index is not df.index + assert df_copy.columns is not df.columns + assert df_copy.index.is_(df.index) + assert df_copy.columns.is_(df.columns) # the shallow copy still shares memory assert np.shares_memory(get_array(df_copy, "a"), get_array(df, "a")) - if using_copy_on_write: - assert df_copy._mgr.blocks[0].refs.has_reference() - assert df_copy._mgr.blocks[1].refs.has_reference() - - if using_copy_on_write: - # mutating shallow copy doesn't mutate original - df_copy.iloc[0, 0] = 0 - assert df.iloc[0, 0] == 1 - # mutating triggered a copy-on-write -> no longer shares memory - assert not np.shares_memory(get_array(df_copy, "a"), get_array(df, "a")) - # but still shares memory for the other columns/blocks - assert np.shares_memory(get_array(df_copy, "c"), get_array(df, "c")) - else: - # mutating shallow copy does mutate original - df_copy.iloc[0, 0] = 0 - assert df.iloc[0, 0] == 0 - # and still shares memory - assert np.shares_memory(get_array(df_copy, "a"), get_array(df, "a")) + assert df_copy._mgr.blocks[0].refs.has_reference() + assert df_copy._mgr.blocks[1].refs.has_reference() + + # mutating shallow copy doesn't mutate original + df_copy.iloc[0, 0] = 0 + assert df.iloc[0, 0] == 1 + # mutating triggered a copy-on-write -> no longer shares memory + assert not np.shares_memory(get_array(df_copy, "a"), get_array(df, "a")) + # but still shares memory for the other columns/blocks + assert np.shares_memory(get_array(df_copy, "c"), get_array(df, "c")) @pytest.mark.parametrize("copy", [True, None, False]) @@ -113,7 +100,7 @@ def test_copy_shallow(using_copy_on_write): "set_flags", ], ) -def test_methods_copy_keyword(request, method, copy, using_copy_on_write): +def test_methods_copy_keyword(request, method, copy): index = None if "to_timestamp" in request.node.callspec.id: index = period_range("2012-01-01", freq="D", periods=3) @@ -126,18 +113,7 @@ def test_methods_copy_keyword(request, method, copy, using_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}, index=index) df2 = method(df, copy=copy) - - share_memory = using_copy_on_write or copy is False - - if request.node.callspec.id.startswith("reindex-"): - # TODO copy=False without CoW still returns a copy in this case - if not using_copy_on_write and copy is False: - share_memory = False - - if share_memory: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) @pytest.mark.parametrize("copy", [True, None, False]) @@ -180,7 +156,7 @@ def test_methods_copy_keyword(request, method, copy, using_copy_on_write): "set_flags", ], ) -def test_methods_series_copy_keyword(request, method, copy, using_copy_on_write): +def test_methods_series_copy_keyword(request, method, copy): index = None if "to_timestamp" in request.node.callspec.id: index = period_range("2012-01-01", freq="D", periods=3) @@ -195,32 +171,21 @@ def test_methods_series_copy_keyword(request, method, copy, using_copy_on_write) ser = Series([1, 2, 3], index=index) ser2 = method(ser, copy=copy) - - share_memory = using_copy_on_write or copy is False - - if share_memory: - assert np.shares_memory(get_array(ser2), get_array(ser)) - else: - assert not np.shares_memory(get_array(ser2), get_array(ser)) + assert np.shares_memory(get_array(ser2), get_array(ser)) @pytest.mark.parametrize("copy", [True, None, False]) -def test_transpose_copy_keyword(using_copy_on_write, copy): +def test_transpose_copy_keyword(copy): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) result = df.transpose(copy=copy) - share_memory = using_copy_on_write or copy is False or copy is None - - if share_memory: - assert np.shares_memory(get_array(df, "a"), get_array(result, 0)) - else: - assert not np.shares_memory(get_array(df, "a"), get_array(result, 0)) + assert np.shares_memory(get_array(df, "a"), get_array(result, 0)) # ----------------------------------------------------------------------------- # DataFrame methods returning new DataFrame using shallow copy -def test_reset_index(using_copy_on_write): +def test_reset_index(): # Case: resetting the index (i.e. adding a new column) + mutating the # resulting dataframe df = DataFrame( @@ -230,28 +195,23 @@ def test_reset_index(using_copy_on_write): df2 = df.reset_index() df2._mgr._verify_integrity() - if using_copy_on_write: - # still shares memory (df2 is a shallow copy) - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + # still shares memory (df2 is a shallow copy) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) # mutating df2 triggers a copy-on-write for that column / block df2.iloc[0, 2] = 0 assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("index", [pd.RangeIndex(0, 2), Index([1, 2])]) -def test_reset_index_series_drop(using_copy_on_write, index): +def test_reset_index_series_drop(index): ser = Series([1, 2], index=index) ser_orig = ser.copy() ser2 = ser.reset_index(drop=True) - if using_copy_on_write: - assert np.shares_memory(get_array(ser), get_array(ser2)) - assert not ser._mgr._has_no_reference(0) - else: - assert not np.shares_memory(get_array(ser), get_array(ser2)) + assert np.shares_memory(get_array(ser), get_array(ser2)) + assert not ser._mgr._has_no_reference(0) ser2.iloc[0] = 100 tm.assert_series_equal(ser, ser_orig) @@ -268,45 +228,39 @@ def test_groupby_column_index_in_references(): tm.assert_frame_equal(result, expected) -def test_rename_columns(using_copy_on_write): +def test_rename_columns(): # Case: renaming columns returns a new dataframe # + afterwards modifying the result df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.rename(columns=str.upper) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "A"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "A"), get_array(df, "a")) df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "A"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "C"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "C"), get_array(df, "c")) expected = DataFrame({"A": [0, 2, 3], "B": [4, 5, 6], "C": [0.1, 0.2, 0.3]}) tm.assert_frame_equal(df2, expected) tm.assert_frame_equal(df, df_orig) -def test_rename_columns_modify_parent(using_copy_on_write): +def test_rename_columns_modify_parent(): # Case: renaming columns returns a new dataframe # + afterwards modifying the original (parent) dataframe df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df2 = df.rename(columns=str.upper) df2_orig = df2.copy() - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "A"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "A"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "A"), get_array(df, "a")) df.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "A"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "C"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "C"), get_array(df, "c")) expected = DataFrame({"a": [0, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) tm.assert_frame_equal(df, expected) tm.assert_frame_equal(df2, df2_orig) -def test_pipe(using_copy_on_write): +def test_pipe(): df = DataFrame({"a": [1, 2, 3], "b": 1.5}) df_orig = df.copy() @@ -319,18 +273,12 @@ def testfunc(df): # mutating df2 triggers a copy-on-write for that column df2.iloc[0, 0] = 0 - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - expected = DataFrame({"a": [0, 2, 3], "b": 1.5}) - tm.assert_frame_equal(df, expected) - - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + tm.assert_frame_equal(df, df_orig) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) -def test_pipe_modify_df(using_copy_on_write): +def test_pipe_modify_df(): df = DataFrame({"a": [1, 2, 3], "b": 1.5}) df_orig = df.copy() @@ -342,34 +290,24 @@ def testfunc(df): assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - expected = DataFrame({"a": [100, 2, 3], "b": 1.5}) - tm.assert_frame_equal(df, expected) - - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + tm.assert_frame_equal(df, df_orig) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) -def test_reindex_columns(using_copy_on_write): +def test_reindex_columns(): # Case: reindexing the column returns a new dataframe # + afterwards modifying the result df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.reindex(columns=["a", "c"]) - if using_copy_on_write: - # still shares memory (df2 is a shallow copy) - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + # still shares memory (df2 is a shallow copy) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) tm.assert_frame_equal(df, df_orig) @@ -383,46 +321,37 @@ def test_reindex_columns(using_copy_on_write): ], ids=["identical", "view", "copy", "values"], ) -def test_reindex_rows(index, using_copy_on_write): +def test_reindex_rows(index): # Case: reindexing the rows with an index that matches the current index # can use a shallow copy df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.reindex(index=index(df.index)) - if using_copy_on_write: - # still shares memory (df2 is a shallow copy) - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + # still shares memory (df2 is a shallow copy) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) tm.assert_frame_equal(df, df_orig) -def test_drop_on_column(using_copy_on_write): +def test_drop_on_column(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.drop(columns="a") df2._mgr._verify_integrity() - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) - else: - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) tm.assert_frame_equal(df, df_orig) -def test_select_dtypes(using_copy_on_write): +def test_select_dtypes(): # Case: selecting columns using `select_dtypes()` returns a new dataframe # + afterwards modifying the result df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) @@ -430,40 +359,31 @@ def test_select_dtypes(using_copy_on_write): df2 = df.select_dtypes("int64") df2._mgr._verify_integrity() - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column/block df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize( "filter_kwargs", [{"items": ["a"]}, {"like": "a"}, {"regex": "a"}] ) -def test_filter(using_copy_on_write, filter_kwargs): +def test_filter(filter_kwargs): # Case: selecting columns using `filter()` returns a new dataframe # + afterwards modifying the result df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.filter(**filter_kwargs) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column/block - if using_copy_on_write: - df2.iloc[0, 0] = 0 - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + df2.iloc[0, 0] = 0 + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) -def test_shift_no_op(using_copy_on_write): +def test_shift_no_op(): df = DataFrame( [[1, 2], [3, 4], [5, 6]], index=date_range("2020-01-01", "2020-01-03"), @@ -471,20 +391,15 @@ def test_shift_no_op(using_copy_on_write): ) df_orig = df.copy() df2 = df.shift(periods=0) - - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) - assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) tm.assert_frame_equal(df2, df_orig) -def test_shift_index(using_copy_on_write): +def test_shift_index(): df = DataFrame( [[1, 2], [3, 4], [5, 6]], index=date_range("2020-01-01", "2020-01-03"), @@ -495,7 +410,7 @@ def test_shift_index(using_copy_on_write): assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) -def test_shift_rows_freq(using_copy_on_write): +def test_shift_rows_freq(): df = DataFrame( [[1, 2], [3, 4], [5, 6]], index=date_range("2020-01-01", "2020-01-03"), @@ -505,18 +420,13 @@ def test_shift_rows_freq(using_copy_on_write): df_orig.index = date_range("2020-01-02", "2020-01-04") df2 = df.shift(periods=1, freq="1D") - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) tm.assert_frame_equal(df2, df_orig) -def test_shift_columns(using_copy_on_write): +def test_shift_columns(): df = DataFrame( [[1, 2], [3, 4], [5, 6]], columns=date_range("2020-01-01", "2020-01-02") ) @@ -524,18 +434,17 @@ def test_shift_columns(using_copy_on_write): assert np.shares_memory(get_array(df2, "2020-01-02"), get_array(df, "2020-01-01")) df.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory( - get_array(df2, "2020-01-02"), get_array(df, "2020-01-01") - ) - expected = DataFrame( - [[np.nan, 1], [np.nan, 3], [np.nan, 5]], - columns=date_range("2020-01-01", "2020-01-02"), - ) - tm.assert_frame_equal(df2, expected) + assert not np.shares_memory( + get_array(df2, "2020-01-02"), get_array(df, "2020-01-01") + ) + expected = DataFrame( + [[np.nan, 1], [np.nan, 3], [np.nan, 5]], + columns=date_range("2020-01-01", "2020-01-02"), + ) + tm.assert_frame_equal(df2, expected) -def test_pop(using_copy_on_write): +def test_pop(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() view_original = df[:] @@ -544,16 +453,11 @@ def test_pop(using_copy_on_write): assert np.shares_memory(result.values, get_array(view_original, "a")) assert np.shares_memory(get_array(df, "b"), get_array(view_original, "b")) - if using_copy_on_write: - result.iloc[0] = 0 - assert not np.shares_memory(result.values, get_array(view_original, "a")) + result.iloc[0] = 0 + assert not np.shares_memory(result.values, get_array(view_original, "a")) df.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df, "b"), get_array(view_original, "b")) - tm.assert_frame_equal(view_original, df_orig) - else: - expected = DataFrame({"a": [1, 2, 3], "b": [0, 5, 6], "c": [0.1, 0.2, 0.3]}) - tm.assert_frame_equal(view_original, expected) + assert not np.shares_memory(get_array(df, "b"), get_array(view_original, "b")) + tm.assert_frame_equal(view_original, df_orig) @pytest.mark.parametrize( @@ -564,46 +468,35 @@ def test_pop(using_copy_on_write): lambda x, y: x.align(y.a.iloc[slice(0, 1)], axis=1), ], ) -def test_align_frame(using_copy_on_write, func): +def test_align_frame(func): df = DataFrame({"a": [1, 2, 3], "b": "a"}) df_orig = df.copy() df_changed = df[["b", "a"]].copy() df2, _ = func(df, df_changed) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) -def test_align_series(using_copy_on_write): +def test_align_series(): ser = Series([1, 2]) ser_orig = ser.copy() ser_other = ser.copy() ser2, ser_other_result = ser.align(ser_other) - if using_copy_on_write: - assert np.shares_memory(ser2.values, ser.values) - assert np.shares_memory(ser_other_result.values, ser_other.values) - else: - assert not np.shares_memory(ser2.values, ser.values) - assert not np.shares_memory(ser_other_result.values, ser_other.values) - + assert np.shares_memory(ser2.values, ser.values) + assert np.shares_memory(ser_other_result.values, ser_other.values) ser2.iloc[0] = 0 ser_other_result.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(ser2.values, ser.values) - assert not np.shares_memory(ser_other_result.values, ser_other.values) + assert not np.shares_memory(ser2.values, ser.values) + assert not np.shares_memory(ser_other_result.values, ser_other.values) tm.assert_series_equal(ser, ser_orig) tm.assert_series_equal(ser_other, ser_orig) -def test_align_copy_false(using_copy_on_write): +def test_align_copy_false(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) df_orig = df.copy() df2, df3 = df.align(df, copy=False) @@ -611,15 +504,14 @@ def test_align_copy_false(using_copy_on_write): assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) - if using_copy_on_write: - df2.loc[0, "a"] = 0 - tm.assert_frame_equal(df, df_orig) # Original is unchanged + df2.loc[0, "a"] = 0 + tm.assert_frame_equal(df, df_orig) # Original is unchanged - df3.loc[0, "a"] = 0 - tm.assert_frame_equal(df, df_orig) # Original is unchanged + df3.loc[0, "a"] = 0 + tm.assert_frame_equal(df, df_orig) # Original is unchanged -def test_align_with_series_copy_false(using_copy_on_write): +def test_align_with_series_copy_false(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) ser = Series([1, 2, 3], name="x") ser_orig = ser.copy() @@ -630,15 +522,14 @@ def test_align_with_series_copy_false(using_copy_on_write): assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) assert np.shares_memory(get_array(ser, "x"), get_array(ser2, "x")) - if using_copy_on_write: - df2.loc[0, "a"] = 0 - tm.assert_frame_equal(df, df_orig) # Original is unchanged + df2.loc[0, "a"] = 0 + tm.assert_frame_equal(df, df_orig) # Original is unchanged - ser2.loc[0] = 0 - tm.assert_series_equal(ser, ser_orig) # Original is unchanged + ser2.loc[0] = 0 + tm.assert_series_equal(ser, ser_orig) # Original is unchanged -def test_to_frame(using_copy_on_write): +def test_to_frame(): # Case: converting a Series to a DataFrame with to_frame ser = Series([1, 2, 3]) ser_orig = ser.copy() @@ -650,26 +541,15 @@ def test_to_frame(using_copy_on_write): df.iloc[0, 0] = 0 - if using_copy_on_write: - # mutating df triggers a copy-on-write for that column - assert not np.shares_memory(ser.values, get_array(df, 0)) - tm.assert_series_equal(ser, ser_orig) - else: - # but currently select_dtypes() actually returns a view -> mutates parent - expected = ser_orig.copy() - expected.iloc[0] = 0 - tm.assert_series_equal(ser, expected) + # mutating df triggers a copy-on-write for that column + assert not np.shares_memory(ser.values, get_array(df, 0)) + tm.assert_series_equal(ser, ser_orig) # modify original series -> don't modify dataframe df = ser[:].to_frame() ser.iloc[0] = 0 - if using_copy_on_write: - tm.assert_frame_equal(df, ser_orig.to_frame()) - else: - expected = ser_orig.copy().to_frame() - expected.iloc[0, 0] = 0 - tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(df, ser_orig.to_frame()) @pytest.mark.parametrize( @@ -682,37 +562,29 @@ def test_to_frame(using_copy_on_write): ], ids=["shallow-copy", "reset_index", "rename", "select_dtypes"], ) -def test_chained_methods(request, method, idx, using_copy_on_write): +def test_chained_methods(request, method, idx): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() - # when not using CoW, only the copy() variant actually gives a view - df2_is_view = not using_copy_on_write and request.node.callspec.id == "shallow-copy" - # modify df2 -> don't modify df df2 = method(df) df2.iloc[0, idx] = 0 - if not df2_is_view: - tm.assert_frame_equal(df, df_orig) + tm.assert_frame_equal(df, df_orig) # modify df -> don't modify df2 df2 = method(df) df.iloc[0, 0] = 0 - if not df2_is_view: - tm.assert_frame_equal(df2.iloc[:, idx:], df_orig) + tm.assert_frame_equal(df2.iloc[:, idx:], df_orig) @pytest.mark.parametrize("obj", [Series([1, 2], name="a"), DataFrame({"a": [1, 2]})]) -def test_to_timestamp(using_copy_on_write, obj): +def test_to_timestamp(obj): obj.index = Index([Period("2012-1-1", freq="D"), Period("2012-1-2", freq="D")]) obj_orig = obj.copy() obj2 = obj.to_timestamp() - if using_copy_on_write: - assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) - else: - assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) + assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) # mutating obj2 triggers a copy-on-write for that column / block obj2.iloc[0] = 0 @@ -721,16 +593,13 @@ def test_to_timestamp(using_copy_on_write, obj): @pytest.mark.parametrize("obj", [Series([1, 2], name="a"), DataFrame({"a": [1, 2]})]) -def test_to_period(using_copy_on_write, obj): +def test_to_period(obj): obj.index = Index([Timestamp("2019-12-31"), Timestamp("2020-12-31")]) obj_orig = obj.copy() obj2 = obj.to_period(freq="Y") - if using_copy_on_write: - assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) - else: - assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) + assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) # mutating obj2 triggers a copy-on-write for that column / block obj2.iloc[0] = 0 @@ -738,16 +607,13 @@ def test_to_period(using_copy_on_write, obj): tm.assert_equal(obj, obj_orig) -def test_set_index(using_copy_on_write): +def test_set_index(): # GH 49473 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.set_index("a") - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - else: - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) # mutating df2 triggers a copy-on-write for that column / block df2.iloc[0, 1] = 0 @@ -764,20 +630,18 @@ def test_set_index_mutating_parent_does_not_mutate_index(): tm.assert_frame_equal(result, expected) -def test_add_prefix(using_copy_on_write): +def test_add_prefix(): # GH 49473 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.add_prefix("CoW_") - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "CoW_a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "CoW_a"), get_array(df, "a")) df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "CoW_a"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "CoW_c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "CoW_c"), get_array(df, "c")) expected = DataFrame( {"CoW_a": [0, 2, 3], "CoW_b": [4, 5, 6], "CoW_c": [0.1, 0.2, 0.3]} ) @@ -785,17 +649,15 @@ def test_add_prefix(using_copy_on_write): tm.assert_frame_equal(df, df_orig) -def test_add_suffix(using_copy_on_write): +def test_add_suffix(): # GH 49473 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.add_suffix("_CoW") - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a_CoW"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a_CoW"), get_array(df, "a")) df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "a_CoW"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "c_CoW"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "c_CoW"), get_array(df, "c")) expected = DataFrame( {"a_CoW": [0, 2, 3], "b_CoW": [4, 5, 6], "c_CoW": [0.1, 0.2, 0.3]} ) @@ -804,36 +666,27 @@ def test_add_suffix(using_copy_on_write): @pytest.mark.parametrize("axis, val", [(0, 5.5), (1, np.nan)]) -def test_dropna(using_copy_on_write, axis, val): +def test_dropna(axis, val): df = DataFrame({"a": [1, 2, 3], "b": [4, val, 6], "c": "d"}) df_orig = df.copy() df2 = df.dropna(axis=axis) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("val", [5, 5.5]) -def test_dropna_series(using_copy_on_write, val): +def test_dropna_series(val): ser = Series([1, val, 4]) ser_orig = ser.copy() ser2 = ser.dropna() - - if using_copy_on_write: - assert np.shares_memory(ser2.values, ser.values) - else: - assert not np.shares_memory(ser2.values, ser.values) + assert np.shares_memory(ser2.values, ser.values) ser2.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(ser2.values, ser.values) + assert not np.shares_memory(ser2.values, ser.values) tm.assert_series_equal(ser, ser_orig) @@ -846,52 +699,40 @@ def test_dropna_series(using_copy_on_write, val): lambda df: df.tail(3), ], ) -def test_head_tail(method, using_copy_on_write): +def test_head_tail(method): df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = method(df) df2._mgr._verify_integrity() - if using_copy_on_write: - # We are explicitly deviating for CoW here to make an eager copy (avoids - # tracking references for very cheap ops) - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + # We are explicitly deviating for CoW here to make an eager copy (avoids + # tracking references for very cheap ops) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) # modify df2 to trigger CoW for that block df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - # without CoW enabled, head and tail return views. Mutating df2 also mutates df. - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - df2.iloc[0, 0] = 1 + assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) -def test_infer_objects(using_copy_on_write): +def test_infer_objects(): df = DataFrame({"a": [1, 2], "b": "c", "c": 1, "d": "x"}) df_orig = df.copy() df2 = df.infer_objects() - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) df2.iloc[0, 0] = 0 df2.iloc[0, 1] = "d" - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) tm.assert_frame_equal(df, df_orig) -def test_infer_objects_no_reference(using_copy_on_write): +def test_infer_objects_no_reference(): df = DataFrame( { "a": [1, 2], @@ -912,14 +753,13 @@ def test_infer_objects_no_reference(using_copy_on_write): df.iloc[0, 0] = 0 df.iloc[0, 1] = "d" df.iloc[0, 3] = Timestamp("2018-12-31") - if using_copy_on_write: - assert np.shares_memory(arr_a, get_array(df, "a")) - # TODO(CoW): Block splitting causes references here - assert not np.shares_memory(arr_b, get_array(df, "b")) - assert np.shares_memory(arr_d, get_array(df, "d")) + assert np.shares_memory(arr_a, get_array(df, "a")) + # TODO(CoW): Block splitting causes references here + assert not np.shares_memory(arr_b, get_array(df, "b")) + assert np.shares_memory(arr_d, get_array(df, "d")) -def test_infer_objects_reference(using_copy_on_write): +def test_infer_objects_reference(): df = DataFrame( { "a": [1, 2], @@ -940,10 +780,9 @@ def test_infer_objects_reference(using_copy_on_write): df.iloc[0, 0] = 0 df.iloc[0, 1] = "d" df.iloc[0, 3] = Timestamp("2018-12-31") - if using_copy_on_write: - assert not np.shares_memory(arr_a, get_array(df, "a")) - assert not np.shares_memory(arr_b, get_array(df, "b")) - assert np.shares_memory(arr_d, get_array(df, "d")) + assert not np.shares_memory(arr_a, get_array(df, "a")) + assert not np.shares_memory(arr_b, get_array(df, "b")) + assert np.shares_memory(arr_d, get_array(df, "d")) @pytest.mark.parametrize( @@ -953,103 +792,76 @@ def test_infer_objects_reference(using_copy_on_write): {"before": 0, "after": 1, "axis": 0}, ], ) -def test_truncate(using_copy_on_write, kwargs): +def test_truncate(kwargs): df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 2}) df_orig = df.copy() df2 = df.truncate(**kwargs) df2._mgr._verify_integrity() - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("method", ["assign", "drop_duplicates"]) -def test_assign_drop_duplicates(using_copy_on_write, method): +def test_assign_drop_duplicates(method): df = DataFrame({"a": [1, 2, 3]}) df_orig = df.copy() df2 = getattr(df, method)() df2._mgr._verify_integrity() - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("obj", [Series([1, 2]), DataFrame({"a": [1, 2]})]) -def test_take(using_copy_on_write, obj): +def test_take(obj): # Check that no copy is made when we take all rows in original order obj_orig = obj.copy() obj2 = obj.take([0, 1]) - - if using_copy_on_write: - assert np.shares_memory(obj2.values, obj.values) - else: - assert not np.shares_memory(obj2.values, obj.values) + assert np.shares_memory(obj2.values, obj.values) obj2.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(obj2.values, obj.values) + assert not np.shares_memory(obj2.values, obj.values) tm.assert_equal(obj, obj_orig) @pytest.mark.parametrize("obj", [Series([1, 2]), DataFrame({"a": [1, 2]})]) -def test_between_time(using_copy_on_write, obj): +def test_between_time(obj): obj.index = date_range("2018-04-09", periods=2, freq="1D20min") obj_orig = obj.copy() obj2 = obj.between_time("0:00", "1:00") - - if using_copy_on_write: - assert np.shares_memory(obj2.values, obj.values) - else: - assert not np.shares_memory(obj2.values, obj.values) + assert np.shares_memory(obj2.values, obj.values) obj2.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(obj2.values, obj.values) + assert not np.shares_memory(obj2.values, obj.values) tm.assert_equal(obj, obj_orig) -def test_reindex_like(using_copy_on_write): +def test_reindex_like(): df = DataFrame({"a": [1, 2], "b": "a"}) other = DataFrame({"b": "a", "a": [1, 2]}) df_orig = df.copy() df2 = df.reindex_like(other) - - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 1] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) -def test_sort_index(using_copy_on_write): +def test_sort_index(): # GH 49473 ser = Series([1, 2, 3]) ser_orig = ser.copy() ser2 = ser.sort_index() - - if using_copy_on_write: - assert np.shares_memory(ser.values, ser2.values) - else: - assert not np.shares_memory(ser.values, ser2.values) + assert np.shares_memory(ser.values, ser2.values) # mutating ser triggers a copy-on-write for the column / block ser2.iloc[0] = 0 @@ -1061,14 +873,10 @@ def test_sort_index(using_copy_on_write): "obj, kwargs", [(Series([1, 2, 3], name="a"), {}), (DataFrame({"a": [1, 2, 3]}), {"by": "a"})], ) -def test_sort_values(using_copy_on_write, obj, kwargs): +def test_sort_values(obj, kwargs): obj_orig = obj.copy() obj2 = obj.sort_values(**kwargs) - - if using_copy_on_write: - assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) - else: - assert not np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) + assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) # mutating df triggers a copy-on-write for the column / block obj2.iloc[0] = 0 @@ -1080,7 +888,7 @@ def test_sort_values(using_copy_on_write, obj, kwargs): "obj, kwargs", [(Series([1, 2, 3], name="a"), {}), (DataFrame({"a": [1, 2, 3]}), {"by": "a"})], ) -def test_sort_values_inplace(using_copy_on_write, obj, kwargs): +def test_sort_values_inplace(obj, kwargs): obj_orig = obj.copy() view = obj[:] obj.sort_values(inplace=True, **kwargs) @@ -1089,105 +897,79 @@ def test_sort_values_inplace(using_copy_on_write, obj, kwargs): # mutating obj triggers a copy-on-write for the column / block obj.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(obj, "a"), get_array(view, "a")) - tm.assert_equal(view, obj_orig) - else: - assert np.shares_memory(get_array(obj, "a"), get_array(view, "a")) + assert not np.shares_memory(get_array(obj, "a"), get_array(view, "a")) + tm.assert_equal(view, obj_orig) @pytest.mark.parametrize("decimals", [-1, 0, 1]) -def test_round(using_copy_on_write, decimals): +def test_round(decimals): df = DataFrame({"a": [1, 2], "b": "c"}) df_orig = df.copy() df2 = df.round(decimals=decimals) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - # TODO: Make inplace by using out parameter of ndarray.round? - if decimals >= 0: - # Ensure lazy copy if no-op - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + # TODO: Make inplace by using out parameter of ndarray.round? + if decimals >= 0: + # Ensure lazy copy if no-op + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) else: - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 1] = "d" df2.iloc[0, 0] = 4 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) -def test_reorder_levels(using_copy_on_write): +def test_reorder_levels(): index = MultiIndex.from_tuples( [(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"] ) df = DataFrame({"a": [1, 2, 3, 4]}, index=index) df_orig = df.copy() df2 = df.reorder_levels(order=["two", "one"]) - - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) -def test_series_reorder_levels(using_copy_on_write): +def test_series_reorder_levels(): index = MultiIndex.from_tuples( [(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"] ) ser = Series([1, 2, 3, 4], index=index) ser_orig = ser.copy() ser2 = ser.reorder_levels(order=["two", "one"]) - - if using_copy_on_write: - assert np.shares_memory(ser2.values, ser.values) - else: - assert not np.shares_memory(ser2.values, ser.values) + assert np.shares_memory(ser2.values, ser.values) ser2.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(ser2.values, ser.values) + assert not np.shares_memory(ser2.values, ser.values) tm.assert_series_equal(ser, ser_orig) @pytest.mark.parametrize("obj", [Series([1, 2, 3]), DataFrame({"a": [1, 2, 3]})]) -def test_swaplevel(using_copy_on_write, obj): +def test_swaplevel(obj): index = MultiIndex.from_tuples([(1, 1), (1, 2), (2, 1)], names=["one", "two"]) obj.index = index obj_orig = obj.copy() obj2 = obj.swaplevel() - - if using_copy_on_write: - assert np.shares_memory(obj2.values, obj.values) - else: - assert not np.shares_memory(obj2.values, obj.values) + assert np.shares_memory(obj2.values, obj.values) obj2.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(obj2.values, obj.values) + assert not np.shares_memory(obj2.values, obj.values) tm.assert_equal(obj, obj_orig) -def test_frame_set_axis(using_copy_on_write): +def test_frame_set_axis(): # GH 49473 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df.set_axis(["a", "b", "c"], axis="index") - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column / block df2.iloc[0, 0] = 0 @@ -1195,16 +977,12 @@ def test_frame_set_axis(using_copy_on_write): tm.assert_frame_equal(df, df_orig) -def test_series_set_axis(using_copy_on_write): +def test_series_set_axis(): # GH 49473 ser = Series([1, 2, 3]) ser_orig = ser.copy() ser2 = ser.set_axis(["a", "b", "c"], axis="index") - - if using_copy_on_write: - assert np.shares_memory(ser, ser2) - else: - assert not np.shares_memory(ser, ser2) + assert np.shares_memory(ser, ser2) # mutating ser triggers a copy-on-write for the column / block ser2.iloc[0] = 0 @@ -1212,7 +990,7 @@ def test_series_set_axis(using_copy_on_write): tm.assert_series_equal(ser, ser_orig) -def test_set_flags(using_copy_on_write): +def test_set_flags(): ser = Series([1, 2, 3]) ser_orig = ser.copy() ser2 = ser.set_flags(allows_duplicate_labels=False) @@ -1221,47 +999,33 @@ def test_set_flags(using_copy_on_write): # mutating ser triggers a copy-on-write for the column / block ser2.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(ser2, ser) - tm.assert_series_equal(ser, ser_orig) - else: - assert np.shares_memory(ser2, ser) - expected = Series([0, 2, 3]) - tm.assert_series_equal(ser, expected) + assert not np.shares_memory(ser2, ser) + tm.assert_series_equal(ser, ser_orig) @pytest.mark.parametrize("kwargs", [{"mapper": "test"}, {"index": "test"}]) -def test_rename_axis(using_copy_on_write, kwargs): +def test_rename_axis(kwargs): df = DataFrame({"a": [1, 2, 3, 4]}, index=Index([1, 2, 3, 4], name="a")) df_orig = df.copy() df2 = df.rename_axis(**kwargs) - - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize( "func, tz", [("tz_convert", "Europe/Berlin"), ("tz_localize", None)] ) -def test_tz_convert_localize(using_copy_on_write, func, tz): +def test_tz_convert_localize(func, tz): # GH 49473 ser = Series( [1, 2], index=date_range(start="2014-08-01 09:00", freq="h", periods=2, tz=tz) ) ser_orig = ser.copy() ser2 = getattr(ser, func)("US/Central") - - if using_copy_on_write: - assert np.shares_memory(ser.values, ser2.values) - else: - assert not np.shares_memory(ser.values, ser2.values) + assert np.shares_memory(ser.values, ser2.values) # mutating ser triggers a copy-on-write for the column / block ser2.iloc[0] = 0 @@ -1269,31 +1033,26 @@ def test_tz_convert_localize(using_copy_on_write, func, tz): tm.assert_series_equal(ser, ser_orig) -def test_droplevel(using_copy_on_write): +def test_droplevel(): # GH 49473 index = MultiIndex.from_tuples([(1, 1), (1, 2), (2, 1)], names=["one", "two"]) df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}, index=index) df_orig = df.copy() df2 = df.droplevel(0) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c")) - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column / block df2.iloc[0, 0] = 0 assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) tm.assert_frame_equal(df, df_orig) -def test_squeeze(using_copy_on_write): +def test_squeeze(): df = DataFrame({"a": [1, 2, 3]}) df_orig = df.copy() series = df.squeeze() @@ -1303,16 +1062,11 @@ def test_squeeze(using_copy_on_write): # mutating squeezed df triggers a copy-on-write for that column/block series.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(series.values, get_array(df, "a")) - tm.assert_frame_equal(df, df_orig) - else: - # Without CoW the original will be modified - assert np.shares_memory(series.values, get_array(df, "a")) - assert df.loc[0, "a"] == 0 + assert not np.shares_memory(series.values, get_array(df, "a")) + tm.assert_frame_equal(df, df_orig) -def test_items(using_copy_on_write): +def test_items(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) df_orig = df.copy() @@ -1325,54 +1079,41 @@ def test_items(using_copy_on_write): # mutating df triggers a copy-on-write for that column / block ser.iloc[0] = 0 - if using_copy_on_write: - assert not np.shares_memory(get_array(ser, name), get_array(df, name)) - tm.assert_frame_equal(df, df_orig) - else: - # Original frame will be modified - assert df.loc[0, name] == 0 + assert not np.shares_memory(get_array(ser, name), get_array(df, name)) + tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("dtype", ["int64", "Int64"]) -def test_putmask(using_copy_on_write, dtype): +def test_putmask(dtype): df = DataFrame({"a": [1, 2], "b": 1, "c": 2}, dtype=dtype) view = df[:] df_orig = df.copy() df[df == df] = 5 - if using_copy_on_write: - assert not np.shares_memory(get_array(view, "a"), get_array(df, "a")) - tm.assert_frame_equal(view, df_orig) - else: - # Without CoW the original will be modified - assert np.shares_memory(get_array(view, "a"), get_array(df, "a")) - assert view.iloc[0, 0] == 5 + assert not np.shares_memory(get_array(view, "a"), get_array(df, "a")) + tm.assert_frame_equal(view, df_orig) @pytest.mark.parametrize("dtype", ["int64", "Int64"]) -def test_putmask_no_reference(using_copy_on_write, dtype): +def test_putmask_no_reference(dtype): df = DataFrame({"a": [1, 2], "b": 1, "c": 2}, dtype=dtype) arr_a = get_array(df, "a") df[df == df] = 5 - - if using_copy_on_write: - assert np.shares_memory(arr_a, get_array(df, "a")) + assert np.shares_memory(arr_a, get_array(df, "a")) @pytest.mark.parametrize("dtype", ["float64", "Float64"]) -def test_putmask_aligns_rhs_no_reference(using_copy_on_write, dtype): +def test_putmask_aligns_rhs_no_reference(dtype): df = DataFrame({"a": [1.5, 2], "b": 1.5}, dtype=dtype) arr_a = get_array(df, "a") df[df == df] = DataFrame({"a": [5.5, 5]}) - - if using_copy_on_write: - assert np.shares_memory(arr_a, get_array(df, "a")) + assert np.shares_memory(arr_a, get_array(df, "a")) @pytest.mark.parametrize( "val, exp, warn", [(5.5, True, FutureWarning), (5, False, None)] ) -def test_putmask_dont_copy_some_blocks(using_copy_on_write, val, exp, warn): +def test_putmask_dont_copy_some_blocks(val, exp, warn): df = DataFrame({"a": [1, 2], "b": 1, "c": 1.5}) view = df[:] df_orig = df.copy() @@ -1382,19 +1123,13 @@ def test_putmask_dont_copy_some_blocks(using_copy_on_write, val, exp, warn): with tm.assert_produces_warning(warn, match="incompatible dtype"): df[indexer] = val - if using_copy_on_write: - assert not np.shares_memory(get_array(view, "a"), get_array(df, "a")) - # TODO(CoW): Could split blocks to avoid copying the whole block - assert np.shares_memory(get_array(view, "b"), get_array(df, "b")) is exp - assert np.shares_memory(get_array(view, "c"), get_array(df, "c")) - assert df._mgr._has_no_reference(1) is not exp - assert not df._mgr._has_no_reference(2) - tm.assert_frame_equal(view, df_orig) - elif val == 5: - # Without CoW the original will be modified, the other case upcasts, e.g. copy - assert np.shares_memory(get_array(view, "a"), get_array(df, "a")) - assert np.shares_memory(get_array(view, "c"), get_array(df, "c")) - assert view.iloc[0, 0] == 5 + assert not np.shares_memory(get_array(view, "a"), get_array(df, "a")) + # TODO(CoW): Could split blocks to avoid copying the whole block + assert np.shares_memory(get_array(view, "b"), get_array(df, "b")) is exp + assert np.shares_memory(get_array(view, "c"), get_array(df, "c")) + assert df._mgr._has_no_reference(1) is not exp + assert not df._mgr._has_no_reference(2) + tm.assert_frame_equal(view, df_orig) @pytest.mark.parametrize("dtype", ["int64", "Int64"]) @@ -1405,20 +1140,15 @@ def test_putmask_dont_copy_some_blocks(using_copy_on_write, val, exp, warn): lambda ser: ser.mask(ser <= 0, 10), ], ) -def test_where_mask_noop(using_copy_on_write, dtype, func): +def test_where_mask_noop(dtype, func): ser = Series([1, 2, 3], dtype=dtype) ser_orig = ser.copy() result = func(ser) - - if using_copy_on_write: - assert np.shares_memory(get_array(ser), get_array(result)) - else: - assert not np.shares_memory(get_array(ser), get_array(result)) + assert np.shares_memory(get_array(ser), get_array(result)) result.iloc[0] = 10 - if using_copy_on_write: - assert not np.shares_memory(get_array(ser), get_array(result)) + assert not np.shares_memory(get_array(ser), get_array(result)) tm.assert_series_equal(ser, ser_orig) @@ -1430,7 +1160,7 @@ def test_where_mask_noop(using_copy_on_write, dtype, func): lambda ser: ser.mask(ser >= 0, 10), ], ) -def test_where_mask(using_copy_on_write, dtype, func): +def test_where_mask(dtype, func): ser = Series([1, 2, 3], dtype=dtype) ser_orig = ser.copy() @@ -1448,59 +1178,40 @@ def test_where_mask(using_copy_on_write, dtype, func): lambda df, val: df.mask(df >= 0, val), ], ) -def test_where_mask_noop_on_single_column(using_copy_on_write, dtype, val, func): +def test_where_mask_noop_on_single_column(dtype, val, func): df = DataFrame({"a": [1, 2, 3], "b": [-4, -5, -6]}, dtype=dtype) df_orig = df.copy() result = func(df, val) - - if using_copy_on_write: - assert np.shares_memory(get_array(df, "b"), get_array(result, "b")) - assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) - else: - assert not np.shares_memory(get_array(df, "b"), get_array(result, "b")) + assert np.shares_memory(get_array(df, "b"), get_array(result, "b")) + assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) result.iloc[0, 1] = 10 - if using_copy_on_write: - assert not np.shares_memory(get_array(df, "b"), get_array(result, "b")) + assert not np.shares_memory(get_array(df, "b"), get_array(result, "b")) tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("func", ["mask", "where"]) -def test_chained_where_mask(using_copy_on_write, func): +def test_chained_where_mask(func): df = DataFrame({"a": [1, 4, 2], "b": 1}) df_orig = df.copy() - if using_copy_on_write: - with tm.raises_chained_assignment_error(): - getattr(df["a"], func)(df["a"] > 2, 5, inplace=True) - tm.assert_frame_equal(df, df_orig) - - with tm.raises_chained_assignment_error(): - getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True) - tm.assert_frame_equal(df, df_orig) - else: - with tm.assert_produces_warning(FutureWarning, match="inplace method"): - getattr(df["a"], func)(df["a"] > 2, 5, inplace=True) - - with tm.assert_produces_warning(None): - getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True) + with tm.raises_chained_assignment_error(): + getattr(df["a"], func)(df["a"] > 2, 5, inplace=True) + tm.assert_frame_equal(df, df_orig) - with tm.assert_produces_warning(None): - getattr(df[df["a"] > 1], func)(df["a"] > 2, 5, inplace=True) + with tm.raises_chained_assignment_error(): + getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True) + tm.assert_frame_equal(df, df_orig) -def test_asfreq_noop(using_copy_on_write): +def test_asfreq_noop(): df = DataFrame( {"a": [0.0, None, 2.0, 3.0]}, index=date_range("1/1/2000", periods=4, freq="min"), ) df_orig = df.copy() df2 = df.asfreq(freq="min") - - if using_copy_on_write: - assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - else: - assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) # mutating df2 triggers a copy-on-write for that column / block df2.iloc[0, 0] = 0 @@ -1509,17 +1220,16 @@ def test_asfreq_noop(using_copy_on_write): tm.assert_frame_equal(df, df_orig) -def test_iterrows(using_copy_on_write): +def test_iterrows(): df = DataFrame({"a": 0, "b": 1}, index=[1, 2, 3]) df_orig = df.copy() for _, sub in df.iterrows(): sub.iloc[0] = 100 - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) + tm.assert_frame_equal(df, df_orig) -def test_interpolate_creates_copy(using_copy_on_write): +def test_interpolate_creates_copy(): # GH#51126 df = DataFrame({"a": [1.5, np.nan, 3]}) view = df[:] @@ -1527,48 +1237,33 @@ def test_interpolate_creates_copy(using_copy_on_write): df.ffill(inplace=True) df.iloc[0, 0] = 100.5 - - if using_copy_on_write: - tm.assert_frame_equal(view, expected) - else: - expected = DataFrame({"a": [100.5, 1.5, 3]}) - tm.assert_frame_equal(view, expected) + tm.assert_frame_equal(view, expected) -def test_isetitem(using_copy_on_write): +def test_isetitem(): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) df_orig = df.copy() df2 = df.copy(deep=None) # Trigger a CoW df2.isetitem(1, np.array([-1, -2, -3])) # This is inplace - - if using_copy_on_write: - assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) - assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) - else: - assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) - assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) df2.loc[0, "a"] = 0 tm.assert_frame_equal(df, df_orig) # Original is unchanged - - if using_copy_on_write: - assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) - else: - assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) @pytest.mark.parametrize( "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"] ) -def test_isetitem_series(using_copy_on_write, dtype): +def test_isetitem_series(dtype): df = DataFrame({"a": [1, 2, 3], "b": np.array([4, 5, 6], dtype=dtype)}) ser = Series([7, 8, 9]) ser_orig = ser.copy() df.isetitem(0, ser) - if using_copy_on_write: - assert np.shares_memory(get_array(df, "a"), get_array(ser)) - assert not df._mgr._has_no_reference(0) + assert np.shares_memory(get_array(df, "a"), get_array(ser)) + assert not df._mgr._has_no_reference(0) # mutating dataframe doesn't update series df.loc[0, "a"] = 0 @@ -1584,17 +1279,13 @@ def test_isetitem_series(using_copy_on_write, dtype): tm.assert_frame_equal(df, expected) -def test_isetitem_frame(using_copy_on_write): +def test_isetitem_frame(): df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 2}) rhs = DataFrame({"a": [4, 5, 6], "b": 2}) df.isetitem([0, 1], rhs) - if using_copy_on_write: - assert np.shares_memory(get_array(df, "a"), get_array(rhs, "a")) - assert np.shares_memory(get_array(df, "b"), get_array(rhs, "b")) - assert not df._mgr._has_no_reference(0) - else: - assert not np.shares_memory(get_array(df, "a"), get_array(rhs, "a")) - assert not np.shares_memory(get_array(df, "b"), get_array(rhs, "b")) + assert np.shares_memory(get_array(df, "a"), get_array(rhs, "a")) + assert np.shares_memory(get_array(df, "b"), get_array(rhs, "b")) + assert not df._mgr._has_no_reference(0) expected = df.copy() rhs.iloc[0, 0] = 100 rhs.iloc[0, 1] = 100 @@ -1602,7 +1293,7 @@ def test_isetitem_frame(using_copy_on_write): @pytest.mark.parametrize("key", ["a", ["a"]]) -def test_get(using_copy_on_write, key): +def test_get(key): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) df_orig = df.copy() @@ -1618,7 +1309,7 @@ def test_get(using_copy_on_write, key): @pytest.mark.parametrize( "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"] ) -def test_xs(using_copy_on_write, axis, key, dtype): +def test_xs(axis, key, dtype): single_block = dtype == "int64" df = DataFrame( {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)} @@ -1632,15 +1323,13 @@ def test_xs(using_copy_on_write, axis, key, dtype): else: assert result._mgr._has_no_reference(0) - if using_copy_on_write or single_block: - result.iloc[0] = 0 - + result.iloc[0] = 0 tm.assert_frame_equal(df, df_orig) @pytest.mark.parametrize("axis", [0, 1]) @pytest.mark.parametrize("key, level", [("l1", 0), (2, 1)]) -def test_xs_multiindex(using_copy_on_write, key, level, axis): +def test_xs_multiindex(key, level, axis): arr = np.arange(18).reshape(6, 3) index = MultiIndex.from_product([["l1", "l2"], [1, 2, 3]], names=["lev1", "lev2"]) df = DataFrame(arr, index=index, columns=list("abc")) @@ -1659,7 +1348,7 @@ def test_xs_multiindex(using_copy_on_write, key, level, axis): tm.assert_frame_equal(df, df_orig) -def test_update_frame(using_copy_on_write): +def test_update_frame(): df1 = DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]}) df2 = DataFrame({"b": [100.0]}, index=[1]) df1_orig = df1.copy() @@ -1668,16 +1357,13 @@ def test_update_frame(using_copy_on_write): expected = DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 100.0, 6.0]}) tm.assert_frame_equal(df1, expected) - if using_copy_on_write: - # df1 is updated, but its view not - tm.assert_frame_equal(view, df1_orig) - assert np.shares_memory(get_array(df1, "a"), get_array(view, "a")) - assert not np.shares_memory(get_array(df1, "b"), get_array(view, "b")) - else: - tm.assert_frame_equal(view, expected) + # df1 is updated, but its view not + tm.assert_frame_equal(view, df1_orig) + assert np.shares_memory(get_array(df1, "a"), get_array(view, "a")) + assert not np.shares_memory(get_array(df1, "b"), get_array(view, "b")) -def test_update_series(using_copy_on_write): +def test_update_series(): ser1 = Series([1.0, 2.0, 3.0]) ser2 = Series([100.0], index=[1]) ser1_orig = ser1.copy() @@ -1687,11 +1373,8 @@ def test_update_series(using_copy_on_write): expected = Series([1.0, 100.0, 3.0]) tm.assert_series_equal(ser1, expected) - if using_copy_on_write: - # ser1 is updated, but its view not - tm.assert_series_equal(view, ser1_orig) - else: - tm.assert_series_equal(view, expected) + # ser1 is updated, but its view not + tm.assert_series_equal(view, ser1_orig) def test_update_chained_assignment(): @@ -1707,71 +1390,58 @@ def test_update_chained_assignment(): tm.assert_frame_equal(df, df_orig) -def test_inplace_arithmetic_series(using_copy_on_write): +def test_inplace_arithmetic_series(): ser = Series([1, 2, 3]) ser_orig = ser.copy() data = get_array(ser) ser *= 2 - if using_copy_on_write: - # https://github.com/pandas-dev/pandas/pull/55745 - # changed to NOT update inplace because there is no benefit (actual - # operation already done non-inplace). This was only for the optics - # of updating the backing array inplace, but we no longer want to make - # that guarantee - assert not np.shares_memory(get_array(ser), data) - tm.assert_numpy_array_equal(data, get_array(ser_orig)) - else: - assert np.shares_memory(get_array(ser), data) - tm.assert_numpy_array_equal(data, get_array(ser)) + # https://github.com/pandas-dev/pandas/pull/55745 + # changed to NOT update inplace because there is no benefit (actual + # operation already done non-inplace). This was only for the optics + # of updating the backing array inplace, but we no longer want to make + # that guarantee + assert not np.shares_memory(get_array(ser), data) + tm.assert_numpy_array_equal(data, get_array(ser_orig)) -def test_inplace_arithmetic_series_with_reference(using_copy_on_write): +def test_inplace_arithmetic_series_with_reference(): ser = Series([1, 2, 3]) ser_orig = ser.copy() view = ser[:] ser *= 2 - if using_copy_on_write: - assert not np.shares_memory(get_array(ser), get_array(view)) - tm.assert_series_equal(ser_orig, view) - else: - assert np.shares_memory(get_array(ser), get_array(view)) + assert not np.shares_memory(get_array(ser), get_array(view)) + tm.assert_series_equal(ser_orig, view) @pytest.mark.parametrize("copy", [True, False]) -def test_transpose(using_copy_on_write, copy): +def test_transpose(copy): df = DataFrame({"a": [1, 2, 3], "b": 1}) df_orig = df.copy() result = df.transpose(copy=copy) - - if not copy or using_copy_on_write: - assert np.shares_memory(get_array(df, "a"), get_array(result, 0)) - else: - assert not np.shares_memory(get_array(df, "a"), get_array(result, 0)) + assert np.shares_memory(get_array(df, "a"), get_array(result, 0)) result.iloc[0, 0] = 100 - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) + tm.assert_frame_equal(df, df_orig) -def test_transpose_different_dtypes(using_copy_on_write): +def test_transpose_different_dtypes(): df = DataFrame({"a": [1, 2, 3], "b": 1.5}) df_orig = df.copy() result = df.T assert not np.shares_memory(get_array(df, "a"), get_array(result, 0)) result.iloc[0, 0] = 100 - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) + tm.assert_frame_equal(df, df_orig) -def test_transpose_ea_single_column(using_copy_on_write): +def test_transpose_ea_single_column(): df = DataFrame({"a": [1, 2, 3]}, dtype="Int64") result = df.T assert not np.shares_memory(get_array(df, "a"), get_array(result, 0)) -def test_transform_frame(using_copy_on_write): +def test_transform_frame(): df = DataFrame({"a": [1, 2, 3], "b": 1}) df_orig = df.copy() @@ -1780,11 +1450,10 @@ def func(ser): return ser df.transform(func) - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) + tm.assert_frame_equal(df, df_orig) -def test_transform_series(using_copy_on_write): +def test_transform_series(): ser = Series([1, 2, 3]) ser_orig = ser.copy() @@ -1793,8 +1462,7 @@ def func(ser): return ser ser.transform(func) - if using_copy_on_write: - tm.assert_series_equal(ser, ser_orig) + tm.assert_series_equal(ser, ser_orig) def test_count_read_only_array(): @@ -1805,36 +1473,30 @@ def test_count_read_only_array(): tm.assert_series_equal(result, expected) -def test_insert_series(using_copy_on_write): +def test_insert_series(): df = DataFrame({"a": [1, 2, 3]}) ser = Series([1, 2, 3]) ser_orig = ser.copy() df.insert(loc=1, value=ser, column="b") - if using_copy_on_write: - assert np.shares_memory(get_array(ser), get_array(df, "b")) - assert not df._mgr._has_no_reference(1) - else: - assert not np.shares_memory(get_array(ser), get_array(df, "b")) + assert np.shares_memory(get_array(ser), get_array(df, "b")) + assert not df._mgr._has_no_reference(1) df.iloc[0, 1] = 100 tm.assert_series_equal(ser, ser_orig) -def test_eval(using_copy_on_write): +def test_eval(): df = DataFrame({"a": [1, 2, 3], "b": 1}) df_orig = df.copy() result = df.eval("c = a+b") - if using_copy_on_write: - assert np.shares_memory(get_array(df, "a"), get_array(result, "a")) - else: - assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) + assert np.shares_memory(get_array(df, "a"), get_array(result, "a")) result.iloc[0, 0] = 100 tm.assert_frame_equal(df, df_orig) -def test_eval_inplace(using_copy_on_write): +def test_eval_inplace(): df = DataFrame({"a": [1, 2, 3], "b": 1}) df_orig = df.copy() df_view = df[:] @@ -1843,11 +1505,10 @@ def test_eval_inplace(using_copy_on_write): assert np.shares_memory(get_array(df, "a"), get_array(df_view, "a")) df.iloc[0, 0] = 100 - if using_copy_on_write: - tm.assert_frame_equal(df_view, df_orig) + tm.assert_frame_equal(df_view, df_orig) -def test_apply_modify_row(using_copy_on_write): +def test_apply_modify_row(): # Case: applying a function on each row as a Series object, where the # function mutates the row object (which needs to trigger CoW if row is a view) df = DataFrame({"A": [1, 2], "B": [3, 4]}) @@ -1859,10 +1520,7 @@ def transform(row): df.apply(transform, axis=1) - if using_copy_on_write: - tm.assert_frame_equal(df, df_orig) - else: - assert df.loc[0, "B"] == 100 + tm.assert_frame_equal(df, df_orig) # row Series is a copy df = DataFrame({"A": [1, 2], "B": ["b", "c"]}) diff --git a/pandas/tests/generic/test_duplicate_labels.py b/pandas/tests/generic/test_duplicate_labels.py index 43d1c74d76db2..6c108847c2bc6 100644 --- a/pandas/tests/generic/test_duplicate_labels.py +++ b/pandas/tests/generic/test_duplicate_labels.py @@ -89,16 +89,6 @@ def test_preserve_getitem(self): assert df.loc[[0]].flags.allows_duplicate_labels is False assert df.loc[0, ["A"]].flags.allows_duplicate_labels is False - def test_ndframe_getitem_caching_issue(self, request, using_copy_on_write): - if not using_copy_on_write: - request.applymarker(pytest.mark.xfail(reason="Unclear behavior.")) - # NDFrame.__getitem__ will cache the first df['A']. May need to - # invalidate that cache? Update the cached entries? - df = pd.DataFrame({"A": [0]}).set_flags(allows_duplicate_labels=False) - assert df["A"].flags.allows_duplicate_labels is False - df.flags.allows_duplicate_labels = True - assert df["A"].flags.allows_duplicate_labels is True - @pytest.mark.parametrize( "objs, kwargs", [ diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index a7873594ecade..8d173d850583f 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -12,7 +12,7 @@ class TestPeriodIndex: - def test_getitem_periodindex_duplicates_string_slice(self, using_copy_on_write): + def test_getitem_periodindex_duplicates_string_slice(self): # monotonic idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="Y-JUN") ts = Series(np.random.default_rng(2).standard_normal(len(idx)), index=idx) @@ -22,10 +22,7 @@ def test_getitem_periodindex_duplicates_string_slice(self, using_copy_on_write): expected = ts[1:3] tm.assert_series_equal(result, expected) result[:] = 1 - if using_copy_on_write: - tm.assert_series_equal(ts, original) - else: - assert (ts[1:3] == 1).all() + tm.assert_series_equal(ts, original) # not monotonic idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="Y-JUN") diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 79c3780642e7d..d7ef2d39e8df6 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -32,7 +32,7 @@ class TestCommon: @pytest.mark.parametrize("name", [None, "new_name"]) - def test_to_frame(self, name, index_flat, using_copy_on_write): + def test_to_frame(self, name, index_flat): # see GH#15230, GH#22580 idx = index_flat @@ -46,8 +46,6 @@ def test_to_frame(self, name, index_flat, using_copy_on_write): assert df.index is idx assert len(df.columns) == 1 assert df.columns[0] == idx_name - if not using_copy_on_write: - assert df[idx_name].values is not idx.values df = idx.to_frame(index=False, name=idx_name) assert df.index is not idx diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 4faac0e96abc8..92addeb29252a 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -753,7 +753,7 @@ def test_reindex_items(self): mgr.iget(3).internal_values(), reindexed.iget(3).internal_values() ) - def test_get_numeric_data(self, using_copy_on_write): + def test_get_numeric_data(self): mgr = create_mgr( "int: int; float: float; complex: complex;" "str: object; bool: bool; obj: object; dt: datetime", @@ -774,18 +774,12 @@ def test_get_numeric_data(self, using_copy_on_write): np.array([100.0, 200.0, 300.0]), inplace=True, ) - if using_copy_on_write: - tm.assert_almost_equal( - mgr.iget(mgr.items.get_loc("float")).internal_values(), - np.array([1.0, 1.0, 1.0]), - ) - else: - tm.assert_almost_equal( - mgr.iget(mgr.items.get_loc("float")).internal_values(), - np.array([100.0, 200.0, 300.0]), - ) + tm.assert_almost_equal( + mgr.iget(mgr.items.get_loc("float")).internal_values(), + np.array([1.0, 1.0, 1.0]), + ) - def test_get_bool_data(self, using_copy_on_write): + def test_get_bool_data(self): mgr = create_mgr( "int: int; float: float; complex: complex;" "str: object; bool: bool; obj: object; dt: datetime", @@ -801,16 +795,10 @@ def test_get_bool_data(self, using_copy_on_write): ) bools.iset(0, np.array([True, False, True]), inplace=True) - if using_copy_on_write: - tm.assert_numpy_array_equal( - mgr.iget(mgr.items.get_loc("bool")).internal_values(), - np.array([True, True, True]), - ) - else: - tm.assert_numpy_array_equal( - mgr.iget(mgr.items.get_loc("bool")).internal_values(), - np.array([True, False, True]), - ) + tm.assert_numpy_array_equal( + mgr.iget(mgr.items.get_loc("bool")).internal_values(), + np.array([True, True, True]), + ) def test_unicode_repr_doesnt_raise(self): repr(create_mgr("b,\u05d0: object")) diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py index 774f6b61df517..2f9e968dd1b71 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -438,7 +438,7 @@ def test_context_manageri_user_provided(all_parsers, datapath): @skip_pyarrow # ParserError: Empty CSV file -def test_file_descriptor_leak(all_parsers, using_copy_on_write): +def test_file_descriptor_leak(all_parsers): # GH 31488 parser = all_parsers with tm.ensure_clean() as path: diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 6f6252e3929fb..3cba7b7da347e 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -8,8 +8,6 @@ import numpy as np import pytest -from pandas._config import using_copy_on_write - from pandas.compat import is_platform_windows from pandas.compat.pyarrow import ( pa_version_under11p0, @@ -425,15 +423,10 @@ def test_read_filters(self, engine, tmp_path): repeat=1, ) - def test_write_index(self, engine, using_copy_on_write, request): - check_names = engine != "fastparquet" - if using_copy_on_write and engine == "fastparquet": - request.applymarker( - pytest.mark.xfail(reason="fastparquet write into index") - ) - + def test_write_index(self): + pytest.importorskip("pyarrow") df = pd.DataFrame({"A": [1, 2, 3]}) - check_round_trip(df, engine) + check_round_trip(df, "pyarrow") indexes = [ [2, 3, 4], @@ -446,12 +439,12 @@ def test_write_index(self, engine, using_copy_on_write, request): df.index = index if isinstance(index, pd.DatetimeIndex): df.index = df.index._with_freq(None) # freq doesn't round-trip - check_round_trip(df, engine, check_names=check_names) + check_round_trip(df, "pyarrow") # index with meta-data df.index = [0, 1, 2] df.index.name = "foo" - check_round_trip(df, engine) + check_round_trip(df, "pyarrow") def test_write_multiindex(self, pa): # Not supported in fastparquet as of 0.1.3 or older pyarrow version @@ -1256,23 +1249,6 @@ def test_error_on_using_partition_cols_and_partition_on( partition_cols=partition_cols, ) - @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index") - def test_empty_dataframe(self, fp): - # GH #27339 - df = pd.DataFrame() - expected = df.copy() - check_round_trip(df, fp, expected=expected) - - @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index") - def test_timezone_aware_index(self, fp, timezone_aware_date_list): - idx = 5 * [timezone_aware_date_list] - - df = pd.DataFrame(index=idx, data={"index_as_col": idx}) - - expected = df.copy() - expected.index.name = "index" - check_round_trip(df, fp, expected=expected) - def test_close_file_handle_on_read_error(self): with tm.ensure_clean("test.parquet") as path: pathlib.Path(path).write_bytes(b"breakit") @@ -1361,10 +1337,3 @@ def test_invalid_dtype_backend(self, engine): df.to_parquet(path) with pytest.raises(ValueError, match=msg): read_parquet(path, dtype_backend="numpy") - - @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index") - def test_empty_columns(self, fp): - # GH 52034 - df = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name")) - expected = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name")) - check_round_trip(df, fp, expected=expected) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index fda51b157cd75..4e2af9fef377b 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -36,26 +36,20 @@ def test_reindex(self, multiindex_dataframe_random_data): tm.assert_frame_equal(reindexed, expected) def test_reindex_preserve_levels( - self, multiindex_year_month_day_dataframe_random_data, using_copy_on_write + self, multiindex_year_month_day_dataframe_random_data ): ymd = multiindex_year_month_day_dataframe_random_data new_index = ymd.index[::10] chunk = ymd.reindex(new_index) - if using_copy_on_write: - assert chunk.index.is_(new_index) - else: - assert chunk.index is new_index + assert chunk.index.is_(new_index) chunk = ymd.loc[new_index] assert chunk.index.equals(new_index) ymdT = ymd.T chunk = ymdT.reindex(columns=new_index) - if using_copy_on_write: - assert chunk.columns.is_(new_index) - else: - assert chunk.columns is new_index + assert chunk.columns.is_(new_index) chunk = ymdT.loc[:, new_index] assert chunk.columns.equals(new_index)
This should be all of them
https://api.github.com/repos/pandas-dev/pandas/pulls/57477
2024-02-17T22:58:34Z
2024-02-19T17:21:50Z
2024-02-19T17:21:50Z
2024-02-19T20:30:57Z
TYP: simplify read_csv/fwf/table overloads
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 77c80dcfe7c7e..b57a258d626ee 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -90,6 +90,7 @@ Other API changes ^^^^^^^^^^^^^^^^^ - 3rd party ``py.path`` objects are no longer explicitly supported in IO methods. Use :py:class:`pathlib.Path` objects instead (:issue:`57091`) - :attr:`MultiIndex.codes`, :attr:`MultiIndex.levels`, and :attr:`MultiIndex.names` now returns a ``tuple`` instead of a ``FrozenList`` (:issue:`53531`) +- :func:`read_table`'s ``parse_dates`` argument defaults to ``None`` to improve consistency with :func:`read_csv` (:issue:`57476`) - Made ``dtype`` a required argument in :meth:`ExtensionArray._from_sequence_of_strings` (:issue:`56519`) - Updated :meth:`DataFrame.to_excel` so that the output spreadsheet has no styling. Custom styling can still be done using :meth:`Styler.to_excel` (:issue:`54154`) - pickle and HDF (``.h5``) files created with Python 2 are no longer explicitly supported (:issue:`57387`) diff --git a/pandas/_typing.py b/pandas/_typing.py index 85a69f38b3f67..0bcf5284315d2 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -107,8 +107,10 @@ if sys.version_info >= (3, 11): from typing import Self # pyright: ignore[reportUnusedImport] + from typing import Unpack # pyright: ignore[reportUnusedImport] else: from typing_extensions import Self # pyright: ignore[reportUnusedImport] + from typing_extensions import Unpack # pyright: ignore[reportUnusedImport] else: npt: Any = None @@ -116,6 +118,7 @@ Self: Any = None TypeGuard: Any = None Concatenate: Any = None + Unpack: Any = None HashableT = TypeVar("HashableT", bound=Hashable) HashableT2 = TypeVar("HashableT2", bound=Hashable) diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index 018f597526acd..2a42b4115d1a2 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -87,6 +87,7 @@ ReadCsvBuffer, Self, StorageOptions, + Unpack, UsecolsArgType, ) _doc_read_csv_and_table = ( @@ -242,12 +243,13 @@ .. deprecated:: 2.2.0 skip_blank_lines : bool, default True If ``True``, skip over blank lines rather than interpreting as ``NaN`` values. -parse_dates : bool, list of Hashable, list of lists or dict of {{Hashable : list}}, \ -default False +parse_dates : bool, None, list of Hashable, list of lists or dict of {{Hashable : \ +list}}, default None The behavior is as follows: - * ``bool``. If ``True`` -> try parsing the index. Note: Automatically set to - ``True`` if ``date_format`` or ``date_parser`` arguments have been passed. + * ``bool``. If ``True`` -> try parsing the index. + * ``None``. Behaves like ``True`` if ``date_parser`` or ``date_format`` are + specified. * ``list`` of ``int`` or names. e.g. If ``[1, 2, 3]`` -> try parsing columns 1, 2, 3 each as a separate date column. * ``list`` of ``list``. e.g. If ``[[1, 3]]`` -> combine columns 1 and 3 and parse @@ -478,6 +480,59 @@ class _Fwf_Defaults(TypedDict): widths: None +class _read_shared(TypedDict, total=False): + # annotations shared between read_csv/fwf/table's overloads + # NOTE: Keep in sync with the annotations of the implementation + sep: str | None | lib.NoDefault + delimiter: str | None | lib.NoDefault + header: int | Sequence[int] | None | Literal["infer"] + names: Sequence[Hashable] | None | lib.NoDefault + index_col: IndexLabel | Literal[False] | None + usecols: UsecolsArgType + dtype: DtypeArg | None + engine: CSVEngine | None + converters: Mapping[Hashable, Callable] | None + true_values: list | None + false_values: list | None + skipinitialspace: bool + skiprows: list[int] | int | Callable[[Hashable], bool] | None + skipfooter: int + nrows: int | None + na_values: Hashable | Iterable[Hashable] | Mapping[ + Hashable, Iterable[Hashable] + ] | None + keep_default_na: bool + na_filter: bool + verbose: bool | lib.NoDefault + skip_blank_lines: bool + parse_dates: bool | Sequence[Hashable] | None + infer_datetime_format: bool | lib.NoDefault + keep_date_col: bool | lib.NoDefault + date_parser: Callable | lib.NoDefault + date_format: str | dict[Hashable, str] | None + dayfirst: bool + cache_dates: bool + compression: CompressionOptions + thousands: str | None + decimal: str + lineterminator: str | None + quotechar: str + quoting: int + doublequote: bool + escapechar: str | None + comment: str | None + encoding: str | None + encoding_errors: str | None + dialect: str | csv.Dialect | None + on_bad_lines: str + delim_whitespace: bool | lib.NoDefault + low_memory: bool + memory_map: bool + float_precision: Literal["high", "legacy", "round_trip"] | None + storage_options: StorageOptions | None + dtype_backend: DtypeBackend | lib.NoDefault + + _fwf_defaults: _Fwf_Defaults = {"colspecs": "infer", "infer_nrows": 100, "widths": None} _c_unsupported = {"skipfooter"} _python_unsupported = {"low_memory", "float_precision"} @@ -624,241 +679,46 @@ def _read( return parser.read(nrows) -# iterator=True -> TextFileReader @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Hashable - | Iterable[Hashable] - | Mapping[Hashable, Iterable[Hashable]] - | None = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] | None = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: Literal[True], chunksize: int | None = ..., - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool | lib.NoDefault = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: Literal["high", "legacy", "round_trip"] | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> TextFileReader: ... -# chunksize=int -> TextFileReader @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Hashable - | Iterable[Hashable] - | Mapping[Hashable, Iterable[Hashable]] - | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] | None = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: bool = ..., chunksize: int, - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool | lib.NoDefault = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: Literal["high", "legacy", "round_trip"] | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> TextFileReader: ... -# default case -> DataFrame @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Hashable - | Iterable[Hashable] - | Mapping[Hashable, Iterable[Hashable]] - | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] | None = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: Literal[False] = ..., chunksize: None = ..., - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool | lib.NoDefault = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: Literal["high", "legacy", "round_trip"] | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> DataFrame: ... -# Unions -> DataFrame | TextFileReader @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Hashable - | Iterable[Hashable] - | Mapping[Hashable, Iterable[Hashable]] - | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] | None = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: bool = ..., chunksize: int | None = ..., - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool | lib.NoDefault = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: Literal["high", "legacy", "round_trip"] | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> DataFrame | TextFileReader: ... @@ -1024,230 +884,46 @@ def read_csv( return _read(filepath_or_buffer, kwds) -# iterator=True -> TextFileReader @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: Literal[True], chunksize: int | None = ..., - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: str | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> TextFileReader: ... -# chunksize=int -> TextFileReader @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: bool = ..., chunksize: int, - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: str | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> TextFileReader: ... -# default -> DataFrame @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: Literal[False] = ..., chunksize: None = ..., - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: str | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> DataFrame: ... -# Unions -> DataFrame | TextFileReader @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, - sep: str | None | lib.NoDefault = ..., - delimiter: str | None | lib.NoDefault = ..., - header: int | Sequence[int] | None | Literal["infer"] = ..., - names: Sequence[Hashable] | None | lib.NoDefault = ..., - index_col: IndexLabel | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., - dtype: DtypeArg | None = ..., - engine: CSVEngine | None = ..., - converters: Mapping[Hashable, Callable] | None = ..., - true_values: list | None = ..., - false_values: list | None = ..., - skipinitialspace: bool = ..., - skiprows: list[int] | int | Callable[[Hashable], bool] | None = ..., - skipfooter: int = ..., - nrows: int | None = ..., - na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = ..., - keep_default_na: bool = ..., - na_filter: bool = ..., - verbose: bool | lib.NoDefault = ..., - skip_blank_lines: bool = ..., - parse_dates: bool | Sequence[Hashable] = ..., - infer_datetime_format: bool | lib.NoDefault = ..., - keep_date_col: bool | lib.NoDefault = ..., - date_parser: Callable | lib.NoDefault = ..., - date_format: str | dict[Hashable, str] | None = ..., - dayfirst: bool = ..., - cache_dates: bool = ..., iterator: bool = ..., chunksize: int | None = ..., - compression: CompressionOptions = ..., - thousands: str | None = ..., - decimal: str = ..., - lineterminator: str | None = ..., - quotechar: str = ..., - quoting: int = ..., - doublequote: bool = ..., - escapechar: str | None = ..., - comment: str | None = ..., - encoding: str | None = ..., - encoding_errors: str | None = ..., - dialect: str | csv.Dialect | None = ..., - on_bad_lines=..., - delim_whitespace: bool = ..., - low_memory: bool = ..., - memory_map: bool = ..., - float_precision: str | None = ..., - storage_options: StorageOptions = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., + **kwds: Unpack[_read_shared], ) -> DataFrame | TextFileReader: ... @@ -1287,13 +963,16 @@ def read_table( skipfooter: int = 0, nrows: int | None = None, # NA and Missing Data Handling - na_values: Sequence[str] | Mapping[str, Sequence[str]] | None = None, + na_values: Hashable + | Iterable[Hashable] + | Mapping[Hashable, Iterable[Hashable]] + | None = None, keep_default_na: bool = True, na_filter: bool = True, verbose: bool | lib.NoDefault = lib.no_default, skip_blank_lines: bool = True, # Datetime Handling - parse_dates: bool | Sequence[Hashable] = False, + parse_dates: bool | Sequence[Hashable] | None = None, infer_datetime_format: bool | lib.NoDefault = lib.no_default, keep_date_col: bool | lib.NoDefault = lib.no_default, date_parser: Callable | lib.NoDefault = lib.no_default, @@ -1322,7 +1001,7 @@ def read_table( delim_whitespace: bool | lib.NoDefault = lib.no_default, low_memory: bool = _c_parser_defaults["low_memory"], memory_map: bool = False, - float_precision: str | None = None, + float_precision: Literal["high", "legacy", "round_trip"] | None = None, storage_options: StorageOptions | None = None, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, ) -> DataFrame | TextFileReader: @@ -1410,10 +1089,9 @@ def read_fwf( colspecs: Sequence[tuple[int, int]] | str | None = ..., widths: Sequence[int] | None = ..., infer_nrows: int = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., iterator: Literal[True], chunksize: int | None = ..., - **kwds, + **kwds: Unpack[_read_shared], ) -> TextFileReader: ... @@ -1425,10 +1103,9 @@ def read_fwf( colspecs: Sequence[tuple[int, int]] | str | None = ..., widths: Sequence[int] | None = ..., infer_nrows: int = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., iterator: bool = ..., chunksize: int, - **kwds, + **kwds: Unpack[_read_shared], ) -> TextFileReader: ... @@ -1440,10 +1117,9 @@ def read_fwf( colspecs: Sequence[tuple[int, int]] | str | None = ..., widths: Sequence[int] | None = ..., infer_nrows: int = ..., - dtype_backend: DtypeBackend | lib.NoDefault = ..., iterator: Literal[False] = ..., chunksize: None = ..., - **kwds, + **kwds: Unpack[_read_shared], ) -> DataFrame: ... @@ -1454,10 +1130,9 @@ def read_fwf( colspecs: Sequence[tuple[int, int]] | str | None = "infer", widths: Sequence[int] | None = None, infer_nrows: int = 100, - dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, iterator: bool = False, chunksize: int | None = None, - **kwds, + **kwds: Unpack[_read_shared], ) -> DataFrame | TextFileReader: r""" Read a table of fixed-width formatted lines into DataFrame. @@ -1488,17 +1163,6 @@ def read_fwf( infer_nrows : int, default 100 The number of rows to consider when letting the parser determine the `colspecs`. - dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable' - Back-end data type applied to the resultant :class:`DataFrame` - (still experimental). Behaviour is as follows: - - * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` - (default). - * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` - DataFrame. - - .. versionadded:: 2.0 - **kwds : optional Optional keyword arguments can be passed to ``TextFileReader``. @@ -1536,7 +1200,7 @@ def read_fwf( # GH#40830 # Ensure length of `colspecs` matches length of `names` names = kwds.get("names") - if names is not None: + if names is not None and names is not lib.no_default: if len(names) != len(colspecs) and colspecs != "infer": # need to check len(index_col) as it might contain # unnamed indices, in which case it's name is not required @@ -1547,20 +1211,26 @@ def read_fwf( if not is_list_like(index_col): len_index = 1 else: + # for mypy: handled in the if-branch + assert index_col is not lib.no_default + len_index = len(index_col) if kwds.get("usecols") is None and len(names) + len_index != len(colspecs): # If usecols is used colspec may be longer than names raise ValueError("Length of colspecs must match length of names") - kwds["colspecs"] = colspecs - kwds["infer_nrows"] = infer_nrows - kwds["engine"] = "python-fwf" - kwds["iterator"] = iterator - kwds["chunksize"] = chunksize - - check_dtype_backend(dtype_backend) - kwds["dtype_backend"] = dtype_backend - return _read(filepath_or_buffer, kwds) + check_dtype_backend(kwds.setdefault("dtype_backend", lib.no_default)) + return _read( + filepath_or_buffer, + kwds + | { + "colspecs": colspecs, + "infer_nrows": infer_nrows, + "engine": "python-fwf", + "iterator": iterator, + "chunksize": chunksize, + }, + ) class TextFileReader(abc.Iterator):
null
https://api.github.com/repos/pandas-dev/pandas/pulls/57476
2024-02-17T22:06:03Z
2024-02-21T18:05:33Z
2024-02-21T18:05:33Z
2024-04-07T10:59:17Z
REGR: DataFrame.transpose resulting in not contiguous data on nullable EAs
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index ca4fef4f57fb6..54b0d5f93dfa3 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -32,6 +32,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) - Fixed regression in :meth:`DataFrame.to_json` converting nullable integers to floats (:issue:`57224`) - Fixed regression in :meth:`DataFrame.to_sql` when ``method="multi"`` is passed and the dialect type is not Oracle (:issue:`57310`) +- Fixed regression in :meth:`DataFrame.transpose` with nullable extension dtypes not having F-contiguous data potentially causing exceptions when used (:issue:`57315`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) - Fixed regression in :meth:`ExtensionArray.to_numpy` raising for non-numeric masked dtypes (:issue:`56991`) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index c1ed3dacb9a95..c336706da45d6 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -1651,13 +1651,24 @@ def transpose_homogeneous_masked_arrays( same dtype. The caller is responsible for ensuring validity of input data. """ masked_arrays = list(masked_arrays) + dtype = masked_arrays[0].dtype + values = [arr._data.reshape(1, -1) for arr in masked_arrays] - transposed_values = np.concatenate(values, axis=0) + transposed_values = np.concatenate( + values, + axis=0, + out=np.empty( + (len(masked_arrays), len(masked_arrays[0])), + order="F", + dtype=dtype.numpy_dtype, + ), + ) masks = [arr._mask.reshape(1, -1) for arr in masked_arrays] - transposed_masks = np.concatenate(masks, axis=0) + transposed_masks = np.concatenate( + masks, axis=0, out=np.empty_like(transposed_values, dtype=bool) + ) - dtype = masked_arrays[0].dtype arr_type = dtype.construct_array_type() transposed_arrays: list[BaseMaskedArray] = [] for i in range(transposed_values.shape[1]): diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index 495663ce135f9..f42fd4483e9ac 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -1,6 +1,7 @@ import numpy as np import pytest +import pandas as pd from pandas import ( DataFrame, DatetimeIndex, @@ -179,3 +180,19 @@ def test_transpose_not_inferring_dt_mixed_blocks(self): dtype=object, ) tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype1", ["Int64", "Float64"]) + @pytest.mark.parametrize("dtype2", ["Int64", "Float64"]) + def test_transpose(self, dtype1, dtype2): + # GH#57315 - transpose should have F contiguous blocks + df = DataFrame( + { + "a": pd.array([1, 1, 2], dtype=dtype1), + "b": pd.array([3, 4, 5], dtype=dtype2), + } + ) + result = df.T + for blk in result._mgr.blocks: + # When dtypes are unequal, we get NumPy object array + data = blk.values._data if dtype1 == dtype2 else blk.values + assert data.flags["F_CONTIGUOUS"]
- [x] closes #57315 (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/57474
2024-02-17T20:49:51Z
2024-02-18T15:15:09Z
2024-02-18T15:15:09Z
2024-02-23T03:35:35Z
DEPR: remove deprecated method `is_anchored`
diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst index ab89fe74e7337..b5ddf2a214561 100644 --- a/doc/source/reference/offset_frequency.rst +++ b/doc/source/reference/offset_frequency.rst @@ -35,7 +35,6 @@ Methods :toctree: api/ DateOffset.copy - DateOffset.is_anchored DateOffset.is_on_offset DateOffset.is_month_start DateOffset.is_month_end @@ -82,7 +81,6 @@ Methods :toctree: api/ BusinessDay.copy - BusinessDay.is_anchored BusinessDay.is_on_offset BusinessDay.is_month_start BusinessDay.is_month_end @@ -122,7 +120,6 @@ Methods :toctree: api/ BusinessHour.copy - BusinessHour.is_anchored BusinessHour.is_on_offset BusinessHour.is_month_start BusinessHour.is_month_end @@ -169,7 +166,6 @@ Methods :toctree: api/ CustomBusinessDay.copy - CustomBusinessDay.is_anchored CustomBusinessDay.is_on_offset CustomBusinessDay.is_month_start CustomBusinessDay.is_month_end @@ -209,7 +205,6 @@ Methods :toctree: api/ CustomBusinessHour.copy - CustomBusinessHour.is_anchored CustomBusinessHour.is_on_offset CustomBusinessHour.is_month_start CustomBusinessHour.is_month_end @@ -244,7 +239,6 @@ Methods :toctree: api/ MonthEnd.copy - MonthEnd.is_anchored MonthEnd.is_on_offset MonthEnd.is_month_start MonthEnd.is_month_end @@ -279,7 +273,6 @@ Methods :toctree: api/ MonthBegin.copy - MonthBegin.is_anchored MonthBegin.is_on_offset MonthBegin.is_month_start MonthBegin.is_month_end @@ -323,7 +316,6 @@ Methods :toctree: api/ BusinessMonthEnd.copy - BusinessMonthEnd.is_anchored BusinessMonthEnd.is_on_offset BusinessMonthEnd.is_month_start BusinessMonthEnd.is_month_end @@ -367,7 +359,6 @@ Methods :toctree: api/ BusinessMonthBegin.copy - BusinessMonthBegin.is_anchored BusinessMonthBegin.is_on_offset BusinessMonthBegin.is_month_start BusinessMonthBegin.is_month_end @@ -415,7 +406,6 @@ Methods :toctree: api/ CustomBusinessMonthEnd.copy - CustomBusinessMonthEnd.is_anchored CustomBusinessMonthEnd.is_on_offset CustomBusinessMonthEnd.is_month_start CustomBusinessMonthEnd.is_month_end @@ -463,7 +453,6 @@ Methods :toctree: api/ CustomBusinessMonthBegin.copy - CustomBusinessMonthBegin.is_anchored CustomBusinessMonthBegin.is_on_offset CustomBusinessMonthBegin.is_month_start CustomBusinessMonthBegin.is_month_end @@ -499,7 +488,6 @@ Methods :toctree: api/ SemiMonthEnd.copy - SemiMonthEnd.is_anchored SemiMonthEnd.is_on_offset SemiMonthEnd.is_month_start SemiMonthEnd.is_month_end @@ -535,7 +523,6 @@ Methods :toctree: api/ SemiMonthBegin.copy - SemiMonthBegin.is_anchored SemiMonthBegin.is_on_offset SemiMonthBegin.is_month_start SemiMonthBegin.is_month_end @@ -571,7 +558,6 @@ Methods :toctree: api/ Week.copy - Week.is_anchored Week.is_on_offset Week.is_month_start Week.is_month_end @@ -607,7 +593,6 @@ Methods :toctree: api/ WeekOfMonth.copy - WeekOfMonth.is_anchored WeekOfMonth.is_on_offset WeekOfMonth.weekday WeekOfMonth.is_month_start @@ -645,7 +630,6 @@ Methods :toctree: api/ LastWeekOfMonth.copy - LastWeekOfMonth.is_anchored LastWeekOfMonth.is_on_offset LastWeekOfMonth.is_month_start LastWeekOfMonth.is_month_end @@ -681,7 +665,6 @@ Methods :toctree: api/ BQuarterEnd.copy - BQuarterEnd.is_anchored BQuarterEnd.is_on_offset BQuarterEnd.is_month_start BQuarterEnd.is_month_end @@ -717,7 +700,6 @@ Methods :toctree: api/ BQuarterBegin.copy - BQuarterBegin.is_anchored BQuarterBegin.is_on_offset BQuarterBegin.is_month_start BQuarterBegin.is_month_end @@ -753,7 +735,6 @@ Methods :toctree: api/ QuarterEnd.copy - QuarterEnd.is_anchored QuarterEnd.is_on_offset QuarterEnd.is_month_start QuarterEnd.is_month_end @@ -789,7 +770,6 @@ Methods :toctree: api/ QuarterBegin.copy - QuarterBegin.is_anchored QuarterBegin.is_on_offset QuarterBegin.is_month_start QuarterBegin.is_month_end @@ -825,7 +805,6 @@ Methods :toctree: api/ BYearEnd.copy - BYearEnd.is_anchored BYearEnd.is_on_offset BYearEnd.is_month_start BYearEnd.is_month_end @@ -861,7 +840,6 @@ Methods :toctree: api/ BYearBegin.copy - BYearBegin.is_anchored BYearBegin.is_on_offset BYearBegin.is_month_start BYearBegin.is_month_end @@ -897,7 +875,6 @@ Methods :toctree: api/ YearEnd.copy - YearEnd.is_anchored YearEnd.is_on_offset YearEnd.is_month_start YearEnd.is_month_end @@ -933,7 +910,6 @@ Methods :toctree: api/ YearBegin.copy - YearBegin.is_anchored YearBegin.is_on_offset YearBegin.is_month_start YearBegin.is_month_end @@ -973,7 +949,6 @@ Methods FY5253.copy FY5253.get_rule_code_suffix FY5253.get_year_end - FY5253.is_anchored FY5253.is_on_offset FY5253.is_month_start FY5253.is_month_end @@ -1014,7 +989,6 @@ Methods FY5253Quarter.copy FY5253Quarter.get_rule_code_suffix FY5253Quarter.get_weeks - FY5253Quarter.is_anchored FY5253Quarter.is_on_offset FY5253Quarter.year_has_extra_week FY5253Quarter.is_month_start @@ -1050,7 +1024,6 @@ Methods :toctree: api/ Easter.copy - Easter.is_anchored Easter.is_on_offset Easter.is_month_start Easter.is_month_end @@ -1086,7 +1059,6 @@ Methods :toctree: api/ Tick.copy - Tick.is_anchored Tick.is_on_offset Tick.is_month_start Tick.is_month_end @@ -1122,7 +1094,6 @@ Methods :toctree: api/ Day.copy - Day.is_anchored Day.is_on_offset Day.is_month_start Day.is_month_end @@ -1158,7 +1129,6 @@ Methods :toctree: api/ Hour.copy - Hour.is_anchored Hour.is_on_offset Hour.is_month_start Hour.is_month_end @@ -1194,7 +1164,6 @@ Methods :toctree: api/ Minute.copy - Minute.is_anchored Minute.is_on_offset Minute.is_month_start Minute.is_month_end @@ -1230,7 +1199,6 @@ Methods :toctree: api/ Second.copy - Second.is_anchored Second.is_on_offset Second.is_month_start Second.is_month_end @@ -1266,7 +1234,6 @@ Methods :toctree: api/ Milli.copy - Milli.is_anchored Milli.is_on_offset Milli.is_month_start Milli.is_month_end @@ -1302,7 +1269,6 @@ Methods :toctree: api/ Micro.copy - Micro.is_anchored Micro.is_on_offset Micro.is_month_start Micro.is_month_end @@ -1338,7 +1304,6 @@ Methods :toctree: api/ Nano.copy - Nano.is_anchored Nano.is_on_offset Nano.is_month_start Nano.is_month_end diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 77c80dcfe7c7e..38d9523a5083a 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -118,6 +118,7 @@ Removal of prior version deprecations/changes - Changed the default value of ``observed`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` to ``True`` (:issue:`51811`) - Enforced silent-downcasting deprecation for :ref:`all relevant methods <whatsnew_220.silent_downcasting>` (:issue:`54710`) - In :meth:`DataFrame.stack`, the default value of ``future_stack`` is now ``True``; specifying ``False`` will raise a ``FutureWarning`` (:issue:`55448`) +- Removed :meth:`DateOffset.is_anchored` and :meth:`offsets.Tick.is_anchored` (:issue:`56594`) - Removed ``DataFrame.applymap``, ``Styler.applymap`` and ``Styler.applymap_index`` (:issue:`52364`) - Removed ``DataFrame.bool`` and ``Series.bool`` (:issue:`51756`) - Removed ``DataFrame.first`` and ``DataFrame.last`` (:issue:`53710`) diff --git a/pandas/_libs/tslibs/offsets.pyi b/pandas/_libs/tslibs/offsets.pyi index 434f10a00745f..8f1e34522c026 100644 --- a/pandas/_libs/tslibs/offsets.pyi +++ b/pandas/_libs/tslibs/offsets.pyi @@ -94,7 +94,6 @@ class BaseOffset: def __getstate__(self): ... @property def nanos(self) -> int: ... - def is_anchored(self) -> bool: ... def _get_offset(name: str) -> BaseOffset: ... diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index e96a905367f69..1afdb4f8b96fc 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -755,30 +755,6 @@ cdef class BaseOffset: def nanos(self): raise ValueError(f"{self} is a non-fixed frequency") - def is_anchored(self) -> bool: - # GH#55388 - """ - Return boolean whether the frequency is a unit frequency (n=1). - - .. deprecated:: 2.2.0 - is_anchored is deprecated and will be removed in a future version. - Use ``obj.n == 1`` instead. - - Examples - -------- - >>> pd.DateOffset().is_anchored() - True - >>> pd.DateOffset(2).is_anchored() - False - """ - warnings.warn( - f"{type(self).__name__}.is_anchored is deprecated and will be removed " - f"in a future version, please use \'obj.n == 1\' instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return self.n == 1 - # ------------------------------------------------------------------ def is_month_start(self, _Timestamp ts): @@ -962,30 +938,6 @@ cdef class Tick(SingleConstructorOffset): def is_on_offset(self, dt: datetime) -> bool: return True - def is_anchored(self) -> bool: - # GH#55388 - """ - Return False. - - .. deprecated:: 2.2.0 - is_anchored is deprecated and will be removed in a future version. - Use ``False`` instead. - - Examples - -------- - >>> pd.offsets.Hour().is_anchored() - False - >>> pd.offsets.Hour(2).is_anchored() - False - """ - warnings.warn( - f"{type(self).__name__}.is_anchored is deprecated and will be removed " - f"in a future version, please use False instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return False - # This is identical to BaseOffset.__hash__, but has to be redefined here # for Python 3, because we've redefined __eq__. def __hash__(self) -> int: @@ -2692,16 +2644,6 @@ cdef class QuarterOffset(SingleConstructorOffset): month = MONTH_ALIASES[self.startingMonth] return f"{self._prefix}-{month}" - def is_anchored(self) -> bool: - warnings.warn( - f"{type(self).__name__}.is_anchored is deprecated and will be removed " - f"in a future version, please use \'obj.n == 1 " - f"and obj.startingMonth is not None\' instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return self.n == 1 and self.startingMonth is not None - def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False @@ -3344,16 +3286,6 @@ cdef class Week(SingleConstructorOffset): self.weekday = state.pop("weekday") self._cache = state.pop("_cache", {}) - def is_anchored(self) -> bool: - warnings.warn( - f"{type(self).__name__}.is_anchored is deprecated and will be removed " - f"in a future version, please use \'obj.n == 1 " - f"and obj.weekday is not None\' instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return self.n == 1 and self.weekday is not None - @apply_wraps def _apply(self, other): if self.weekday is None: @@ -3640,17 +3572,6 @@ cdef class FY5253Mixin(SingleConstructorOffset): self.weekday = state.pop("weekday") self.variation = state.pop("variation") - def is_anchored(self) -> bool: - warnings.warn( - f"{type(self).__name__}.is_anchored is deprecated and will be removed " - f"in a future version, please use \'obj.n == 1\' instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return ( - self.n == 1 and self.startingMonth is not None and self.weekday is not None - ) - # -------------------------------------------------------------------- # Name-related methods diff --git a/pandas/tests/tseries/offsets/test_business_quarter.py b/pandas/tests/tseries/offsets/test_business_quarter.py index 6d7a115054b7f..3e87ab3e6d397 100644 --- a/pandas/tests/tseries/offsets/test_business_quarter.py +++ b/pandas/tests/tseries/offsets/test_business_quarter.py @@ -9,7 +9,6 @@ import pytest -import pandas._testing as tm from pandas.tests.tseries.offsets.common import ( assert_is_on_offset, assert_offset_equal, @@ -54,14 +53,6 @@ def test_repr(self): expected = "<BusinessQuarterBegin: startingMonth=1>" assert repr(BQuarterBegin(startingMonth=1)) == expected - def test_is_anchored(self): - msg = "BQuarterBegin.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert BQuarterBegin(startingMonth=1).is_anchored() - assert BQuarterBegin().is_anchored() - assert not BQuarterBegin(2, startingMonth=1).is_anchored() - def test_offset_corner_case(self): # corner offset = BQuarterBegin(n=-1, startingMonth=1) @@ -180,14 +171,6 @@ def test_repr(self): expected = "<BusinessQuarterEnd: startingMonth=1>" assert repr(BQuarterEnd(startingMonth=1)) == expected - def test_is_anchored(self): - msg = "BQuarterEnd.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert BQuarterEnd(startingMonth=1).is_anchored() - assert BQuarterEnd().is_anchored() - assert not BQuarterEnd(2, startingMonth=1).is_anchored() - def test_offset_corner_case(self): # corner offset = BQuarterEnd(n=-1, startingMonth=1) diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py index 824e66a1ddef1..208f8f550086a 100644 --- a/pandas/tests/tseries/offsets/test_fiscal.py +++ b/pandas/tests/tseries/offsets/test_fiscal.py @@ -7,7 +7,6 @@ import pytest from pandas import Timestamp -import pandas._testing as tm from pandas.tests.tseries.offsets.common import ( WeekDay, assert_is_on_offset, @@ -295,20 +294,6 @@ def test_apply(self): class TestFY5253LastOfMonthQuarter: - def test_is_anchored(self): - msg = "FY5253Quarter.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert makeFY5253LastOfMonthQuarter( - startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4 - ).is_anchored() - assert makeFY5253LastOfMonthQuarter( - weekday=WeekDay.SAT, startingMonth=3, qtr_with_extra_week=4 - ).is_anchored() - assert not makeFY5253LastOfMonthQuarter( - 2, startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4 - ).is_anchored() - def test_equality(self): assert makeFY5253LastOfMonthQuarter( startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4 diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 72eff4b6ee479..cab9df710ed99 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -624,13 +624,6 @@ def test_constructor(self, kwd, request): def test_default_constructor(self, dt): assert (dt + DateOffset(2)) == datetime(2008, 1, 4) - def test_is_anchored(self): - msg = "DateOffset.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert not DateOffset(2).is_anchored() - assert DateOffset(1).is_anchored() - def test_copy(self): assert DateOffset(months=2).copy() == DateOffset(months=2) assert DateOffset(milliseconds=1).copy() == DateOffset(milliseconds=1) diff --git a/pandas/tests/tseries/offsets/test_quarter.py b/pandas/tests/tseries/offsets/test_quarter.py index 5fd3ba0a5fb87..d3872b7ce9537 100644 --- a/pandas/tests/tseries/offsets/test_quarter.py +++ b/pandas/tests/tseries/offsets/test_quarter.py @@ -9,7 +9,6 @@ import pytest -import pandas._testing as tm from pandas.tests.tseries.offsets.common import ( assert_is_on_offset, assert_offset_equal, @@ -53,14 +52,6 @@ def test_repr(self): expected = "<QuarterBegin: startingMonth=1>" assert repr(QuarterBegin(startingMonth=1)) == expected - def test_is_anchored(self): - msg = "QuarterBegin.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert QuarterBegin(startingMonth=1).is_anchored() - assert QuarterBegin().is_anchored() - assert not QuarterBegin(2, startingMonth=1).is_anchored() - def test_offset_corner_case(self): # corner offset = QuarterBegin(n=-1, startingMonth=1) @@ -164,14 +155,6 @@ def test_repr(self): expected = "<QuarterEnd: startingMonth=1>" assert repr(QuarterEnd(startingMonth=1)) == expected - def test_is_anchored(self): - msg = "QuarterEnd.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert QuarterEnd(startingMonth=1).is_anchored() - assert QuarterEnd().is_anchored() - assert not QuarterEnd(2, startingMonth=1).is_anchored() - def test_offset_corner_case(self): # corner offset = QuarterEnd(n=-1, startingMonth=1) diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py index 399b7038d3426..07e434e883c04 100644 --- a/pandas/tests/tseries/offsets/test_ticks.py +++ b/pandas/tests/tseries/offsets/test_ticks.py @@ -337,14 +337,6 @@ def test_tick_equalities(cls): assert cls() == cls(1) -@pytest.mark.parametrize("cls", tick_classes) -def test_tick_offset(cls): - msg = f"{cls.__name__}.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert not cls().is_anchored() - - @pytest.mark.parametrize("cls", tick_classes) def test_compare_ticks(cls): three = cls(3) diff --git a/pandas/tests/tseries/offsets/test_week.py b/pandas/tests/tseries/offsets/test_week.py index 0cd6f769769ae..f9a8755dc6336 100644 --- a/pandas/tests/tseries/offsets/test_week.py +++ b/pandas/tests/tseries/offsets/test_week.py @@ -21,7 +21,6 @@ WeekOfMonth, ) -import pandas._testing as tm from pandas.tests.tseries.offsets.common import ( WeekDay, assert_is_on_offset, @@ -42,15 +41,6 @@ def test_corner(self): with pytest.raises(ValueError, match="Day must be"): Week(weekday=-1) - def test_is_anchored(self): - msg = "Week.is_anchored is deprecated " - - with tm.assert_produces_warning(FutureWarning, match=msg): - assert Week(weekday=0).is_anchored() - assert not Week().is_anchored() - assert not Week(2, weekday=2).is_anchored() - assert not Week(2).is_anchored() - offset_cases = [] # not business week offset_cases.append(
xref #56594 removed deprecated methods `DateOffset.is_anchored` and `offsets.Tick.is_anchored`
https://api.github.com/repos/pandas-dev/pandas/pulls/57473
2024-02-17T18:46:12Z
2024-02-19T20:48:28Z
2024-02-19T20:48:28Z
2024-02-19T21:06:02Z
BUG: guess_datetime_format fails to infer timeformat
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index a77e93c4ab4be..edcf83953a14e 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -287,6 +287,7 @@ Styler Other ^^^^^ +- Bug in :func:`tseries.api.guess_datetime_format` would fail to infer time format when "%Y" == "%H%M" (:issue:`57452`) - Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` and ``ascending=False`` not returning a :class:`RangeIndex` columns (:issue:`57293`) - Bug in :meth:`DataFrame.where` where using a non-bool type array in the function would return a ``ValueError`` instead of a ``TypeError`` (:issue:`56330`) diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 1e544a9927086..ad723df485ba6 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -915,8 +915,8 @@ def guess_datetime_format(dt_str: str, bint dayfirst=False) -> str | None: (("year", "month", "day", "hour"), "%Y%m%d%H", 0), (("year", "month", "day"), "%Y%m%d", 0), (("hour", "minute", "second"), "%H%M%S", 0), - (("hour", "minute"), "%H%M", 0), (("year",), "%Y", 0), + (("hour", "minute"), "%H%M", 0), (("month",), "%B", 0), (("month",), "%b", 0), (("month",), "%m", 2), diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py index d8f23156bd4d4..4dd9d7b20be69 100644 --- a/pandas/tests/tslibs/test_parsing.py +++ b/pandas/tests/tslibs/test_parsing.py @@ -218,6 +218,7 @@ def test_parsers_month_freq(date_str, expected): ("Tue 24 Aug 2021 01:30:48 AM", "%a %d %b %Y %I:%M:%S %p"), ("Tuesday 24 Aug 2021 01:30:48 AM", "%A %d %b %Y %I:%M:%S %p"), ("27.03.2003 14:55:00.000", "%d.%m.%Y %H:%M:%S.%f"), # GH50317 + ("2023-11-09T20:23:46Z", "%Y-%m-%dT%H:%M:%S%z"), # GH57452 ], ) def test_guess_datetime_format_with_parseable_formats(string, fmt):
- [x] closes #57452(Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/57471
2024-02-17T13:52:50Z
2024-02-21T19:14:10Z
2024-02-21T19:14:10Z
2024-02-22T04:06:48Z
PERF: RangeIndex.append returns a RangeIndex when possible
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 7802ef4798659..157b87c93e729 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -245,6 +245,7 @@ Removal of prior version deprecations/changes Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ +- :meth:`RangeIndex.append` returns a :class:`RangeIndex` instead of a :class:`Index` when appending values that could continue the :class:`RangeIndex` (:issue:`57467`) - :meth:`Series.str.extract` returns a :class:`RangeIndex` columns instead of an :class:`Index` column when possible (:issue:`57542`) - Performance improvement in :class:`DataFrame` when ``data`` is a ``dict`` and ``columns`` is specified (:issue:`24368`) - Performance improvement in :meth:`DataFrame.join` for sorted but non-unique indexes (:issue:`56941`) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 09d635b53c482..0781a86e5d57e 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -989,7 +989,10 @@ def _concat(self, indexes: list[Index], name: Hashable) -> Index: indexes = [RangeIndex(3), RangeIndex(4, 6)] -> Index([0,1,2,4,5], dtype='int64') """ if not all(isinstance(x, RangeIndex) for x in indexes): - return super()._concat(indexes, name) + result = super()._concat(indexes, name) + if result.dtype.kind == "i": + return self._shallow_copy(result._values) + return result elif len(indexes) == 1: return indexes[0] diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 898548d1cc4dc..8c24ce5d699d5 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -608,6 +608,20 @@ def test_range_index_rsub_by_const(self): tm.assert_index_equal(result, expected) +def test_append_non_rangeindex_return_rangeindex(): + ri = RangeIndex(1) + result = ri.append(Index([1])) + expected = RangeIndex(2) + tm.assert_index_equal(result, expected, exact=True) + + +def test_append_non_rangeindex_return_index(): + ri = RangeIndex(1) + result = ri.append(Index([1, 3, 4])) + expected = Index([0, 1, 3, 4]) + tm.assert_index_equal(result, expected, exact=True) + + def test_reindex_returns_rangeindex(): ri = RangeIndex(2, name="foo") result, result_indexer = ri.reindex([1, 2, 3])
Discovered in https://github.com/pandas-dev/pandas/pull/57441
https://api.github.com/repos/pandas-dev/pandas/pulls/57467
2024-02-17T01:16:24Z
2024-03-06T21:15:52Z
2024-03-06T21:15:52Z
2024-03-06T21:15:55Z
Backport PR #57311 on branch 2.2.x (Fixing multi method for to_sql for non-oracle databases)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 5e814ec2a1b92..ca4fef4f57fb6 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -31,6 +31,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.sort_index` not producing a stable sort for a index with duplicates (:issue:`57151`) - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) - Fixed regression in :meth:`DataFrame.to_json` converting nullable integers to floats (:issue:`57224`) +- Fixed regression in :meth:`DataFrame.to_sql` when ``method="multi"`` is passed and the dialect type is not Oracle (:issue:`57310`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`DataFrameGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) - Fixed regression in :meth:`ExtensionArray.to_numpy` raising for non-numeric masked dtypes (:issue:`56991`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 55693d4cdb753..62dd0c3bf0161 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2969,6 +2969,9 @@ def to_sql( database. Otherwise, the datetimes will be stored as timezone unaware timestamps local to the original timezone. + Not all datastores support ``method="multi"``. Oracle, for example, + does not support multi-value insert. + References ---------- .. [1] https://docs.sqlalchemy.org diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 3a58daf681cfb..195a7c5040853 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1012,22 +1012,19 @@ def _execute_insert(self, conn, keys: list[str], data_iter) -> int: def _execute_insert_multi(self, conn, keys: list[str], data_iter) -> int: """ - Alternative to _execute_insert for DBs support multivalue INSERT. + Alternative to _execute_insert for DBs support multi-value INSERT. Note: multi-value insert is usually faster for analytics DBs and tables containing a few columns but performance degrades quickly with increase of columns. + """ from sqlalchemy import insert data = [dict(zip(keys, row)) for row in data_iter] - stmt = insert(self.table) - # conn.execute is used here to ensure compatibility with Oracle. - # Using stmt.values(data) would produce a multi row insert that - # isn't supported by Oracle. - # see: https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.Insert.values - result = conn.execute(stmt, data) + stmt = insert(self.table).values(data) + result = conn.execute(stmt) return result.rowcount def insert_data(self) -> tuple[list[str], list[np.ndarray]]:
Backport PR #57311: Fixing multi method for to_sql for non-oracle databases
https://api.github.com/repos/pandas-dev/pandas/pulls/57466
2024-02-17T01:10:25Z
2024-02-17T22:33:12Z
2024-02-17T22:33:12Z
2024-02-17T22:33:12Z
DOC: Making pandas always lowercase
diff --git a/doc/source/conf.py b/doc/source/conf.py index c4b1a584836f5..77dd5d03d311c 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -431,7 +431,7 @@ "index", "pandas.tex", "pandas: powerful Python data analysis toolkit", - "Wes McKinney and the Pandas Development Team", + "Wes McKinney and the pandas Development Team", "manual", ) ] diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 7e0b9c3200d3b..62559c4232b51 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -253,7 +253,7 @@ Testing type hints in code using pandas .. warning:: - * Pandas is not yet a py.typed library (:pep:`561`)! + * pandas is not yet a py.typed library (:pep:`561`)! The primary purpose of locally declaring pandas as a py.typed library is to test and improve the pandas-builtin type annotations. diff --git a/doc/source/development/contributing_documentation.rst b/doc/source/development/contributing_documentation.rst index 964f82be4fa7b..443470e6c50f9 100644 --- a/doc/source/development/contributing_documentation.rst +++ b/doc/source/development/contributing_documentation.rst @@ -14,7 +14,7 @@ experts. If something in the docs doesn't make sense to you, updating the relevant section after you figure it out is a great way to ensure it will help the next person. Please visit the `issues page <https://github.com/pandas-dev/pandas/issues?page=1&q=is%3Aopen+sort%3Aupdated-desc+label%3ADocs>`__ for a full list of issues that are currently open regarding the -Pandas documentation. +pandas documentation. diff --git a/doc/source/development/debugging_extensions.rst b/doc/source/development/debugging_extensions.rst index d63ecb3157cff..f09d73fa13b9a 100644 --- a/doc/source/development/debugging_extensions.rst +++ b/doc/source/development/debugging_extensions.rst @@ -6,7 +6,7 @@ Debugging C extensions ====================== -Pandas uses Cython and C/C++ `extension modules <https://docs.python.org/3/extending/extending.html>`_ to optimize performance. Unfortunately, the standard Python debugger does not allow you to step into these extensions. Cython extensions can be debugged with the `Cython debugger <https://docs.cython.org/en/latest/src/userguide/debugging.html>`_ and C/C++ extensions can be debugged using the tools shipped with your platform's compiler. +pandas uses Cython and C/C++ `extension modules <https://docs.python.org/3/extending/extending.html>`_ to optimize performance. Unfortunately, the standard Python debugger does not allow you to step into these extensions. Cython extensions can be debugged with the `Cython debugger <https://docs.cython.org/en/latest/src/userguide/debugging.html>`_ and C/C++ extensions can be debugged using the tools shipped with your platform's compiler. For Python developers with limited or no C/C++ experience this can seem a daunting task. Core developer Will Ayd has written a 3 part blog series to help guide you from the standard Python debugger into these other tools: diff --git a/doc/source/development/maintaining.rst b/doc/source/development/maintaining.rst index c7803d8401e4e..f177684b8c98f 100644 --- a/doc/source/development/maintaining.rst +++ b/doc/source/development/maintaining.rst @@ -430,7 +430,7 @@ Release git checkout <branch> git pull --ff-only upstream <branch> git clean -xdf - git commit --allow-empty --author="Pandas Development Team <pandas-dev@python.org>" -m "RLS: <version>" + git commit --allow-empty --author="pandas Development Team <pandas-dev@python.org>" -m "RLS: <version>" git tag -a v<version> -m "Version <version>" # NOTE that the tag is v1.5.2 with "v" not 1.5.2 git push upstream <branch> --follow-tags @@ -460,7 +460,7 @@ which will be triggered when the tag is pushed. 4. Create a `new GitHub release <https://github.com/pandas-dev/pandas/releases/new>`_: - Tag: ``<version>`` - - Title: ``Pandas <version>`` + - Title: ``pandas <version>`` - Description: Copy the description of the last release of the same kind (release candidate, major/minor or patch release) - Files: ``pandas-<version>.tar.gz`` source distribution just generated - Set as a pre-release: Only check for a release candidate diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst index 0c3307cdd7473..3cdcb81c14961 100644 --- a/doc/source/user_guide/10min.rst +++ b/doc/source/user_guide/10min.rst @@ -19,7 +19,7 @@ Customarily, we import as follows: Basic data structures in pandas ------------------------------- -Pandas provides two types of classes for handling data: +pandas provides two types of classes for handling data: 1. :class:`Series`: a one-dimensional labeled array holding data of any type such as integers, strings, Python objects etc. diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 060db772b9682..9c48e66daacf0 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -1044,7 +1044,7 @@ Writing CSVs to binary file objects ``df.to_csv(..., mode="wb")`` allows writing a CSV to a file object opened binary mode. In most cases, it is not necessary to specify -``mode`` as Pandas will auto-detect whether the file object is +``mode`` as pandas will auto-detect whether the file object is opened in text or binary mode. .. ipython:: python @@ -1604,7 +1604,7 @@ Specifying ``iterator=True`` will also return the ``TextFileReader`` object: Specifying the parser engine '''''''''''''''''''''''''''' -Pandas currently supports three engines, the C engine, the python engine, and an experimental +pandas currently supports three engines, the C engine, the python engine, and an experimental pyarrow engine (requires the ``pyarrow`` package). In general, the pyarrow engine is fastest on larger workloads and is equivalent in speed to the C engine on most other workloads. The python engine tends to be slower than the pyarrow and C engines on most workloads. However, @@ -3910,7 +3910,7 @@ The look and feel of Excel worksheets created from pandas can be modified using .. note:: - As of Pandas 3.0, by default spreadsheets created with the ``to_excel`` method + As of pandas 3.0, by default spreadsheets created with the ``to_excel`` method will not contain any styling. Users wishing to bold text, add bordered styles, etc in a worksheet output by ``to_excel`` can do so by using :meth:`Styler.to_excel` to create styled excel files. For documentation on styling spreadsheets, see diff --git a/doc/source/whatsnew/v0.11.0.rst b/doc/source/whatsnew/v0.11.0.rst index f05cbc7f07d7d..dcb0d3229aa5d 100644 --- a/doc/source/whatsnew/v0.11.0.rst +++ b/doc/source/whatsnew/v0.11.0.rst @@ -12,7 +12,7 @@ Data have had quite a number of additions, and Dtype support is now full-fledged There are also a number of important API changes that long-time pandas users should pay close attention to. -There is a new section in the documentation, :ref:`10 Minutes to Pandas <10min>`, +There is a new section in the documentation, :ref:`10 Minutes to pandas <10min>`, primarily geared to new users. There is a new section in the documentation, :ref:`Cookbook <cookbook>`, a collection diff --git a/doc/source/whatsnew/v1.3.1.rst b/doc/source/whatsnew/v1.3.1.rst index a57995eb0db9a..f3b21554e668c 100644 --- a/doc/source/whatsnew/v1.3.1.rst +++ b/doc/source/whatsnew/v1.3.1.rst @@ -14,7 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- Pandas could not be built on PyPy (:issue:`42355`) +- pandas could not be built on PyPy (:issue:`42355`) - :class:`DataFrame` constructed with an older version of pandas could not be unpickled (:issue:`42345`) - Performance regression in constructing a :class:`DataFrame` from a dictionary of dictionaries (:issue:`42248`) - Fixed regression in :meth:`DataFrame.agg` dropping values when the DataFrame had an Extension Array dtype, a duplicate index, and ``axis=1`` (:issue:`42380`) diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index ec0b04f8b3b77..91953f693190c 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -607,7 +607,7 @@ Deprecated Int64Index, UInt64Index & Float64Index :class:`Int64Index`, :class:`UInt64Index` and :class:`Float64Index` have been deprecated in favor of the base :class:`Index` class and will be removed in -Pandas 2.0 (:issue:`43028`). +pandas 2.0 (:issue:`43028`). For constructing a numeric index, you can use the base :class:`Index` class instead specifying the data type (which will also work on older pandas diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index f4cd57af105dd..43aa63c284f38 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -63,7 +63,7 @@ We recommend installing the latest version of PyArrow to access the most recentl DataFrame interchange protocol implementation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Pandas now implement the DataFrame interchange API spec. +pandas now implement the DataFrame interchange API spec. See the full details on the API at https://data-apis.org/dataframe-protocol/latest/index.html The protocol consists of two parts: diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 16f53719ff3a7..cacbf8452ba32 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -57,7 +57,7 @@ can it now take all numpy numeric dtypes, i.e. pd.Index([1, 2, 3], dtype=np.uint16) pd.Index([1, 2, 3], dtype=np.float32) -The ability for :class:`Index` to hold the numpy numeric dtypes has meant some changes in Pandas +The ability for :class:`Index` to hold the numpy numeric dtypes has meant some changes in pandas functionality. In particular, operations that previously were forced to create 64-bit indexes, can now create indexes with lower bit sizes, e.g. 32-bit indexes. diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index d4eb5742ef928..495c8244142f9 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -67,7 +67,7 @@ DataFrame reductions preserve extension dtypes In previous versions of pandas, the results of DataFrame reductions (:meth:`DataFrame.sum` :meth:`DataFrame.mean` etc.) had NumPy dtypes, even when the DataFrames -were of extension dtypes. Pandas can now keep the dtypes when doing reductions over DataFrame +were of extension dtypes. pandas can now keep the dtypes when doing reductions over DataFrame columns with a common dtype (:issue:`52788`). *Old Behavior*
- [ ] 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/57464
2024-02-16T22:35:14Z
2024-02-17T01:10:50Z
2024-02-17T01:10:50Z
2024-02-17T11:15:12Z
DOC: add section Raises to PeriodIndex docstring
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 50c3b251170c2..4aee8293049f1 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -134,6 +134,12 @@ class PeriodIndex(DatetimeIndexOpsMixin): from_fields from_ordinals + Raises + ------ + ValueError + Passing the parameter data as a list without specifying either freq or + dtype will raise a ValueError: "freq not specified and cannot be inferred" + See Also -------- Index : The base pandas Index type.
we raise a ValueError: "freq not specified and cannot be inferred" if both freq and dtype are not specified in `PeriodIndex` ``` >>> pd.PeriodIndex(["2023-01-01", "2023-02-01", "2023-03-01", "2023-04-01"], freq="M") PeriodIndex(['2023-01', '2023-02', '2023-03', '2023-04'], dtype='period[M]') >>> pd.PeriodIndex(["2023-01-01", "2023-02-01", "2023-03-01", "2023-04-01"], dtype ="period[M]") PeriodIndex(['2023-01', '2023-02', '2023-03', '2023-04'], dtype='period[M]') >>> pd.PeriodIndex(["2023-01-01", "2023-02-01", "2023-03-01", "2023-04-01"]) ValueError: freq not specified and cannot be inferred ``` I added a section "Raises" to `PeriodIndex` documentation.
https://api.github.com/repos/pandas-dev/pandas/pulls/57461
2024-02-16T18:47:16Z
2024-02-16T20:53:46Z
2024-02-16T20:53:46Z
2024-02-16T20:53:52Z
Backport PR #57402 on branch 2.2.x (BUG: wrong future Warning on string assignment in certain condition)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 9733aff0e6eb5..5e814ec2a1b92 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :meth:`CategoricalIndex.difference` raising ``KeyError`` when other contains null values other than NaN (:issue:`57318`) - Fixed regression in :meth:`DataFrame.groupby` raising ``ValueError`` when grouping by a :class:`Series` in some cases (:issue:`57276`) - Fixed regression in :meth:`DataFrame.loc` raising ``IndexError`` for non-unique, masked dtype indexes where result has more than 10,000 rows (:issue:`57027`) +- Fixed regression in :meth:`DataFrame.loc` which was unnecessarily throwing "incompatible dtype warning" when expanding with partial row indexer and multiple columns (see `PDEP6 <https://pandas.pydata.org/pdeps/0006-ban-upcasting.html>`_) (:issue:`56503`) - Fixed regression in :meth:`DataFrame.map` with ``na_action="ignore"`` not being respected for NumPy nullable and :class:`ArrowDtypes` (:issue:`57316`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) - Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 4dc0d477f89e8..655a53997620a 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -647,6 +647,20 @@ def infer_fill_value(val): return np.nan +def construct_1d_array_from_inferred_fill_value( + value: object, length: int +) -> ArrayLike: + # Find our empty_value dtype by constructing an array + # from our value and doing a .take on it + from pandas.core.algorithms import take_nd + from pandas.core.construction import sanitize_array + from pandas.core.indexes.base import Index + + arr = sanitize_array(value, Index(range(1)), copy=False) + taker = -1 * np.ones(length, dtype=np.intp) + return take_nd(arr, taker) + + def maybe_fill(arr: np.ndarray) -> np.ndarray: """ Fill numpy.ndarray with NaN, unless we have a integer or boolean dtype. diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 934ba3a4d7f29..869e511fc0720 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -57,6 +57,7 @@ ABCSeries, ) from pandas.core.dtypes.missing import ( + construct_1d_array_from_inferred_fill_value, infer_fill_value, is_valid_na_for_dtype, isna, @@ -68,7 +69,6 @@ from pandas.core.construction import ( array as pd_array, extract_array, - sanitize_array, ) from pandas.core.indexers import ( check_array_indexer, @@ -844,7 +844,6 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None: if self.ndim != 2: return - orig_key = key if isinstance(key, tuple) and len(key) > 1: # key may be a tuple if we are .loc # if length of key is > 1 set key to column part @@ -862,7 +861,7 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None: keys = self.obj.columns.union(key, sort=False) diff = Index(key).difference(self.obj.columns, sort=False) - if len(diff) and com.is_null_slice(orig_key[0]): + if len(diff): # e.g. if we are doing df.loc[:, ["A", "B"]] = 7 and "B" # is a new column, add the new columns with dtype=np.void # so that later when we go through setitem_single_column @@ -1878,12 +1877,9 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc"): self.obj[key] = empty_value elif not is_list_like(value): - # Find our empty_value dtype by constructing an array - # from our value and doing a .take on it - arr = sanitize_array(value, Index(range(1)), copy=False) - taker = -1 * np.ones(len(self.obj), dtype=np.intp) - empty_value = algos.take_nd(arr, taker) - self.obj[key] = empty_value + self.obj[key] = construct_1d_array_from_inferred_fill_value( + value, len(self.obj) + ) else: # FIXME: GH#42099#issuecomment-864326014 self.obj[key] = infer_fill_value(value) @@ -2165,6 +2161,17 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None: else: # set value into the column (first attempting to operate inplace, then # falling back to casting if necessary) + dtype = self.obj.dtypes.iloc[loc] + if dtype == np.void: + # This means we're expanding, with multiple columns, e.g. + # df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]}) + # df.loc[df.index <= 2, ['F', 'G']] = (1, 'abc') + # Columns F and G will initially be set to np.void. + # Here, we replace those temporary `np.void` columns with + # columns of the appropriate dtype, based on `value`. + self.obj.iloc[:, loc] = construct_1d_array_from_inferred_fill_value( + value, len(self.obj) + ) self.obj._mgr.column_setitem(loc, plane_indexer, value) self.obj._clear_item_cache() diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 99233d3cd4cf3..a58dd701f0f22 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -1401,3 +1401,19 @@ def test_full_setter_loc_incompatible_dtype(): df.loc[:, "a"] = {0: 3, 1: 4} expected = DataFrame({"a": [3, 4]}) tm.assert_frame_equal(df, expected) + + +def test_setitem_partial_row_multiple_columns(): + # https://github.com/pandas-dev/pandas/issues/56503 + df = DataFrame({"A": [1, 2, 3], "B": [4.0, 5, 6]}) + # should not warn + df.loc[df.index <= 1, ["F", "G"]] = (1, "abc") + expected = DataFrame( + { + "A": [1, 2, 3], + "B": [4.0, 5, 6], + "F": [1.0, 1, float("nan")], + "G": ["abc", "abc", float("nan")], + } + ) + tm.assert_frame_equal(df, expected)
Backport PR #57402: BUG: wrong future Warning on string assignment in certain condition
https://api.github.com/repos/pandas-dev/pandas/pulls/57460
2024-02-16T17:57:53Z
2024-02-16T19:21:45Z
2024-02-16T19:21:45Z
2024-02-16T19:21:46Z
PERF: DataFrame(ndarray) constructor ensure to copy to column-major layout
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index aab0f1c6dac3c..6bc3556902e80 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -250,10 +250,12 @@ def ndarray_to_mgr( elif isinstance(values, (np.ndarray, ExtensionArray)): # drop subclass info - _copy = ( - copy if (dtype is None or astype_is_view(values.dtype, dtype)) else False - ) - values = np.array(values, copy=_copy) + if copy and (dtype is None or astype_is_view(values.dtype, dtype)): + # only force a copy now if copy=True was requested + # and a subsequent `astype` will not already result in a copy + values = np.array(values, copy=True, order="F") + else: + values = np.array(values, copy=False) values = _ensure_2d(values) else:
Closes https://github.com/pandas-dev/pandas/issues/50756 xref https://github.com/pandas-dev/pandas/issues/57431 With CoW enabled now, the default behaviour of `DataFrame(ndarray)` is to copy the numpy array (before 3.0, this would not copy the data). However, if we do a copy, we should also make sure we copy it to the optimal layout (typically column major). Before CoW, this copy would often happen later on anyway, and an explicit `copy()` actually does ensure column-major layout: On main: ``` >>> arr = np.random.randn(10, 3) >>> df = pd.DataFrame(arr) # does actually make a copy of `arr` under the hood >>> df._mgr.blocks[0].values.flags.c_contiguous False >>> df2 = df.copy() # explicit copy method >>> df2._mgr.blocks[0].values.flags.c_contiguous True ```
https://api.github.com/repos/pandas-dev/pandas/pulls/57459
2024-02-16T17:01:18Z
2024-03-05T00:56:59Z
2024-03-05T00:56:59Z
2024-03-07T08:33:08Z
Backport PR #57450 on branch 2.2.x (DOC: Set verbose parameter as deprecated in docstring)
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index e26e7e7470461..e04f27b560610 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -240,6 +240,8 @@ performance of reading a large file. verbose : bool, default False Indicate number of ``NA`` values placed in non-numeric columns. + + .. deprecated:: 2.2.0 skip_blank_lines : bool, default True If ``True``, skip over blank lines rather than interpreting as ``NaN`` values. parse_dates : bool, list of Hashable, list of lists or dict of {{Hashable : list}}, \
Backport PR #57450: DOC: Set verbose parameter as deprecated in docstring
https://api.github.com/repos/pandas-dev/pandas/pulls/57455
2024-02-16T14:02:29Z
2024-02-16T17:26:32Z
2024-02-16T17:26:32Z
2024-02-16T17:26:33Z
Release the gil in take for axis=1
diff --git a/pandas/_libs/algos_take_helper.pxi.in b/pandas/_libs/algos_take_helper.pxi.in index 88c3abba506a3..385727fad3c50 100644 --- a/pandas/_libs/algos_take_helper.pxi.in +++ b/pandas/_libs/algos_take_helper.pxi.in @@ -184,6 +184,17 @@ def take_2d_axis1_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values, fv = fill_value + {{if c_type_in == c_type_out != "object"}} + with nogil: + for i in range(n): + for j in range(k): + idx = indexer[j] + if idx == -1: + out[i, j] = fv + else: + out[i, j] = values[i, idx] + + {{else}} for i in range(n): for j in range(k): idx = indexer[j] @@ -195,6 +206,7 @@ def take_2d_axis1_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values, {{else}} out[i, j] = values[i, idx] {{endif}} + {{endif}} @cython.wraparound(False)
- [ ] 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. We missed this when we took care of axis=0 in Basel
https://api.github.com/repos/pandas-dev/pandas/pulls/57454
2024-02-16T14:02:11Z
2024-02-16T16:05:18Z
2024-02-16T16:05:18Z
2024-02-18T11:44:10Z
DOC: Set verbose parameter as deprecated in docstring
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index d9dc5b41a81c2..018f597526acd 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -238,6 +238,8 @@ performance of reading a large file. verbose : bool, default False Indicate number of ``NA`` values placed in non-numeric columns. + + .. deprecated:: 2.2.0 skip_blank_lines : bool, default True If ``True``, skip over blank lines rather than interpreting as ``NaN`` values. parse_dates : bool, list of Hashable, list of lists or dict of {{Hashable : list}}, \
This PR follows: - #56556 TODO: - [x] closes #57451 - [ ] [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/57450
2024-02-16T11:02:22Z
2024-02-16T14:01:44Z
2024-02-16T14:01:44Z
2024-02-16T14:45:38Z
DOC: fix SA05 errors in docstrings for pandas.core.window Expanding and Rolling, and SeriesGroupBy
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index f3666647f47e1..231d40e17c0c0 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -65,8 +65,8 @@ fi ### DOCSTRINGS ### if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then - MSG='Validate docstrings (EX01, EX03, EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT02, RT04, RT05, SA02, SA03, SA04, SS01, SS02, SS03, SS04, SS05, SS06)' ; echo $MSG - $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01,EX03,EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT02,RT04,RT05,SA02,SA03,SA04,SS01,SS02,SS03,SS04,SS05,SS06 + MSG='Validate docstrings (EX01, EX03, EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT02, RT04, RT05, SA02, SA03, SA04, SA05, SS01, SS02, SS03, SS04, SS05, SS06)' ; echo $MSG + $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01,EX03,EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT02,RT04,RT05,SA02,SA03,SA04,SA05,SS01,SS02,SS03,SS04,SS05,SS06 RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Partially validate docstrings (PR02)' ; echo $MSG @@ -3182,14 +3182,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.util.hash_pandas_object # There should be no backslash in the final line, please keep this comment in the last ignored function RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Partially validate docstrings (SA05)' ; echo $MSG - $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=SA05 --ignore_functions \ - pandas.core.groupby.SeriesGroupBy.first\ - pandas.core.groupby.SeriesGroupBy.last\ - pandas.core.window.expanding.Expanding.aggregate\ - pandas.core.window.rolling.Rolling.aggregate # There should be no backslash in the final line, please keep this comment in the last ignored function - RET=$(($RET + $?)) ; echo $MSG "DONE" - fi ### DOCUMENTATION NOTEBOOKS ### diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index c048c4a506629..c3ee53c1b4551 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -139,8 +139,8 @@ def _get_window_indexer(self) -> BaseIndexer: """ See Also -------- - pandas.DataFrame.aggregate : Similar DataFrame method. - pandas.Series.aggregate : Similar Series method. + DataFrame.aggregate : Similar DataFrame method. + Series.aggregate : Similar Series method. """ ), examples=dedent( diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 9e42a9033fb66..aa55dd41f0997 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1216,8 +1216,8 @@ def calc(x): """ See Also -------- - pandas.DataFrame.aggregate : Similar DataFrame method. - pandas.Series.aggregate : Similar Series method. + DataFrame.aggregate : Similar DataFrame method. + Series.aggregate : Similar Series method. """ ), examples=dedent( @@ -1906,8 +1906,8 @@ def _raise_monotonic_error(self, msg: str): """ See Also -------- - pandas.Series.rolling : Calling object with Series data. - pandas.DataFrame.rolling : Calling object with DataFrame data. + Series.rolling : Calling object with Series data. + DataFrame.rolling : Calling object with DataFrame data. """ ), examples=dedent(
- [x] closes #57392 - [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.
https://api.github.com/repos/pandas-dev/pandas/pulls/57446
2024-02-15T23:52:03Z
2024-02-16T17:24:30Z
2024-02-16T17:24:30Z
2024-02-16T17:24:30Z
PERF: Allow RangeIndex.take to return a RangeIndex when possible
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 483cf659080ea..e74967695a2ff 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -166,6 +166,7 @@ Performance improvements - Performance improvement in :meth:`Index.take` when ``indices`` is a full range indexer from zero to length of index (:issue:`56806`) - Performance improvement in :meth:`MultiIndex.equals` for equal length indexes (:issue:`56990`) - Performance improvement in :meth:`RangeIndex.append` when appending the same index (:issue:`57252`) +- Performance improvement in :meth:`RangeIndex.take` returning a :class:`RangeIndex` instead of a :class:`Index` when possible. (:issue:`57445`) - Performance improvement in indexing operations for string dtypes (:issue:`56997`) - diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index a8e8ae140041a..20286cad58df9 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1006,11 +1006,13 @@ def _concat(self, indexes: list[Index], name: Hashable) -> Index: # Get the stop value from "next" or alternatively # from the last non-empty index stop = non_empty_indexes[-1].stop if next_ is None else next_ - return RangeIndex(start, stop, step).rename(name) + if len(non_empty_indexes) == 1: + step = non_empty_indexes[0].step + return RangeIndex(start, stop, step, name=name) # Here all "indexes" had 0 length, i.e. were empty. # In this case return an empty range index. - return RangeIndex(0, 0).rename(name) + return RangeIndex(_empty_range, name=name) def __len__(self) -> int: """ @@ -1168,7 +1170,7 @@ def take( # type: ignore[override] allow_fill: bool = True, fill_value=None, **kwargs, - ) -> Index: + ) -> Self | Index: if kwargs: nv.validate_take((), kwargs) if is_scalar(indices): @@ -1179,7 +1181,7 @@ def take( # type: ignore[override] self._maybe_disallow_fill(allow_fill, fill_value, indices) if len(indices) == 0: - taken = np.array([], dtype=self.dtype) + return type(self)(_empty_range, name=self.name) else: ind_max = indices.max() if ind_max >= len(self): @@ -1199,5 +1201,4 @@ def take( # type: ignore[override] if self.start != 0: taken += self.start - # _constructor so RangeIndex-> Index with an int64 dtype - return self._constructor._simple_new(taken, name=self.name) + return self._shallow_copy(taken, name=self.name) diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 29d6916cc7f08..d500687763a1e 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -606,3 +606,20 @@ def test_range_index_rsub_by_const(self): result = 3 - RangeIndex(0, 4, 1) expected = RangeIndex(3, -1, -1) tm.assert_index_equal(result, expected) + + +def test_take_return_rangeindex(): + ri = RangeIndex(5, name="foo") + result = ri.take([]) + expected = RangeIndex(0, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + result = ri.take([3, 4]) + expected = RangeIndex(3, 5, name="foo") + tm.assert_index_equal(result, expected, exact=True) + + +def test_append_one_nonempty_preserve_step(): + expected = RangeIndex(0, -1, -1) + result = RangeIndex(0).append([expected]) + tm.assert_index_equal(result, expected, exact=True)
Discovered in https://github.com/pandas-dev/pandas/pull/57441
https://api.github.com/repos/pandas-dev/pandas/pulls/57445
2024-02-15T23:45:09Z
2024-02-18T21:43:10Z
2024-02-18T21:43:10Z
2024-02-20T10:12:15Z
CLN: Enforce deprecation of using alias for builtin/NumPy funcs
diff --git a/doc/source/whatsnew/v0.15.1.rst b/doc/source/whatsnew/v0.15.1.rst index 09b59f35972cd..765201996d544 100644 --- a/doc/source/whatsnew/v0.15.1.rst +++ b/doc/source/whatsnew/v0.15.1.rst @@ -92,7 +92,7 @@ API changes .. code-block:: ipython - In [4]: gr.apply(sum) + In [4]: gr.apply("sum") Out[4]: joe jim @@ -102,9 +102,8 @@ API changes current behavior: .. ipython:: python - :okwarning: - gr.apply(sum) + gr.apply("sum") - Support for slicing with monotonic decreasing indexes, even if ``start`` or ``stop`` is not found in the index (:issue:`7860`): diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 8bb051b6228ce..a95f0485abd5f 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -199,6 +199,7 @@ Removal of prior version deprecations/changes - Enforced deprecation disallowing parsing datetimes with mixed time zones unless user passes ``utc=True`` to :func:`to_datetime` (:issue:`57275`) - Enforced silent-downcasting deprecation for :ref:`all relevant methods <whatsnew_220.silent_downcasting>` (:issue:`54710`) - In :meth:`DataFrame.stack`, the default value of ``future_stack`` is now ``True``; specifying ``False`` will raise a ``FutureWarning`` (:issue:`55448`) +- Methods ``apply``, ``agg``, and ``transform`` will no longer replace NumPy functions (e.g. ``np.sum``) and built-in functions (e.g. ``min``) with the equivalent pandas implementation; use string aliases (e.g. ``"sum"`` and ``"min"``) if you desire to use the pandas implementation (:issue:`53974`) - Passing both ``freq`` and ``fill_value`` in :meth:`DataFrame.shift` and :meth:`Series.shift` and :meth:`.DataFrameGroupBy.shift` now raises a ``ValueError`` (:issue:`54818`) - Removed :meth:`DateOffset.is_anchored` and :meth:`offsets.Tick.is_anchored` (:issue:`56594`) - Removed ``DataFrame.applymap``, ``Styler.applymap`` and ``Styler.applymap_index`` (:issue:`52364`) diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index ddd8d07c5f2eb..12395b42bba19 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -398,9 +398,6 @@ def external_error_raised(expected_exception: type[Exception]) -> ContextManager return pytest.raises(expected_exception, match=None) -cython_table = pd.core.common._cython_table.items() - - def get_cython_table_params(ndframe, func_names_and_expected): """ Combine frame, functions from com._cython_table @@ -421,11 +418,6 @@ def get_cython_table_params(ndframe, func_names_and_expected): results = [] for func_name, expected in func_names_and_expected: results.append((ndframe, func_name, expected)) - results += [ - (ndframe, func, expected) - for func, name in cython_table - if name == func_name - ] return results diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 0dabb76c2581d..d9d95c96ba0fe 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -175,10 +175,7 @@ def agg(self) -> DataFrame | Series | None: Result of aggregation, or None if agg cannot be performed by this method. """ - obj = self.obj func = self.func - args = self.args - kwargs = self.kwargs if isinstance(func, str): return self.apply_str() @@ -189,12 +186,6 @@ def agg(self) -> DataFrame | Series | None: # we require a list, but not a 'str' return self.agg_list_like() - if callable(func): - f = com.get_cython_func(func) - if f and not args and not kwargs: - warn_alias_replacement(obj, func, f) - return getattr(obj, f)() - # caller can react return None @@ -300,12 +291,6 @@ def transform_str_or_callable(self, func) -> DataFrame | Series: if isinstance(func, str): return self._apply_str(obj, func, *args, **kwargs) - if not args and not kwargs: - f = com.get_cython_func(func) - if f: - warn_alias_replacement(obj, func, f) - return getattr(obj, f)() - # Two possible ways to use a UDF - apply or call directly try: return obj.apply(func, args=args, **kwargs) diff --git a/pandas/core/common.py b/pandas/core/common.py index 8ae30c5257c8b..5f37f3de578e8 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -608,22 +608,6 @@ def require_length_match(data, index: Index) -> None: ) -# the ufuncs np.maximum.reduce and np.minimum.reduce default to axis=0, -# whereas np.min and np.max (which directly call obj.min and obj.max) -# default to axis=None. -_builtin_table = { - builtins.sum: np.sum, - builtins.max: np.maximum.reduce, - builtins.min: np.minimum.reduce, -} - -# GH#53425: Only for deprecation -_builtin_table_alias = { - builtins.sum: "np.sum", - builtins.max: "np.maximum.reduce", - builtins.min: "np.minimum.reduce", -} - _cython_table = { builtins.sum: "sum", builtins.max: "max", @@ -660,14 +644,6 @@ def get_cython_func(arg: Callable) -> str | None: return _cython_table.get(arg) -def is_builtin_func(arg): - """ - if we define a builtin function for this argument, return it, - otherwise return the arg - """ - return _builtin_table.get(arg, arg) - - def fill_missing_names(names: Sequence[Hashable | None]) -> list[Hashable]: """ If a name is missing then replace it by level_n, where n is the count diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index a604283f3d078..ab5e8bbd4528c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -59,7 +59,6 @@ maybe_mangle_lambdas, reconstruct_func, validate_func_kwargs, - warn_alias_replacement, ) import pandas.core.common as com from pandas.core.frame import DataFrame @@ -357,11 +356,6 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) return ret else: - cyfunc = com.get_cython_func(func) - if cyfunc and not args and not kwargs: - warn_alias_replacement(self, func, cyfunc) - return getattr(self, cyfunc)() - if maybe_use_numba(engine): return self._aggregate_with_numba( func, *args, engine_kwargs=engine_kwargs, **kwargs @@ -409,11 +403,6 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) agg = aggregate def _python_agg_general(self, func, *args, **kwargs): - orig_func = func - func = com.is_builtin_func(func) - if orig_func != func: - alias = com._builtin_table_alias[func] - warn_alias_replacement(self, orig_func, alias) f = lambda x: func(x, *args, **kwargs) obj = self._obj_with_exclusions @@ -1656,11 +1645,6 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) agg = aggregate def _python_agg_general(self, func, *args, **kwargs): - orig_func = func - func = com.is_builtin_func(func) - if orig_func != func: - alias = com._builtin_table_alias[func] - warn_alias_replacement(self, orig_func, alias) f = lambda x: func(x, *args, **kwargs) if self.ngroups == 0: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 4fa0fe140924a..61168f71f4924 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -94,7 +94,6 @@ class providing the base-class of operations. sample, ) from pandas.core._numba import executor -from pandas.core.apply import warn_alias_replacement from pandas.core.arrays import ( ArrowExtensionArray, BaseMaskedArray, @@ -1647,12 +1646,6 @@ def apply(self, func, *args, include_groups: bool = True, **kwargs) -> NDFrameT: b 2 dtype: int64 """ - orig_func = func - func = com.is_builtin_func(func) - if orig_func != func: - alias = com._builtin_table_alias[orig_func] - warn_alias_replacement(self, orig_func, alias) - if isinstance(func, str): if hasattr(self, func): res = getattr(self, func) @@ -1868,11 +1861,6 @@ def _cython_transform(self, how: str, numeric_only: bool = False, **kwargs): @final def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): # optimized transforms - orig_func = func - func = com.get_cython_func(func) or func - if orig_func != func: - warn_alias_replacement(self, orig_func, func) - if not isinstance(func, str): return self._transform_general(func, engine, engine_kwargs, *args, **kwargs) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 4147437114b2f..915cd189c73a9 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -45,16 +45,12 @@ ) import pandas.core.algorithms as algos -from pandas.core.apply import ( - ResamplerWindowApply, - warn_alias_replacement, -) +from pandas.core.apply import ResamplerWindowApply from pandas.core.arrays import ArrowExtensionArray from pandas.core.base import ( PandasObject, SelectionMixin, ) -import pandas.core.common as com from pandas.core.generic import ( NDFrame, _shared_docs, @@ -1609,10 +1605,6 @@ def _downsample(self, how, **kwargs): how : string / cython mapped function **kwargs : kw args passed to how function """ - orig_how = how - how = com.get_cython_func(how) or how - if orig_how != how: - warn_alias_replacement(self, orig_how, how) ax = self.ax # Excludes `on` column when provided @@ -1775,10 +1767,6 @@ def _downsample(self, how, **kwargs): if self.kind == "timestamp": return super()._downsample(how, **kwargs) - orig_how = how - how = com.get_cython_func(how) or how - if orig_how != how: - warn_alias_replacement(self, orig_how, how) ax = self.ax if is_subperiod(ax.freq, self.freq): diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index 2dd7f9902c78d..9f3fee686a056 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1699,13 +1699,11 @@ def foo2(x, b=2, c=0): def test_agg_std(): df = DataFrame(np.arange(6).reshape(3, 2), columns=["A", "B"]) - with tm.assert_produces_warning(FutureWarning, match="using DataFrame.std"): - result = df.agg(np.std) + result = df.agg(np.std, ddof=1) expected = Series({"A": 2.0, "B": 2.0}, dtype=float) tm.assert_series_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, match="using Series.std"): - result = df.agg([np.std]) + result = df.agg([np.std], ddof=1) expected = DataFrame({"A": 2.0, "B": 2.0}, index=["std"]) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/apply/test_frame_apply_relabeling.py b/pandas/tests/apply/test_frame_apply_relabeling.py index 723bdd349c0cb..57c109abba304 100644 --- a/pandas/tests/apply/test_frame_apply_relabeling.py +++ b/pandas/tests/apply/test_frame_apply_relabeling.py @@ -49,24 +49,20 @@ def test_agg_relabel_multi_columns_multi_methods(): def test_agg_relabel_partial_functions(): # GH 26513, test on partial, functools or more complex cases df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]}) - msg = "using Series.[mean|min]" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.agg(foo=("A", np.mean), bar=("A", "mean"), cat=("A", min)) + result = df.agg(foo=("A", np.mean), bar=("A", "mean"), cat=("A", min)) expected = pd.DataFrame( {"A": [1.5, 1.5, 1.0]}, index=pd.Index(["foo", "bar", "cat"]) ) tm.assert_frame_equal(result, expected) - msg = "using Series.[mean|min|max|sum]" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.agg( - foo=("A", min), - bar=("A", np.min), - cat=("B", max), - dat=("C", "min"), - f=("B", np.sum), - kk=("B", lambda x: min(x)), - ) + result = df.agg( + foo=("A", min), + bar=("A", np.min), + cat=("B", max), + dat=("C", "min"), + f=("B", np.sum), + kk=("B", lambda x: min(x)), + ) expected = pd.DataFrame( { "A": [1.0, 1.0, np.nan, np.nan, np.nan, np.nan], diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index e0153c97b8f29..53fc135e77780 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -547,10 +547,7 @@ def test_apply_listlike_reducer(string_series, ops, names, how, kwargs): # GH 39140 expected = Series({name: op(string_series) for name, op in zip(names, ops)}) expected.name = "series" - warn = FutureWarning if how == "agg" else None - msg = f"using Series.[{'|'.join(names)}]" - with tm.assert_produces_warning(warn, match=msg): - result = getattr(string_series, how)(ops, **kwargs) + result = getattr(string_series, how)(ops, **kwargs) tm.assert_series_equal(result, expected) @@ -571,10 +568,7 @@ def test_apply_dictlike_reducer(string_series, ops, how, kwargs, by_row): # GH 39140 expected = Series({name: op(string_series) for name, op in ops.items()}) expected.name = string_series.name - warn = FutureWarning if how == "agg" else None - msg = "using Series.[sum|mean]" - with tm.assert_produces_warning(warn, match=msg): - result = getattr(string_series, how)(ops, **kwargs) + result = getattr(string_series, how)(ops, **kwargs) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/apply/test_series_apply_relabeling.py b/pandas/tests/apply/test_series_apply_relabeling.py index cdfa054f91c9b..c0a285e6eb38c 100644 --- a/pandas/tests/apply/test_series_apply_relabeling.py +++ b/pandas/tests/apply/test_series_apply_relabeling.py @@ -14,12 +14,8 @@ def test_relabel_no_duplicated_method(): expected = df["B"].agg({"foo": "min", "bar": "max"}) tm.assert_series_equal(result, expected) - msg = "using Series.[sum|min|max]" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df["B"].agg(foo=sum, bar=min, cat="max") - msg = "using Series.[sum|min|max]" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = df["B"].agg({"foo": sum, "bar": min, "cat": "max"}) + result = df["B"].agg(foo=sum, bar=min, cat="max") + expected = df["B"].agg({"foo": sum, "bar": min, "cat": "max"}) tm.assert_series_equal(result, expected) @@ -32,8 +28,6 @@ def test_relabel_duplicated_method(): expected = pd.Series([6, 6], index=["foo", "bar"], name="A") tm.assert_series_equal(result, expected) - msg = "using Series.min" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df["B"].agg(foo=min, bar="min") + result = df["B"].agg(foo=min, bar="min") expected = pd.Series([1, 1], index=["foo", "bar"], name="B") tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index c6962815ffda1..255784e8bf24d 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -289,9 +289,7 @@ def func(ser): def test_agg_multiple_functions_maintain_order(df): # GH #610 funcs = [("mean", np.mean), ("max", np.max), ("min", np.min)] - msg = "is currently using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby("A")["C"].agg(funcs) + result = df.groupby("A")["C"].agg(funcs) exp_cols = Index(["mean", "max", "min"]) tm.assert_index_equal(result.columns, exp_cols) @@ -881,11 +879,9 @@ def test_agg_relabel_multiindex_column( expected = DataFrame({"a_max": [1, 3]}, index=idx) tm.assert_frame_equal(result, expected) - msg = "is currently using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby(("x", "group")).agg( - col_1=agg_col1, col_2=agg_col2, col_3=agg_col3 - ) + result = df.groupby(("x", "group")).agg( + col_1=agg_col1, col_2=agg_col2, col_3=agg_col3 + ) expected = DataFrame( {"col_1": agg_result1, "col_2": agg_result2, "col_3": agg_result3}, index=idx ) @@ -1036,13 +1032,6 @@ def test_groupby_as_index_agg(df): gr = df.groupby(ts) gr.nth(0) # invokes set_selection_from_grouper internally - msg = "The behavior of DataFrame.sum with axis=None is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): - res = gr.apply(sum) - with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): - alt = df.groupby(ts).apply(sum) - tm.assert_frame_equal(res, alt) - for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]: gr = df.groupby(ts, as_index=False) left = getattr(gr, attr)() diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index 19eef06de9136..aafd06e8f88cf 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -21,7 +21,6 @@ bdate_range, ) import pandas._testing as tm -import pandas.core.common as com @pytest.mark.parametrize( @@ -85,10 +84,8 @@ def test_cython_agg_boolean(): } ) result = frame.groupby("a")["b"].mean() - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - expected = frame.groupby("a")["b"].agg(np.mean) + # GH#53425 + expected = frame.groupby("a")["b"].agg(np.mean) tm.assert_series_equal(result, expected) @@ -152,10 +149,7 @@ def test_cython_fail_agg(): grouped = ts.groupby(lambda x: x.month) summed = grouped.sum() - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - expected = grouped.agg(np.sum) + expected = grouped.agg(np.sum) tm.assert_series_equal(summed, expected) @@ -176,13 +170,12 @@ def test_cython_fail_agg(): def test__cython_agg_general(op, targop): df = DataFrame(np.random.default_rng(2).standard_normal(1000)) labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + kwargs = {"ddof": 1} if op == "var" else {} + if op not in ["first", "last"]: + kwargs["axis"] = 0 result = df.groupby(labels)._cython_agg_general(op, alt=None, numeric_only=True) - warn = FutureWarning if targop in com._cython_table else None - msg = f"using DataFrameGroupBy.{op}" - with tm.assert_produces_warning(warn, match=msg): - # GH#53425 - expected = df.groupby(labels).agg(targop) + expected = df.groupby(labels).agg(targop, **kwargs) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index ef45381ba1a7f..12f99e3cf7a63 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -410,10 +410,7 @@ def __call__(self, x): expected = df.groupby("foo").agg("sum") for ecall in equiv_callables: - warn = FutureWarning if ecall is sum or ecall is np.sum else None - msg = "using DataFrameGroupBy.sum" - with tm.assert_produces_warning(warn, match=msg): - result = df.groupby("foo").agg(ecall) + result = df.groupby("foo").agg(ecall) tm.assert_frame_equal(result, expected) @@ -587,9 +584,7 @@ def test_agg_category_nansum(observed): df = DataFrame( {"A": pd.Categorical(["a", "a", "b"], categories=categories), "B": [1, 2, 3]} ) - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby("A", observed=observed).B.agg(np.nansum) + result = df.groupby("A", observed=observed).B.agg(np.nansum) expected = Series( [3, 3, 0], index=pd.CategoricalIndex(["a", "b", "c"], categories=categories, name="A"), diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index ee82d8ad37c2d..dcb73bdba2f9c 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -1177,17 +1177,14 @@ def test_apply_is_unchanged_when_other_methods_are_called_first(reduction_func): # Check output when no other methods are called before .apply() grp = df.groupby(by="a") - msg = "The behavior of DataFrame.sum with axis=None is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): - result = grp.apply(sum, include_groups=False) + result = grp.apply(np.sum, axis=0, include_groups=False) tm.assert_frame_equal(result, expected) # Check output when another method is called before .apply() grp = df.groupby(by="a") args = get_groupby_method_args(reduction_func, df) _ = getattr(grp, reduction_func)(*args) - with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): - result = grp.apply(sum, include_groups=False) + result = grp.apply(np.sum, axis=0, include_groups=False) tm.assert_frame_equal(result, expected) @@ -1503,46 +1500,16 @@ def test_include_groups(include_groups): tm.assert_frame_equal(result, expected) -@pytest.mark.parametrize("f", [max, min, sum]) -@pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key -def test_builtins_apply(keys, f): - # see gh-8155 - rs = np.random.default_rng(2) - df = DataFrame(rs.integers(1, 7, (10, 2)), columns=["jim", "joe"]) - df["jolie"] = rs.standard_normal(10) +@pytest.mark.parametrize("func, value", [(max, 2), (min, 1), (sum, 3)]) +def test_builtins_apply(func, value): + # GH#8155, GH#53974 + # Builtins act as e.g. sum(group), which sums the column labels of group + df = DataFrame({0: [1, 1, 2], 1: [3, 4, 5], 2: [3, 4, 5]}) + gb = df.groupby(0) + result = gb.apply(func, include_groups=False) - gb = df.groupby(keys) - - fname = f.__name__ - - warn = None if f is not sum else FutureWarning - msg = "The behavior of DataFrame.sum with axis=None is deprecated" - with tm.assert_produces_warning( - warn, match=msg, check_stacklevel=False, raise_on_extra_warnings=False - ): - # Also warns on deprecation GH#53425 - result = gb.apply(f) - ngroups = len(df.drop_duplicates(subset=keys)) - - assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))" - assert result.shape == (ngroups, 3), assert_msg - - npfunc = lambda x: getattr(np, fname)(x, axis=0) # numpy's equivalent function - msg = "DataFrameGroupBy.apply operated on the grouping columns" - with tm.assert_produces_warning(DeprecationWarning, match=msg): - expected = gb.apply(npfunc) - tm.assert_frame_equal(result, expected) - - with tm.assert_produces_warning(DeprecationWarning, match=msg): - expected2 = gb.apply(lambda x: npfunc(x)) - tm.assert_frame_equal(result, expected2) - - if f != sum: - expected = gb.agg(fname).reset_index() - expected.set_index(keys, inplace=True, drop=False) - tm.assert_frame_equal(result, expected, check_dtype=False) - - tm.assert_series_equal(getattr(result, fname)(axis=0), getattr(df, fname)(axis=0)) + expected = Series([value, value], index=Index([1, 2], name=0)) + tm.assert_series_equal(result, expected) def test_inconsistent_return_type(): diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 10eca5ea8427f..76c8a6fdb9570 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -138,19 +138,13 @@ def f(x): df = DataFrame({"a": [5, 15, 25]}) c = pd.cut(df.a, bins=[0, 10, 20, 30, 40]) - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = df.a.groupby(c, observed=False).transform(sum) + result = df.a.groupby(c, observed=False).transform(sum) tm.assert_series_equal(result, df["a"]) tm.assert_series_equal( df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"] ) - msg = "using DataFrameGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = df.groupby(c, observed=False).transform(sum) + result = df.groupby(c, observed=False).transform(sum) expected = df[["a"]] tm.assert_frame_equal(result, expected) @@ -159,10 +153,7 @@ def f(x): tm.assert_frame_equal(result, df[["a"]]) result2 = gbc.transform(lambda xs: np.max(xs, axis=0)) - msg = "using DataFrameGroupBy.max" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result3 = gbc.transform(max) + result3 = gbc.transform(max) result4 = gbc.transform(np.maximum.reduce) result5 = gbc.transform(lambda xs: np.maximum.reduce(xs)) tm.assert_frame_equal(result2, df[["a"]], check_dtype=False) @@ -178,19 +169,13 @@ def f(x): df = DataFrame({"a": [5, 15, 25, -5]}) c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40]) - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = df.a.groupby(c, observed=False).transform(sum) + result = df.a.groupby(c, observed=False).transform(sum) tm.assert_series_equal(result, df["a"]) tm.assert_series_equal( df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"] ) - msg = "using DataFrameGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = df.groupby(c, observed=False).transform(sum) + result = df.groupby(c, observed=False).transform(sum) expected = df[["a"]] tm.assert_frame_equal(result, expected) @@ -319,10 +304,7 @@ def test_apply(ordered): result = grouped.mean() tm.assert_frame_equal(result, expected) - msg = "using DataFrameGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = grouped.agg(np.mean) + result = grouped.agg(np.mean) tm.assert_frame_equal(result, expected) # but for transform we should still get back the original index @@ -1245,10 +1227,7 @@ def test_seriesgroupby_observed_true(df_cat, operation): expected = Series(data=[2, 4, 1, 3], index=index, name="C").sort_index() grouped = df_cat.groupby(["A", "B"], observed=True)["C"] - msg = "using np.sum" if operation == "apply" else "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = getattr(grouped, operation)(sum) + result = getattr(grouped, operation)(sum) tm.assert_series_equal(result, expected) @@ -1267,10 +1246,7 @@ def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation): expected = Series(data=[2, 4, 0, 1, 0, 3], index=index, name="C") grouped = df_cat.groupby(["A", "B"], observed=observed)["C"] - msg = "using SeriesGroupBy.sum" if operation == "agg" else "using np.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = getattr(grouped, operation)(sum) + result = getattr(grouped, operation)(sum) tm.assert_series_equal(result, expected) @@ -1709,10 +1685,7 @@ def test_categorical_transform(): categories=["Waiting", "OnTheWay", "Delivered"], ordered=True ) df["status"] = df["status"].astype(delivery_status_type) - msg = "using SeriesGroupBy.max" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - df["last_status"] = df.groupby("package_id")["status"].transform(max) + df["last_status"] = df.groupby("package_id")["status"].transform(max) result = df.copy() expected = DataFrame( @@ -1727,21 +1700,17 @@ def test_categorical_transform(): "Waiting", ], "last_status": [ - "Delivered", - "Delivered", - "Delivered", - "OnTheWay", - "OnTheWay", + "Waiting", + "Waiting", + "Waiting", + "Waiting", + "Waiting", "Waiting", ], } ) expected["status"] = expected["status"].astype(delivery_status_type) - - # .transform(max) should preserve ordered categoricals - expected["last_status"] = expected["last_status"].astype(delivery_status_type) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py index c2456790e4953..18465d00d17e2 100644 --- a/pandas/tests/groupby/test_raises.py +++ b/pandas/tests/groupby/test_raises.py @@ -86,7 +86,7 @@ def df_with_cat_col(): def _call_and_check(klass, msg, how, gb, groupby_func, args, warn_msg=""): warn_klass = None if warn_msg == "" else FutureWarning - with tm.assert_produces_warning(warn_klass, match=warn_msg): + with tm.assert_produces_warning(warn_klass, match=warn_msg, check_stacklevel=False): if klass is None: if how == "method": getattr(gb, groupby_func)(*args) @@ -219,15 +219,14 @@ def test_groupby_raises_string_np( np.sum: (None, ""), np.mean: ( TypeError, - re.escape("agg function failed [how->mean,dtype->object]"), + "Could not convert string .* to numeric", ), }[groupby_func_np] - - if groupby_series: - warn_msg = "using SeriesGroupBy.[sum|mean]" + if how == "transform" and groupby_func_np is np.sum and not groupby_series: + warn_msg = "The behavior of DataFrame.sum with axis=None is deprecated" else: - warn_msg = "using DataFrameGroupBy.[sum|mean]" - _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg=warn_msg) + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg) @pytest.mark.parametrize("how", ["method", "agg", "transform"]) @@ -328,15 +327,13 @@ def test_groupby_raises_datetime_np( gb = gb["d"] klass, msg = { - np.sum: (TypeError, "datetime64 type does not support sum operations"), + np.sum: ( + TypeError, + re.escape("datetime64[us] does not support reduction 'sum'"), + ), np.mean: (None, ""), }[groupby_func_np] - - if groupby_series: - warn_msg = "using SeriesGroupBy.[sum|mean]" - else: - warn_msg = "using DataFrameGroupBy.[sum|mean]" - _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg=warn_msg) + _call_and_check(klass, msg, how, gb, groupby_func_np, ()) @pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"]) @@ -528,18 +525,13 @@ def test_groupby_raises_category_np( gb = gb["d"] klass, msg = { - np.sum: (TypeError, "category type does not support sum operations"), + np.sum: (TypeError, "dtype category does not support reduction 'sum'"), np.mean: ( TypeError, - "category dtype does not support aggregation 'mean'", + "dtype category does not support reduction 'mean'", ), }[groupby_func_np] - - if groupby_series: - warn_msg = "using SeriesGroupBy.[sum|mean]" - else: - warn_msg = "using DataFrameGroupBy.[sum|mean]" - _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg=warn_msg) + _call_and_check(klass, msg, how, gb, groupby_func_np, ()) @pytest.mark.parametrize("how", ["method", "agg", "transform"]) diff --git a/pandas/tests/groupby/test_reductions.py b/pandas/tests/groupby/test_reductions.py index 1a32dcefed91a..e304a5ae467d8 100644 --- a/pandas/tests/groupby/test_reductions.py +++ b/pandas/tests/groupby/test_reductions.py @@ -36,20 +36,17 @@ def test_basic_aggregations(dtype): for k, v in grouped: assert len(v) == 3 - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - agged = grouped.aggregate(np.mean) + agged = grouped.aggregate(np.mean) assert agged[1] == 1 - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = grouped.agg(np.mean) + expected = grouped.agg(np.mean) tm.assert_series_equal(agged, expected) # shorthand tm.assert_series_equal(agged, grouped.mean()) result = grouped.sum() - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = grouped.agg(np.sum) + expected = grouped.agg(np.sum) + if dtype == "int32": + # NumPy's sum returns int64 + expected = expected.astype("int32") tm.assert_series_equal(result, expected) expected = grouped.apply(lambda x: x * x.sum()) @@ -58,15 +55,11 @@ def test_basic_aggregations(dtype): tm.assert_series_equal(transformed, expected) value_grouped = data.groupby(data) - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = value_grouped.aggregate(np.mean) + result = value_grouped.aggregate(np.mean) tm.assert_series_equal(result, agged, check_index_type=False) # complex agg - msg = "using SeriesGroupBy.[mean|std]" - with tm.assert_produces_warning(FutureWarning, match=msg): - agged = grouped.aggregate([np.mean, np.std]) + agged = grouped.aggregate([np.mean, np.std]) msg = r"nested renamer is not supported" with pytest.raises(pd.errors.SpecificationError, match=msg): @@ -450,15 +443,11 @@ def test_cython_median(): labels[::17] = np.nan result = df.groupby(labels).median() - msg = "using DataFrameGroupBy.median" - with tm.assert_produces_warning(FutureWarning, match=msg): - exp = df.groupby(labels).agg(np.nanmedian) + exp = df.groupby(labels).agg(np.nanmedian) tm.assert_frame_equal(result, exp) df = DataFrame(np.random.default_rng(2).standard_normal((1000, 5))) - msg = "using DataFrameGroupBy.median" - with tm.assert_produces_warning(FutureWarning, match=msg): - rs = df.groupby(labels).agg(np.median) + rs = df.groupby(labels).agg(np.median) xp = df.groupby(labels).median() tm.assert_frame_equal(rs, xp) @@ -953,15 +942,11 @@ def test_intercept_builtin_sum(): s = Series([1.0, 2.0, np.nan, 3.0]) grouped = s.groupby([0, 1, 2, 2]) - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = grouped.agg(builtins.sum) - msg = "using np.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result2 = grouped.apply(builtins.sum) - expected = grouped.sum() + # GH#53425 + result = grouped.agg(builtins.sum) + # GH#53425 + result2 = grouped.apply(builtins.sum) + expected = Series([1.0, 2.0, np.nan], index=np.array([0, 1, 2])) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) @@ -1096,10 +1081,8 @@ def test_ops_general(op, targop): labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) result = getattr(df.groupby(labels), op)() - warn = None if op in ("first", "last", "count", "sem") else FutureWarning - msg = f"using DataFrameGroupBy.{op}" - with tm.assert_produces_warning(warn, match=msg): - expected = df.groupby(labels).agg(targop) + kwargs = {"ddof": 1, "axis": 0} if op in ["std", "var"] else {} + expected = df.groupby(labels).agg(targop, **kwargs) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 1bb3539830900..db327cc689afe 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -78,9 +78,7 @@ def demean(arr): # GH 9700 df = DataFrame({"a": range(5, 10), "b": range(5)}) - msg = "using DataFrameGroupBy.max" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby("a").transform(max) + result = df.groupby("a").transform(max) expected = DataFrame({"b": range(5)}) tm.assert_frame_equal(result, expected) @@ -98,9 +96,7 @@ def test_transform_fast(): values = np.repeat(grp.mean().values, ensure_platform_int(grp.count().values)) expected = Series(values, index=df.index, name="val") - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = grp.transform(np.mean) + result = grp.transform(np.mean) tm.assert_series_equal(result, expected) result = grp.transform("mean") @@ -151,18 +147,14 @@ def test_transform_fast3(): def test_transform_broadcast(tsframe, ts): grouped = ts.groupby(lambda x: x.month) - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = grouped.transform(np.mean) + result = grouped.transform(np.mean) tm.assert_index_equal(result.index, ts.index) for _, gp in grouped: assert_fp_equal(result.reindex(gp.index), gp.mean()) grouped = tsframe.groupby(lambda x: x.month) - msg = "using DataFrameGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = grouped.transform(np.mean) + result = grouped.transform(np.mean) tm.assert_index_equal(result.index, tsframe.index) for _, gp in grouped: agged = gp.mean(axis=0) @@ -309,12 +301,8 @@ def test_transform_casting(): def test_transform_multiple(ts): grouped = ts.groupby([lambda x: x.year, lambda x: x.month]) - grouped.transform(lambda x: x * 2) - - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - grouped.transform(np.mean) + grouped.transform(np.mean) def test_dispatch_transform(tsframe): @@ -419,15 +407,11 @@ def test_transform_nuisance_raises(df): def test_transform_function_aliases(df): result = df.groupby("A").transform("mean", numeric_only=True) - msg = "using DataFrameGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = df.groupby("A")[["C", "D"]].transform(np.mean) + expected = df.groupby("A")[["C", "D"]].transform(np.mean) tm.assert_frame_equal(result, expected) result = df.groupby("A")["C"].transform("mean") - msg = "using SeriesGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = df.groupby("A")["C"].transform(np.mean) + expected = df.groupby("A")["C"].transform(np.mean) tm.assert_series_equal(result, expected) @@ -447,22 +431,19 @@ def test_series_fast_transform_date(): tm.assert_series_equal(result, expected) -def test_transform_length(): +@pytest.mark.parametrize("func", [lambda x: np.nansum(x), sum]) +def test_transform_length(func): # GH 9697 df = DataFrame({"col1": [1, 1, 2, 2], "col2": [1, 2, 3, np.nan]}) - expected = Series([3.0] * 4) - - def nsum(x): - return np.nansum(x) + if func is sum: + expected = Series([3.0, 3.0, np.nan, np.nan]) + else: + expected = Series([3.0] * 4) - msg = "using DataFrameGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - results = [ - df.groupby("col1").transform(sum)["col2"], - df.groupby("col1")["col2"].transform(sum), - df.groupby("col1").transform(nsum)["col2"], - df.groupby("col1")["col2"].transform(nsum), - ] + results = [ + df.groupby("col1").transform(func)["col2"], + df.groupby("col1")["col2"].transform(func), + ] for result in results: tm.assert_series_equal(result, expected, check_names=False) @@ -474,10 +455,7 @@ def test_transform_coercion(): df = DataFrame({"A": ["a", "a", "b", "b"], "B": [0, 1, 3, 4]}) g = df.groupby("A") - msg = "using DataFrameGroupBy.mean" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = g.transform(np.mean) - + expected = g.transform(np.mean) result = g.transform(lambda x: np.mean(x, axis=0)) tm.assert_frame_equal(result, expected) @@ -547,9 +525,7 @@ def test_groupby_transform_with_int(): def test_groupby_transform_with_nan_group(): # GH 9941 df = DataFrame({"a": range(10), "b": [1, 1, 2, 3, np.nan, 4, 4, 5, 5, 5]}) - msg = "using SeriesGroupBy.max" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby(df.b)["a"].transform(max) + result = df.groupby(df.b)["a"].transform(max) expected = Series([1.0, 1.0, 2.0, 3.0, np.nan, 6.0, 6.0, 9.0, 9.0, 9.0], name="a") tm.assert_series_equal(result, expected) @@ -1019,9 +995,7 @@ def test_any_all_np_func(func): exp = Series([True, np.nan, True], name="val") - msg = "using SeriesGroupBy.[any|all]" - with tm.assert_produces_warning(FutureWarning, match=msg): - res = df.groupby("key")["val"].transform(func) + res = df.groupby("key")["val"].transform(func) tm.assert_series_equal(res, exp) @@ -1051,10 +1025,7 @@ def test_groupby_transform_timezone_column(func): # GH 24198 ts = pd.to_datetime("now", utc=True).tz_convert("Asia/Singapore") result = DataFrame({"end_time": [ts], "id": [1]}) - warn = FutureWarning if not isinstance(func, str) else None - msg = "using SeriesGroupBy.[min|max]" - with tm.assert_produces_warning(warn, match=msg): - result["max_end_time"] = result.groupby("id").end_time.transform(func) + result["max_end_time"] = result.groupby("id").end_time.transform(func) expected = DataFrame([[ts, 1, ts]], columns=["end_time", "id", "max_end_time"]) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index c5ef0f39ece19..461b6bfc3b420 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1900,9 +1900,7 @@ def test_resample_apply_product(duplicates, unit): if duplicates: df.columns = ["A", "A"] - msg = "using DatetimeIndexResampler.prod" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.resample("QE").apply(np.prod) + result = df.resample("QE").apply(np.prod) expected = DataFrame( np.array([[0, 24], [60, 210], [336, 720], [990, 1716]], dtype=np.int64), index=DatetimeIndex( diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 465d287fd8eff..f3b9c909290a8 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -440,34 +440,30 @@ def cases(request): def test_agg_mixed_column_aggregation(cases, a_mean, a_std, b_mean, b_std, request): expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) - expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]]) - msg = "using SeriesGroupBy.[mean|std]" + expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "<lambda_0>"]]) # "date" is an index and a column, so get included in the agg if "df_mult" in request.node.callspec.id: date_mean = cases["date"].mean() date_std = cases["date"].std() expected = pd.concat([date_mean, date_std, expected], axis=1) expected.columns = pd.MultiIndex.from_product( - [["date", "A", "B"], ["mean", "std"]] + [["date", "A", "B"], ["mean", "<lambda_0>"]] ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = cases.aggregate([np.mean, np.std]) + result = cases.aggregate([np.mean, lambda x: np.std(x, ddof=1)]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "agg", [ - {"func": {"A": np.mean, "B": np.std}}, - {"A": ("A", np.mean), "B": ("B", np.std)}, - {"A": NamedAgg("A", np.mean), "B": NamedAgg("B", np.std)}, + {"func": {"A": np.mean, "B": lambda x: np.std(x, ddof=1)}}, + {"A": ("A", np.mean), "B": ("B", lambda x: np.std(x, ddof=1))}, + {"A": NamedAgg("A", np.mean), "B": NamedAgg("B", lambda x: np.std(x, ddof=1))}, ], ) def test_agg_both_mean_std_named_result(cases, a_mean, b_std, agg): - msg = "using SeriesGroupBy.[mean|std]" expected = pd.concat([a_mean, b_std], axis=1) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = cases.aggregate(**agg) + result = cases.aggregate(**agg) tm.assert_frame_equal(result, expected, check_like=True) @@ -523,11 +519,9 @@ def test_agg_dict_of_lists(cases, a_mean, a_std, b_mean, b_std): ) def test_agg_with_lambda(cases, agg): # passed lambda - msg = "using SeriesGroupBy.sum" rcustom = cases["B"].apply(lambda x: np.std(x, ddof=1)) expected = pd.concat([cases["A"].sum(), rcustom], axis=1) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = cases.agg(**agg) + result = cases.agg(**agg) tm.assert_frame_equal(result, expected, check_like=True) diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index c5e202f36659b..11ad9240527d5 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -57,12 +57,8 @@ def test_count(test_series): def test_numpy_reduction(test_series): result = test_series.resample("YE", closed="right").prod() - - msg = "using SeriesGroupBy.prod" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = test_series.groupby(lambda x: x.year).agg(np.prod) + expected = test_series.groupby(lambda x: x.year).agg(np.prod) expected.index = result.index - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 2a538d34d8b2c..c4af63fe5cc81 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -452,11 +452,9 @@ def test_crosstab_normalize_arrays(self): index=Index([1, 2, "All"], name="a", dtype="object"), columns=Index([3, 4, "All"], name="b", dtype="object"), ) - msg = "using DataFrameGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - test_case = crosstab( - df.a, df.b, df.c, aggfunc=np.sum, normalize="all", margins=True - ) + test_case = crosstab( + df.a, df.b, df.c, aggfunc=np.sum, normalize="all", margins=True + ) tm.assert_frame_equal(test_case, norm_sum) def test_crosstab_with_empties(self): @@ -655,16 +653,14 @@ def test_crosstab_normalize_multiple_columns(self): } ) - msg = "using DataFrameGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = crosstab( - [df.A, df.B], - df.C, - values=df.D, - aggfunc=np.sum, - normalize=True, - margins=True, - ) + result = crosstab( + [df.A, df.B], + df.C, + values=df.D, + aggfunc=np.sum, + normalize=True, + margins=True, + ) expected = DataFrame( np.array([0] * 29 + [1], dtype=float).reshape(10, 3), columns=Index(["bar", "foo", "All"], name="C"), diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 916fe6fdb64b1..99250dc929997 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -11,6 +11,8 @@ from pandas._config import using_pyarrow_string_dtype +from pandas.compat.numpy import np_version_gte1p25 + import pandas as pd from pandas import ( Categorical, @@ -2059,10 +2061,10 @@ def test_pivot_string_as_func(self): [ ("sum", np.sum), ("mean", np.mean), - ("std", np.std), + ("min", np.min), (["sum", "mean"], [np.sum, np.mean]), - (["sum", "std"], [np.sum, np.std]), - (["std", "mean"], [np.std, np.mean]), + (["sum", "min"], [np.sum, np.min]), + (["max", "mean"], [np.max, np.mean]), ], ) def test_pivot_string_func_vs_func(self, f, f_numpy, data): @@ -2070,10 +2072,14 @@ def test_pivot_string_func_vs_func(self, f, f_numpy, data): # for consistency purposes data = data.drop(columns="C") result = pivot_table(data, index="A", columns="B", aggfunc=f) - ops = "|".join(f) if isinstance(f, list) else f - msg = f"using DataFrameGroupBy.[{ops}]" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = pivot_table(data, index="A", columns="B", aggfunc=f_numpy) + expected = pivot_table(data, index="A", columns="B", aggfunc=f_numpy) + + if not np_version_gte1p25 and isinstance(f_numpy, list): + # Prior to 1.25, np.min/np.max would come through as amin and amax + mapper = {"amin": "min", "amax": "max", "sum": "sum", "mean": "mean"} + expected.columns = expected.columns.map( + lambda x: (mapper[x[0]], x[1], x[2]) + ) tm.assert_frame_equal(result, expected) @pytest.mark.slow diff --git a/pandas/tests/window/test_api.py b/pandas/tests/window/test_api.py index b4d555203212e..5ba08ac13fcee 100644 --- a/pandas/tests/window/test_api.py +++ b/pandas/tests/window/test_api.py @@ -87,14 +87,12 @@ def test_agg(step): b_mean = r["B"].mean() b_std = r["B"].std() - with tm.assert_produces_warning(FutureWarning, match="using Rolling.[mean|std]"): - result = r.aggregate([np.mean, np.std]) + result = r.aggregate([np.mean, lambda x: np.std(x, ddof=1)]) expected = concat([a_mean, a_std, b_mean, b_std], axis=1) - expected.columns = MultiIndex.from_product([["A", "B"], ["mean", "std"]]) + expected.columns = MultiIndex.from_product([["A", "B"], ["mean", "<lambda>"]]) tm.assert_frame_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, match="using Rolling.[mean|std]"): - result = r.aggregate({"A": np.mean, "B": np.std}) + result = r.aggregate({"A": np.mean, "B": lambda x: np.std(x, ddof=1)}) expected = concat([a_mean, b_std], axis=1) tm.assert_frame_equal(result, expected, check_like=True) @@ -134,8 +132,7 @@ def test_agg_apply(raw): r = df.rolling(window=3) a_sum = r["A"].sum() - with tm.assert_produces_warning(FutureWarning, match="using Rolling.[sum|std]"): - result = r.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)}) + result = r.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)}) rcustom = r["B"].apply(lambda x: np.std(x, ddof=1), raw=raw) expected = concat([a_sum, rcustom], axis=1) tm.assert_frame_equal(result, expected, check_like=True) @@ -145,18 +142,15 @@ def test_agg_consistency(step): df = DataFrame({"A": range(5), "B": range(0, 10, 2)}) r = df.rolling(window=3, step=step) - with tm.assert_produces_warning(FutureWarning, match="using Rolling.[sum|mean]"): - result = r.agg([np.sum, np.mean]).columns + result = r.agg([np.sum, np.mean]).columns expected = MultiIndex.from_product([list("AB"), ["sum", "mean"]]) tm.assert_index_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, match="using Rolling.[sum|mean]"): - result = r["A"].agg([np.sum, np.mean]).columns + result = r["A"].agg([np.sum, np.mean]).columns expected = Index(["sum", "mean"]) tm.assert_index_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, match="using Rolling.[sum|mean]"): - result = r.agg({"A": [np.sum, np.mean]}).columns + result = r.agg({"A": [np.sum, np.mean]}).columns expected = MultiIndex.from_tuples([("A", "sum"), ("A", "mean")]) tm.assert_index_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Ref: #53974
https://api.github.com/repos/pandas-dev/pandas/pulls/57444
2024-02-15T22:39:46Z
2024-02-27T22:47:50Z
2024-02-27T22:47:50Z
2024-02-27T22:49:06Z
adding pow example for dataframe #57419
diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py index bd2e532536d84..5e97d1b67d826 100644 --- a/pandas/core/ops/docstrings.py +++ b/pandas/core/ops/docstrings.py @@ -623,6 +623,15 @@ def make_flex_doc(op_name: str, typ: str) -> str: B square 0.0 0.0 pentagon 0.0 0.0 hexagon 0.0 0.0 + +>>> df_pow = pd.DataFrame({{'A': [2, 3, 4, 5], +... 'B': [6, 7, 8, 9]}}) +>>> df_pow.pow(2) + A B +0 4 36 +1 9 49 +2 16 64 +3 25 81 """ _flex_comp_doc_FRAME = """
Added example for DataFrame.pow() - [x] closes #57419 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/57442
2024-02-15T20:42:22Z
2024-02-19T23:38:30Z
2024-02-19T23:38:30Z
2024-02-20T00:34:31Z
BUG: read_json returning Index instead of RangeIndex
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index ab62a7c7598d5..d81032fafa730 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -18,6 +18,7 @@ Fixed regressions - Fixed regression in :func:`concat` changing long-standing behavior that always sorted the non-concatenation axis when the axis was a :class:`DatetimeIndex` (:issue:`57006`) - Fixed regression in :func:`merge_ordered` raising ``TypeError`` for ``fill_method="ffill"`` and ``how="left"`` (:issue:`57010`) - Fixed regression in :func:`pandas.testing.assert_series_equal` defaulting to ``check_exact=True`` when checking the :class:`Index` (:issue:`57067`) +- Fixed regression in :func:`read_json` where an :class:`Index` would be returned instead of a :class:`RangeIndex` (:issue:`57429`) - Fixed regression in :func:`wide_to_long` raising an ``AttributeError`` for string columns (:issue:`57066`) - Fixed regression in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, :meth:`.SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, :meth:`.SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 3643cac04e0ca..0e1426d31f0ee 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -1211,6 +1211,7 @@ def _try_convert_data( if result: return new_data, True + converted = False if self.dtype_backend is not lib.no_default and not is_axis: # Fall through for conversion later on return data, True @@ -1218,16 +1219,17 @@ def _try_convert_data( # try float try: data = data.astype("float64") + converted = True except (TypeError, ValueError): pass - if data.dtype.kind == "f": - if data.dtype != "float64": - # coerce floats to 64 - try: - data = data.astype("float64") - except (TypeError, ValueError): - pass + if data.dtype.kind == "f" and data.dtype != "float64": + # coerce floats to 64 + try: + data = data.astype("float64") + converted = True + except (TypeError, ValueError): + pass # don't coerce 0-len data if len(data) and data.dtype in ("float", "object"): @@ -1236,14 +1238,15 @@ def _try_convert_data( new_data = data.astype("int64") if (new_data == data).all(): data = new_data + converted = True except (TypeError, ValueError, OverflowError): pass - # coerce ints to 64 - if data.dtype == "int": - # coerce floats to 64 + if data.dtype == "int" and data.dtype != "int64": + # coerce ints to 64 try: data = data.astype("int64") + converted = True except (TypeError, ValueError): pass @@ -1252,7 +1255,7 @@ def _try_convert_data( if self.orient == "split": return data, False - return data, True + return data, converted @final def _try_convert_to_date(self, data: Series) -> tuple[Series, bool]: diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 28b5fa57d4109..db120588b234c 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -21,6 +21,7 @@ DataFrame, DatetimeIndex, Index, + RangeIndex, Series, Timestamp, date_range, @@ -467,12 +468,12 @@ def test_frame_mixedtype_orient(self): # GH10289 left = read_json(inp, orient=orient, convert_axes=False) tm.assert_frame_equal(left, right) - right.index = pd.RangeIndex(len(df)) + right.index = RangeIndex(len(df)) inp = StringIO(df.to_json(orient="records")) left = read_json(inp, orient="records", convert_axes=False) tm.assert_frame_equal(left, right) - right.columns = pd.RangeIndex(df.shape[1]) + right.columns = RangeIndex(df.shape[1]) inp = StringIO(df.to_json(orient="values")) left = read_json(inp, orient="values", convert_axes=False) tm.assert_frame_equal(left, right) @@ -2139,3 +2140,14 @@ def test_to_json_ea_null(): {"a":null,"b":null} """ assert result == expected + + +def test_read_json_lines_rangeindex(): + # GH 57429 + data = """ +{"a": 1, "b": 2} +{"a": 3, "b": 4} +""" + result = read_json(StringIO(data), lines=True).index + expected = RangeIndex(2) + tm.assert_index_equal(result, expected, exact=True)
- [x] closes #57429 (Replace xxxx with the GitHub issue number) `_convert_axes` and `_try_convert_data` could both probably use a cleanup to align with pandas standard inference, but this is a minimal change for 2.2.1
https://api.github.com/repos/pandas-dev/pandas/pulls/57439
2024-02-15T19:48:20Z
2024-02-21T19:41:04Z
2024-02-21T19:41:04Z
2024-02-21T19:41:06Z
DOC: fix SA05 errors in docstrings for `pandas.plotting.bootstrap_plot` and `pandas.plotting.radviz`
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 5eae5c6b60c17..35383ca526269 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -1871,9 +1871,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.groupby.SeriesGroupBy.first\ pandas.core.groupby.SeriesGroupBy.last\ pandas.core.window.expanding.Expanding.aggregate\ - pandas.core.window.rolling.Rolling.aggregate\ - pandas.plotting.bootstrap_plot\ - pandas.plotting.radviz # There should be no backslash in the final line, please keep this comment in the last ignored function + pandas.core.window.rolling.Rolling.aggregate # There should be no backslash in the final line, please keep this comment in the last ignored function RET=$(($RET + $?)) ; echo $MSG "DONE" fi diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index eb2d12e588b8f..16192fda07bad 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -278,10 +278,11 @@ def radviz( Returns ------- :class:`matplotlib.axes.Axes` + The Axes object from Matplotlib. See Also -------- - pandas.plotting.andrews_curves : Plot clustering visualization. + plotting.andrews_curves : Plot clustering visualization. Examples -------- @@ -431,8 +432,8 @@ def bootstrap_plot( See Also -------- - pandas.DataFrame.plot : Basic plotting for DataFrame objects. - pandas.Series.plot : Basic plotting for Series objects. + DataFrame.plot : Basic plotting for DataFrame objects. + Series.plot : Basic plotting for Series objects. Examples --------
All SA05 Errors resolved in the following cases: 1. scripts/validate_docstrings.py --format=actions --errors=SA05 pandas.plotting.bootstrap_plot 2. scripts/validate_docstrings.py --format=actions --errors=SA05 pandas.plotting.radviz 3. try to fix a `RT03 Return value has no description` in pandas.plotting.radviz - [x] xref [DOC: fix SA05 errors in docstrings  #57392](https://github.com/pandas-dev/pandas/issues/57392) - [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.
https://api.github.com/repos/pandas-dev/pandas/pulls/57434
2024-02-15T09:09:44Z
2024-02-15T17:08:32Z
2024-02-15T17:08:32Z
2024-02-16T07:46:38Z
TYP: misc return types
diff --git a/pandas/_typing.py b/pandas/_typing.py index 9465631e9fe20..85a69f38b3f67 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -118,6 +118,7 @@ Concatenate: Any = None HashableT = TypeVar("HashableT", bound=Hashable) +HashableT2 = TypeVar("HashableT2", bound=Hashable) MutableMappingT = TypeVar("MutableMappingT", bound=MutableMapping) # array-like diff --git a/pandas/core/base.py b/pandas/core/base.py index b9a57de073595..a3a86cb9ce410 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -8,7 +8,6 @@ from typing import ( TYPE_CHECKING, Any, - Callable, Generic, Literal, cast, @@ -105,7 +104,7 @@ class PandasObject(DirNamesMixin): _cache: dict[str, Any] @property - def _constructor(self) -> Callable[..., Self]: + def _constructor(self) -> type[Self]: """ Class constructor (for this class it's just `__class__`). """ @@ -1356,7 +1355,7 @@ def searchsorted( sorter=sorter, ) - def drop_duplicates(self, *, keep: DropKeep = "first"): + def drop_duplicates(self, *, keep: DropKeep = "first") -> Self: duplicated = self._duplicated(keep=keep) # error: Value of type "IndexOpsMixin" is not indexable return self[~duplicated] # type: ignore[index] diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 660979540691e..6142e67ec1316 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -217,6 +217,8 @@ FormattersType, Frequency, FromDictOrient, + HashableT, + HashableT2, IgnoreRaise, IndexKeyFunc, IndexLabel, @@ -239,6 +241,7 @@ SortKind, StorageOptions, Suffixes, + T, ToStataByteorder, ToTimestampHow, UpdateJoin, @@ -643,10 +646,10 @@ class DataFrame(NDFrame, OpsMixin): __pandas_priority__ = 4000 @property - def _constructor(self) -> Callable[..., DataFrame]: + def _constructor(self) -> type[DataFrame]: return DataFrame - def _constructor_from_mgr(self, mgr, axes): + def _constructor_from_mgr(self, mgr, axes) -> DataFrame: if self._constructor is DataFrame: # we are pandas.DataFrame (or a subclass that doesn't override _constructor) return DataFrame._from_mgr(mgr, axes=axes) @@ -659,7 +662,7 @@ def _constructor_from_mgr(self, mgr, axes): def _sliced_from_mgr(self, mgr, axes) -> Series: return Series._from_mgr(mgr, axes) - def _constructor_sliced_from_mgr(self, mgr, axes): + def _constructor_sliced_from_mgr(self, mgr, axes) -> Series: if self._constructor_sliced is Series: ser = self._sliced_from_mgr(mgr, axes) ser._name = None # caller is responsible for setting real name @@ -1353,7 +1356,7 @@ def _get_values_for_csv( decimal: str, na_rep: str, quoting, # int csv.QUOTE_FOO from stdlib - ) -> Self: + ) -> DataFrame: # helper used by to_csv mgr = self._mgr.get_values_for_csv( float_format=float_format, @@ -1831,7 +1834,7 @@ def from_dict( a b 1 3 c 2 4 """ - index = None + index: list | Index | None = None orient = orient.lower() # type: ignore[assignment] if orient == "index": if len(data) > 0: @@ -1857,7 +1860,7 @@ def from_dict( else: realdata = data["data"] - def create_index(indexlist, namelist): + def create_index(indexlist, namelist) -> Index: index: Index if len(namelist) > 1: index = MultiIndex.from_tuples(indexlist, names=namelist) @@ -2700,6 +2703,42 @@ def to_feather(self, path: FilePath | WriteBuffer[bytes], **kwargs) -> None: to_feather(self, path, **kwargs) + @overload + def to_markdown( + self, + buf: None = ..., + *, + mode: str = ..., + index: bool = ..., + storage_options: StorageOptions | None = ..., + **kwargs, + ) -> str: + ... + + @overload + def to_markdown( + self, + buf: FilePath | WriteBuffer[str], + *, + mode: str = ..., + index: bool = ..., + storage_options: StorageOptions | None = ..., + **kwargs, + ) -> None: + ... + + @overload + def to_markdown( + self, + buf: FilePath | WriteBuffer[str] | None, + *, + mode: str = ..., + index: bool = ..., + storage_options: StorageOptions | None = ..., + **kwargs, + ) -> str | None: + ... + @doc( Series.to_markdown, klass=_shared_doc_kwargs["klass"], @@ -2881,6 +2920,39 @@ def to_parquet( **kwargs, ) + @overload + def to_orc( + self, + path: None = ..., + *, + engine: Literal["pyarrow"] = ..., + index: bool | None = ..., + engine_kwargs: dict[str, Any] | None = ..., + ) -> bytes: + ... + + @overload + def to_orc( + self, + path: FilePath | WriteBuffer[bytes], + *, + engine: Literal["pyarrow"] = ..., + index: bool | None = ..., + engine_kwargs: dict[str, Any] | None = ..., + ) -> None: + ... + + @overload + def to_orc( + self, + path: FilePath | WriteBuffer[bytes] | None, + *, + engine: Literal["pyarrow"] = ..., + index: bool | None = ..., + engine_kwargs: dict[str, Any] | None = ..., + ) -> bytes | None: + ... + def to_orc( self, path: FilePath | WriteBuffer[bytes] | None = None, @@ -4027,7 +4099,7 @@ def _setitem_slice(self, key: slice, value) -> None: # backwards-compat, xref GH#31469 self.iloc[key] = value - def _setitem_array(self, key, value): + def _setitem_array(self, key, value) -> None: # also raises Exception if object array with NA values if com.is_bool_indexer(key): # bool indexer is indexing along rows @@ -4061,7 +4133,7 @@ def _setitem_array(self, key, value): elif np.ndim(value) > 1: # list of lists value = DataFrame(value).values - return self._setitem_array(key, value) + self._setitem_array(key, value) else: self._iset_not_inplace(key, value) @@ -4595,7 +4667,7 @@ def eval(self, expr: str, *, inplace: bool = False, **kwargs) -> Any | None: return _eval(expr, inplace=inplace, **kwargs) - def select_dtypes(self, include=None, exclude=None) -> Self: + def select_dtypes(self, include=None, exclude=None) -> DataFrame: """ Return a subset of the DataFrame's columns based on the column dtypes. @@ -5474,9 +5546,21 @@ def pop(self, item: Hashable) -> Series: """ return super().pop(item=item) + @overload + def _replace_columnwise( + self, mapping: dict[Hashable, tuple[Any, Any]], inplace: Literal[True], regex + ) -> None: + ... + + @overload + def _replace_columnwise( + self, mapping: dict[Hashable, tuple[Any, Any]], inplace: Literal[False], regex + ) -> Self: + ... + def _replace_columnwise( self, mapping: dict[Hashable, tuple[Any, Any]], inplace: bool, regex - ): + ) -> Self | None: """ Dispatch to Series.replace column-wise. @@ -5505,7 +5589,7 @@ def _replace_columnwise( res._iset_item(i, newobj, inplace=inplace) if inplace: - return + return None return res.__finalize__(self) @doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"]) @@ -11815,19 +11899,19 @@ def kurt( product = prod @doc(make_doc("cummin", ndim=2)) - def cummin(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cummin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cummin(self, axis, skipna, *args, **kwargs) @doc(make_doc("cummax", ndim=2)) - def cummax(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cummax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cummax(self, axis, skipna, *args, **kwargs) @doc(make_doc("cumsum", ndim=2)) - def cumsum(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cumsum(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) @doc(make_doc("cumprod", 2)) - def cumprod(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cumprod(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cumprod(self, axis, skipna, *args, **kwargs) def nunique(self, axis: Axis = 0, dropna: bool = True) -> Series: @@ -12710,8 +12794,12 @@ def values(self) -> np.ndarray: return self._mgr.as_array() -def _from_nested_dict(data) -> collections.defaultdict: - new_data: collections.defaultdict = collections.defaultdict(dict) +def _from_nested_dict( + data: Mapping[HashableT, Mapping[HashableT2, T]], +) -> collections.defaultdict[HashableT2, dict[HashableT, T]]: + new_data: collections.defaultdict[ + HashableT2, dict[HashableT, T] + ] = collections.defaultdict(dict) for index, s in data.items(): for col, v in s.items(): new_data[col][index] = v diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 93e4468f91edd..149fbf7feb0dd 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -478,8 +478,9 @@ def _validate_dtype(cls, dtype) -> DtypeObj | None: # ---------------------------------------------------------------------- # Construction + # error: Signature of "_constructor" incompatible with supertype "PandasObject" @property - def _constructor(self) -> Callable[..., Self]: + def _constructor(self) -> Callable[..., Self]: # type: ignore[override] """ Used when a manipulation result has the same dimensions as the original. @@ -495,7 +496,9 @@ def _constructor(self) -> Callable[..., Self]: _AXIS_LEN: int @final - def _construct_axes_dict(self, axes: Sequence[Axis] | None = None, **kwargs): + def _construct_axes_dict( + self, axes: Sequence[Axis] | None = None, **kwargs: AxisInt + ) -> dict: """Return an axes dictionary for myself.""" d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} # error: Argument 1 to "update" of "MutableMapping" has incompatible type @@ -719,14 +722,26 @@ def set_axis( """ return self._set_axis_nocheck(labels, axis, inplace=False) + @overload + def _set_axis_nocheck(self, labels, axis: Axis, inplace: Literal[False]) -> Self: + ... + + @overload + def _set_axis_nocheck(self, labels, axis: Axis, inplace: Literal[True]) -> None: + ... + + @overload + def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool) -> Self | None: + ... + @final - def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool): + def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool) -> Self | None: if inplace: setattr(self, self._get_axis_name(axis), labels) - else: - obj = self.copy(deep=False) - setattr(obj, obj._get_axis_name(axis), labels) - return obj + return None + obj = self.copy(deep=False) + setattr(obj, obj._get_axis_name(axis), labels) + return obj @final def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None: @@ -926,6 +941,51 @@ def squeeze(self, axis: Axis | None = None): # ---------------------------------------------------------------------- # Rename + @overload + def _rename( + self, + mapper: Renamer | None = ..., + *, + index: Renamer | None = ..., + columns: Renamer | None = ..., + axis: Axis | None = ..., + copy: bool | None = ..., + inplace: Literal[False] = ..., + level: Level | None = ..., + errors: str = ..., + ) -> Self: + ... + + @overload + def _rename( + self, + mapper: Renamer | None = ..., + *, + index: Renamer | None = ..., + columns: Renamer | None = ..., + axis: Axis | None = ..., + copy: bool | None = ..., + inplace: Literal[True], + level: Level | None = ..., + errors: str = ..., + ) -> None: + ... + + @overload + def _rename( + self, + mapper: Renamer | None = ..., + *, + index: Renamer | None = ..., + columns: Renamer | None = ..., + axis: Axis | None = ..., + copy: bool | None = ..., + inplace: bool, + level: Level | None = ..., + errors: str = ..., + ) -> Self | None: + ... + @final def _rename( self, @@ -1203,8 +1263,24 @@ class name return result return None + @overload + def _set_axis_name( + self, name, axis: Axis = ..., *, inplace: Literal[False] = ... + ) -> Self: + ... + + @overload + def _set_axis_name(self, name, axis: Axis = ..., *, inplace: Literal[True]) -> None: + ... + + @overload + def _set_axis_name(self, name, axis: Axis = ..., *, inplace: bool) -> Self | None: + ... + @final - def _set_axis_name(self, name, axis: Axis = 0, inplace: bool = False): + def _set_axis_name( + self, name, axis: Axis = 0, *, inplace: bool = False + ) -> Self | None: """ Set the name(s) of the axis. @@ -1266,6 +1342,7 @@ def _set_axis_name(self, name, axis: Axis = 0, inplace: bool = False): if not inplace: return renamed + return None # ---------------------------------------------------------------------- # Comparison Methods @@ -4542,12 +4619,10 @@ def add_prefix(self, prefix: str, axis: Axis | None = None) -> Self: mapper = {axis_name: f} - # error: Incompatible return value type (got "Optional[Self]", - # expected "Self") - # error: Argument 1 to "rename" of "NDFrame" has incompatible type - # "**Dict[str, partial[str]]"; expected "Union[str, int, None]" # error: Keywords must be strings - return self._rename(**mapper) # type: ignore[return-value, arg-type, misc] + # error: No overload variant of "_rename" of "NDFrame" matches + # argument type "dict[Literal['index', 'columns'], Callable[[Any], str]]" + return self._rename(**mapper) # type: ignore[call-overload, misc] @final def add_suffix(self, suffix: str, axis: Axis | None = None) -> Self: @@ -4615,12 +4690,10 @@ def add_suffix(self, suffix: str, axis: Axis | None = None) -> Self: axis_name = self._get_axis_name(axis) mapper = {axis_name: f} - # error: Incompatible return value type (got "Optional[Self]", - # expected "Self") - # error: Argument 1 to "rename" of "NDFrame" has incompatible type - # "**Dict[str, partial[str]]"; expected "Union[str, int, None]" # error: Keywords must be strings - return self._rename(**mapper) # type: ignore[return-value, arg-type, misc] + # error: No overload variant of "_rename" of "NDFrame" matches argument + # type "dict[Literal['index', 'columns'], Callable[[Any], str]]" + return self._rename(**mapper) # type: ignore[call-overload, misc] @overload def sort_values( @@ -9241,7 +9314,7 @@ def ranker(data): @doc(_shared_docs["compare"], klass=_shared_doc_kwargs["klass"]) def compare( self, - other, + other: Self, align_axis: Axis = 1, keep_shape: bool = False, keep_equal: bool = False, @@ -9253,7 +9326,8 @@ def compare( f"can only compare '{cls_self}' (not '{cls_other}') with '{cls_self}'" ) - mask = ~((self == other) | (self.isna() & other.isna())) + # error: Unsupported left operand type for & ("Self") + mask = ~((self == other) | (self.isna() & other.isna())) # type: ignore[operator] mask.fillna(True, inplace=True) if not keep_equal: @@ -9596,15 +9670,52 @@ def _align_series( return left, right, join_index + @overload + def _where( + self, + cond, + other=..., + *, + inplace: Literal[False] = ..., + axis: Axis | None = ..., + level=..., + ) -> Self: + ... + + @overload + def _where( + self, + cond, + other=..., + *, + inplace: Literal[True], + axis: Axis | None = ..., + level=..., + ) -> None: + ... + + @overload + def _where( + self, + cond, + other=..., + *, + inplace: bool, + axis: Axis | None = ..., + level=..., + ) -> Self | None: + ... + @final def _where( self, cond, other=lib.no_default, + *, inplace: bool = False, axis: Axis | None = None, level=None, - ): + ) -> Self | None: """ Equivalent to public method `where`, except that `other` is not applied as a function even if callable. Used in __setitem__. @@ -9950,7 +10061,7 @@ def where( ) other = common.apply_if_callable(other, self) - return self._where(cond, other, inplace, axis, level) + return self._where(cond, other, inplace=inplace, axis=axis, level=level) @overload def mask( @@ -11263,20 +11374,20 @@ def block_accum_func(blk_values): self, method=name ) - def cummax(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cummax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return self._accum_func( "cummax", np.maximum.accumulate, axis, skipna, *args, **kwargs ) - def cummin(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cummin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return self._accum_func( "cummin", np.minimum.accumulate, axis, skipna, *args, **kwargs ) - def cumsum(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cumsum(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return self._accum_func("cumsum", np.cumsum, axis, skipna, *args, **kwargs) - def cumprod(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cumprod(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return self._accum_func("cumprod", np.cumprod, axis, skipna, *args, **kwargs) @final @@ -11674,7 +11785,7 @@ def __ixor__(self, other) -> Self: # Misc methods @final - def _find_valid_index(self, *, how: str) -> Hashable | None: + def _find_valid_index(self, *, how: str) -> Hashable: """ Retrieves the index of the first valid value. @@ -11695,7 +11806,7 @@ def _find_valid_index(self, *, how: str) -> Hashable | None: @final @doc(position="first", klass=_shared_doc_kwargs["klass"]) - def first_valid_index(self) -> Hashable | None: + def first_valid_index(self) -> Hashable: """ Return index for {position} non-NA value or None, if no non-NA value is found. @@ -11771,7 +11882,7 @@ def first_valid_index(self) -> Hashable | None: @final @doc(first_valid_index, position="last", klass=_shared_doc_kwargs["klass"]) - def last_valid_index(self) -> Hashable | None: + def last_valid_index(self) -> Hashable: return self._find_valid_index(how="last") diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index f0eb7f44bf34e..36edf6116609b 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -1,9 +1,5 @@ from __future__ import annotations -from collections.abc import ( - Hashable, - Sequence, -) from typing import ( TYPE_CHECKING, Callable, @@ -44,11 +40,14 @@ from pandas.core.series import Series if TYPE_CHECKING: + from collections.abc import Hashable + from pandas._typing import ( AggFuncType, AggFuncTypeBase, AggFuncTypeDict, IndexLabel, + SequenceNotStr, ) from pandas import DataFrame @@ -546,9 +545,10 @@ def pivot( if is_list_like(values) and not isinstance(values, tuple): # Exclude tuple because it is seen as a single column name - values = cast(Sequence[Hashable], values) indexed = data._constructor( - data[values]._values, index=multiindex, columns=values + data[values]._values, + index=multiindex, + columns=cast("SequenceNotStr", values), ) else: indexed = data._constructor_sliced(data[values]._values, index=multiindex) diff --git a/pandas/core/series.py b/pandas/core/series.py index 1672c29f15763..eb5b545092307 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -571,7 +571,7 @@ def _init_dict( # ---------------------------------------------------------------------- @property - def _constructor(self) -> Callable[..., Series]: + def _constructor(self) -> type[Series]: return Series def _constructor_from_mgr(self, mgr, axes): @@ -5135,8 +5135,28 @@ def info( show_counts=show_counts, ) + @overload + def _replace_single( + self, to_replace, method: str, inplace: Literal[False], limit + ) -> Self: + ... + + @overload + def _replace_single( + self, to_replace, method: str, inplace: Literal[True], limit + ) -> None: + ... + + @overload + def _replace_single( + self, to_replace, method: str, inplace: bool, limit + ) -> Self | None: + ... + # TODO(3.0): this can be removed once GH#33302 deprecation is enforced - def _replace_single(self, to_replace, method: str, inplace: bool, limit): + def _replace_single( + self, to_replace, method: str, inplace: bool, limit + ) -> Self | None: """ Replaces values in a Series using the fill method specified when no replacement value is given in the replace method @@ -5155,7 +5175,7 @@ def _replace_single(self, to_replace, method: str, inplace: bool, limit): fill_f(values, limit=limit, mask=mask) if inplace: - return + return None return result def memory_usage(self, index: bool = True, deep: bool = False) -> int: @@ -6396,17 +6416,17 @@ def kurt( product = prod @doc(make_doc("cummin", ndim=1)) - def cummin(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cummin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cummin(self, axis, skipna, *args, **kwargs) @doc(make_doc("cummax", ndim=1)) - def cummax(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cummax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cummax(self, axis, skipna, *args, **kwargs) @doc(make_doc("cumsum", ndim=1)) - def cumsum(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cumsum(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) @doc(make_doc("cumprod", 1)) - def cumprod(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + def cumprod(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: return NDFrame.cumprod(self, axis, skipna, *args, **kwargs)
null
https://api.github.com/repos/pandas-dev/pandas/pulls/57430
2024-02-15T03:05:12Z
2024-02-16T17:23:10Z
2024-02-16T17:23:10Z
2024-04-07T10:59:20Z
CLN: Remove inf_as_na
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index ae135fd41d977..18e970f9e89e2 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -139,6 +139,7 @@ Removal of prior version deprecations/changes - Removed ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`) - Removed deprecated argument ``obj`` in :meth:`.DataFrameGroupBy.get_group` and :meth:`.SeriesGroupBy.get_group` (:issue:`53545`) - Removed deprecated behavior of :meth:`Series.agg` using :meth:`Series.apply` (:issue:`53325`) +- Removed option ``mode.use_inf_as_na``, convert inf entries to ``NaN`` before instead (:issue:`51684`) - Removed support for :class:`DataFrame` in :meth:`DataFrame.from_records`(:issue:`51697`) - Removed support for ``errors="ignore"`` in :func:`to_datetime`, :func:`to_timedelta` and :func:`to_numeric` (:issue:`55734`) - Removed support for ``slice`` in :meth:`DataFrame.take` (:issue:`51539`) diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd index 5920649519442..899d729690451 100644 --- a/pandas/_libs/missing.pxd +++ b/pandas/_libs/missing.pxd @@ -7,8 +7,8 @@ from numpy cimport ( cpdef bint is_matching_na(object left, object right, bint nan_matches_none=*) cpdef bint check_na_tuples_nonequal(object left, object right) -cpdef bint checknull(object val, bint inf_as_na=*) -cpdef ndarray[uint8_t] isnaobj(ndarray arr, bint inf_as_na=*) +cpdef bint checknull(object val) +cpdef ndarray[uint8_t] isnaobj(ndarray arr) cdef bint is_null_datetime64(v) cdef bint is_null_timedelta64(v) diff --git a/pandas/_libs/missing.pyi b/pandas/_libs/missing.pyi index 282dcee3ed6cf..6bf30a03cef32 100644 --- a/pandas/_libs/missing.pyi +++ b/pandas/_libs/missing.pyi @@ -11,6 +11,6 @@ def is_matching_na( ) -> bool: ... def isposinf_scalar(val: object) -> bool: ... def isneginf_scalar(val: object) -> bool: ... -def checknull(val: object, inf_as_na: bool = ...) -> bool: ... -def isnaobj(arr: np.ndarray, inf_as_na: bool = ...) -> npt.NDArray[np.bool_]: ... +def checknull(val: object) -> bool: ... +def isnaobj(arr: np.ndarray) -> npt.NDArray[np.bool_]: ... def is_numeric_na(values: np.ndarray) -> npt.NDArray[np.bool_]: ... diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index 0fd1c2b21d5cd..2f44128cda822 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -137,7 +137,7 @@ cpdef bint is_matching_na(object left, object right, bint nan_matches_none=False return False -cpdef bint checknull(object val, bint inf_as_na=False): +cpdef bint checknull(object val): """ Return boolean describing of the input is NA-like, defined here as any of: @@ -152,8 +152,6 @@ cpdef bint checknull(object val, bint inf_as_na=False): Parameters ---------- val : object - inf_as_na : bool, default False - Whether to treat INF and -INF as NA values. Returns ------- @@ -164,8 +162,6 @@ cpdef bint checknull(object val, bint inf_as_na=False): elif util.is_float_object(val) or util.is_complex_object(val): if val != val: return True - elif inf_as_na: - return val == INF or val == NEGINF return False elif cnp.is_timedelta64_object(val): return cnp.get_timedelta64_value(val) == NPY_NAT @@ -184,7 +180,7 @@ cdef bint is_decimal_na(object val): @cython.wraparound(False) @cython.boundscheck(False) -cpdef ndarray[uint8_t] isnaobj(ndarray arr, bint inf_as_na=False): +cpdef ndarray[uint8_t] isnaobj(ndarray arr): """ Return boolean mask denoting which elements of a 1-D array are na-like, according to the criteria defined in `checknull`: @@ -217,7 +213,7 @@ cpdef ndarray[uint8_t] isnaobj(ndarray arr, bint inf_as_na=False): # equivalents to `val = values[i]` val = cnp.PyArray_GETITEM(arr, cnp.PyArray_ITER_DATA(it)) cnp.PyArray_ITER_NEXT(it) - is_null = checknull(val, inf_as_na=inf_as_na) + is_null = checknull(val) # Dereference pointer (set value) (<uint8_t *>(cnp.PyArray_ITER_DATA(it2)))[0] = <uint8_t>is_null cnp.PyArray_ITER_NEXT(it2) diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index f9e6b3296eb13..5dd1624207d41 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -406,35 +406,6 @@ def is_terminal() -> bool: with cf.config_prefix("mode"): cf.register_option("sim_interactive", False, tc_sim_interactive_doc) -use_inf_as_na_doc = """ -: boolean - True means treat None, NaN, INF, -INF as NA (old way), - False means None and NaN are null, but INF, -INF are not NA - (new way). - - This option is deprecated in pandas 2.1.0 and will be removed in 3.0. -""" - -# We don't want to start importing everything at the global context level -# or we'll hit circular deps. - - -def use_inf_as_na_cb(key) -> None: - # TODO(3.0): enforcing this deprecation will close GH#52501 - from pandas.core.dtypes.missing import _use_inf_as_na - - _use_inf_as_na(key) - - -with cf.config_prefix("mode"): - cf.register_option("use_inf_as_na", False, use_inf_as_na_doc, cb=use_inf_as_na_cb) - -cf.deprecate_option( - # GH#51684 - "mode.use_inf_as_na", - "use_inf_as_na option is deprecated and will be removed in a future " - "version. Convert inf values to NaN before operating instead.", -) # TODO better name? copy_on_write_doc = """ diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 17c1ad5e4d8d9..9ff27bd69a1c9 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -4,7 +4,6 @@ from __future__ import annotations from decimal import Decimal -from functools import partial from typing import ( TYPE_CHECKING, overload, @@ -13,8 +12,6 @@ import numpy as np -from pandas._config import get_option - from pandas._libs import lib import pandas._libs.missing as libmissing from pandas._libs.tslibs import ( @@ -64,8 +61,6 @@ isposinf_scalar = libmissing.isposinf_scalar isneginf_scalar = libmissing.isneginf_scalar -nan_checker = np.isnan -INF_AS_NA = False _dtype_object = np.dtype("object") _dtype_str = np.dtype(str) @@ -180,86 +175,50 @@ def isna(obj: object) -> bool | npt.NDArray[np.bool_] | NDFrame: isnull = isna -def _isna(obj, inf_as_na: bool = False): +def _isna(obj): """ - Detect missing values, treating None, NaN or NA as null. Infinite - values will also be treated as null if inf_as_na is True. + Detect missing values, treating None, NaN or NA as null. Parameters ---------- obj: ndarray or object value Input array or scalar value. - inf_as_na: bool - Whether to treat infinity as null. Returns ------- boolean ndarray or boolean """ if is_scalar(obj): - return libmissing.checknull(obj, inf_as_na=inf_as_na) + return libmissing.checknull(obj) elif isinstance(obj, ABCMultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance(obj, (np.ndarray, ABCExtensionArray)): - return _isna_array(obj, inf_as_na=inf_as_na) + return _isna_array(obj) elif isinstance(obj, ABCIndex): # Try to use cached isna, which also short-circuits for integer dtypes # and avoids materializing RangeIndex._values if not obj._can_hold_na: return obj.isna() - return _isna_array(obj._values, inf_as_na=inf_as_na) + return _isna_array(obj._values) elif isinstance(obj, ABCSeries): - result = _isna_array(obj._values, inf_as_na=inf_as_na) + result = _isna_array(obj._values) # box result = obj._constructor(result, index=obj.index, name=obj.name, copy=False) return result elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): - return _isna_array(np.asarray(obj, dtype=object), inf_as_na=inf_as_na) + return _isna_array(np.asarray(obj, dtype=object)) elif hasattr(obj, "__array__"): - return _isna_array(np.asarray(obj), inf_as_na=inf_as_na) + return _isna_array(np.asarray(obj)) else: return False -def _use_inf_as_na(key) -> None: - """ - Option change callback for na/inf behaviour. - - Choose which replacement for numpy.isnan / -numpy.isfinite is used. - - Parameters - ---------- - flag: bool - True means treat None, NaN, INF, -INF as null (old way), - False means None and NaN are null, but INF, -INF are not null - (new way). - - Notes - ----- - This approach to setting global module values is discussed and - approved here: - - * https://stackoverflow.com/questions/4859217/ - programmatically-creating-variables-in-python/4859312#4859312 - """ - inf_as_na = get_option(key) - globals()["_isna"] = partial(_isna, inf_as_na=inf_as_na) - if inf_as_na: - globals()["nan_checker"] = lambda x: ~np.isfinite(x) - globals()["INF_AS_NA"] = True - else: - globals()["nan_checker"] = np.isnan - globals()["INF_AS_NA"] = False - - -def _isna_array( - values: ArrayLike, inf_as_na: bool = False -) -> npt.NDArray[np.bool_] | NDFrame: +def _isna_array(values: ArrayLike) -> npt.NDArray[np.bool_] | NDFrame: """ Return an array indicating which values of the input array are NaN / NA. @@ -267,8 +226,6 @@ def _isna_array( ---------- obj: ndarray or ExtensionArray The input array whose elements are to be checked. - inf_as_na: bool - Whether or not to treat infinite values as NA. Returns ------- @@ -280,31 +237,25 @@ def _isna_array( if not isinstance(values, np.ndarray): # i.e. ExtensionArray - if inf_as_na and isinstance(dtype, CategoricalDtype): - result = libmissing.isnaobj(values.to_numpy(), inf_as_na=inf_as_na) - else: - # error: Incompatible types in assignment (expression has type - # "Union[ndarray[Any, Any], ExtensionArraySupportsAnyAll]", variable has - # type "ndarray[Any, dtype[bool_]]") - result = values.isna() # type: ignore[assignment] + # error: Incompatible types in assignment (expression has type + # "Union[ndarray[Any, Any], ExtensionArraySupportsAnyAll]", variable has + # type "ndarray[Any, dtype[bool_]]") + result = values.isna() # type: ignore[assignment] elif isinstance(values, np.rec.recarray): # GH 48526 - result = _isna_recarray_dtype(values, inf_as_na=inf_as_na) + result = _isna_recarray_dtype(values) elif is_string_or_object_np_dtype(values.dtype): - result = _isna_string_dtype(values, inf_as_na=inf_as_na) + result = _isna_string_dtype(values) elif dtype.kind in "mM": # this is the NaT pattern result = values.view("i8") == iNaT else: - if inf_as_na: - result = ~np.isfinite(values) - else: - result = np.isnan(values) + result = np.isnan(values) return result -def _isna_string_dtype(values: np.ndarray, inf_as_na: bool) -> npt.NDArray[np.bool_]: +def _isna_string_dtype(values: np.ndarray) -> npt.NDArray[np.bool_]: # Working around NumPy ticket 1542 dtype = values.dtype @@ -312,41 +263,21 @@ def _isna_string_dtype(values: np.ndarray, inf_as_na: bool) -> npt.NDArray[np.bo result = np.zeros(values.shape, dtype=bool) else: if values.ndim in {1, 2}: - result = libmissing.isnaobj(values, inf_as_na=inf_as_na) + result = libmissing.isnaobj(values) else: # 0-D, reached via e.g. mask_missing - result = libmissing.isnaobj(values.ravel(), inf_as_na=inf_as_na) + result = libmissing.isnaobj(values.ravel()) result = result.reshape(values.shape) return result -def _has_record_inf_value(record_as_array: np.ndarray) -> np.bool_: - is_inf_in_record = np.zeros(len(record_as_array), dtype=bool) - for i, value in enumerate(record_as_array): - is_element_inf = False - try: - is_element_inf = np.isinf(value) - except TypeError: - is_element_inf = False - is_inf_in_record[i] = is_element_inf - - return np.any(is_inf_in_record) - - -def _isna_recarray_dtype( - values: np.rec.recarray, inf_as_na: bool -) -> npt.NDArray[np.bool_]: +def _isna_recarray_dtype(values: np.rec.recarray) -> npt.NDArray[np.bool_]: result = np.zeros(values.shape, dtype=bool) for i, record in enumerate(values): record_as_array = np.array(record.tolist()) does_record_contain_nan = isna_all(record_as_array) - does_record_contain_inf = False - if inf_as_na: - does_record_contain_inf = bool(_has_record_inf_value(record_as_array)) - result[i] = np.any( - np.logical_or(does_record_contain_nan, does_record_contain_inf) - ) + result[i] = np.any(does_record_contain_nan) return result @@ -774,7 +705,7 @@ def isna_all(arr: ArrayLike) -> bool: dtype = arr.dtype if lib.is_np_dtype(dtype, "f"): - checker = nan_checker + checker = np.isnan elif (lib.is_np_dtype(dtype, "mM")) or isinstance( dtype, (DatetimeTZDtype, PeriodDtype) @@ -786,9 +717,7 @@ def isna_all(arr: ArrayLike) -> bool: else: # error: Incompatible types in assignment (expression has type "Callable[[Any], # Any]", variable has type "ufunc") - checker = lambda x: _isna_array( # type: ignore[assignment] - x, inf_as_na=INF_AS_NA - ) + checker = _isna_array # type: ignore[assignment] return all( checker(arr[i : i + chunk_len]).all() for i in range(0, total_len, chunk_len) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 93e4468f91edd..18c8b5fd51e6e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8026,8 +8026,7 @@ def isna(self) -> Self: NA values, such as None or :attr:`numpy.NaN`, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty - strings ``''`` or :attr:`numpy.inf` are not considered NA values - (unless you set ``pandas.options.mode.use_inf_as_na = True``). + strings ``''`` or :attr:`numpy.inf` are not considered NA values. Returns ------- @@ -8098,8 +8097,7 @@ def notna(self) -> Self: Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty - strings ``''`` or :attr:`numpy.inf` are not considered NA values - (unless you set ``pandas.options.mode.use_inf_as_na = True``). + strings ``''`` or :attr:`numpy.inf` are not considered NA values. NA values, such as None or :attr:`numpy.NaN`, get mapped to False values. diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 0fa6d2959c802..04d5fcae1a50d 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1205,10 +1205,6 @@ def _format(x): return "None" elif x is NA: return str(NA) - elif lib.is_float(x) and np.isinf(x): - # TODO(3.0): this will be unreachable when use_inf_as_na - # deprecation is enforced - return str(x) elif x is NaT or isinstance(x, (np.datetime64, np.timedelta64)): return "NaT" return self.na_rep diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py index 0eeb01b746088..332d31e9e3fc2 100644 --- a/pandas/tests/arrays/categorical/test_missing.py +++ b/pandas/tests/arrays/categorical/test_missing.py @@ -8,7 +8,6 @@ import pandas as pd from pandas import ( Categorical, - DataFrame, Index, Series, isna, @@ -126,60 +125,6 @@ def test_fillna_array(self): tm.assert_categorical_equal(result, expected) assert isna(cat[-1]) # didn't modify original inplace - @pytest.mark.parametrize( - "values, expected", - [ - ([1, 2, 3], np.array([False, False, False])), - ([1, 2, np.nan], np.array([False, False, True])), - ([1, 2, np.inf], np.array([False, False, True])), - ([1, 2, pd.NA], np.array([False, False, True])), - ], - ) - def test_use_inf_as_na(self, values, expected): - # https://github.com/pandas-dev/pandas/issues/33594 - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - cat = Categorical(values) - result = cat.isna() - tm.assert_numpy_array_equal(result, expected) - - result = Series(cat).isna() - expected = Series(expected) - tm.assert_series_equal(result, expected) - - result = DataFrame(cat).isna() - expected = DataFrame(expected) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "values, expected", - [ - ([1, 2, 3], np.array([False, False, False])), - ([1, 2, np.nan], np.array([False, False, True])), - ([1, 2, np.inf], np.array([False, False, True])), - ([1, 2, pd.NA], np.array([False, False, True])), - ], - ) - def test_use_inf_as_na_outside_context(self, values, expected): - # https://github.com/pandas-dev/pandas/issues/33594 - # Using isna directly for Categorical will fail in general here - cat = Categorical(values) - - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - result = isna(cat) - tm.assert_numpy_array_equal(result, expected) - - result = isna(Series(cat)) - expected = Series(expected) - tm.assert_series_equal(result, expected) - - result = isna(DataFrame(cat)) - expected = DataFrame(expected) - tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize( "a1, a2, categories", [ diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index cb324d29258c0..4b82d43158b88 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -597,31 +597,6 @@ def test_value_counts_sort_false(dtype): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize( - "values, expected", - [ - (["a", "b", "c"], np.array([False, False, False])), - (["a", "b", None], np.array([False, False, True])), - ], -) -def test_use_inf_as_na(values, expected, dtype): - # https://github.com/pandas-dev/pandas/issues/33655 - values = pd.array(values, dtype=dtype) - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - result = values.isna() - tm.assert_numpy_array_equal(result, expected) - - result = pd.Series(values).isna() - expected = pd.Series(expected) - tm.assert_series_equal(result, expected) - - result = pd.DataFrame(values).isna() - expected = pd.DataFrame(expected) - tm.assert_frame_equal(result, expected) - - def test_memory_usage(dtype, arrow_string_storage): # GH 33963 diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index c205f35b0ced8..2109c794ad44f 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -5,8 +5,6 @@ import numpy as np import pytest -from pandas._config import config as cf - from pandas._libs import missing as libmissing from pandas._libs.tslibs import iNaT from pandas.compat.numpy import np_version_gte1p25 @@ -54,25 +52,6 @@ def test_notna_notnull(notna_f): assert not notna_f(None) assert not notna_f(np.nan) - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with cf.option_context("mode.use_inf_as_na", False): - assert notna_f(np.inf) - assert notna_f(-np.inf) - - arr = np.array([1.5, np.inf, 3.5, -np.inf]) - result = notna_f(arr) - assert result.all() - - with tm.assert_produces_warning(FutureWarning, match=msg): - with cf.option_context("mode.use_inf_as_na", True): - assert not notna_f(np.inf) - assert not notna_f(-np.inf) - - arr = np.array([1.5, np.inf, 3.5, -np.inf]) - result = notna_f(arr) - assert result.sum() == 2 - @pytest.mark.parametrize("null_func", [notna, notnull, isna, isnull]) @pytest.mark.parametrize( @@ -88,10 +67,7 @@ def test_notna_notnull(notna_f): ], ) def test_null_check_is_series(null_func, ser): - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with cf.option_context("mode.use_inf_as_na", False): - assert isinstance(null_func(ser), Series) + assert isinstance(null_func(ser), Series) class TestIsNA: @@ -232,10 +208,7 @@ def test_isna_old_datetimelike(self): objs = [dta, dta.tz_localize("US/Eastern"), dta - dta, dta.to_period("D")] for obj in objs: - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with cf.option_context("mode.use_inf_as_na", True): - result = isna(obj) + result = isna(obj) tm.assert_numpy_array_equal(result, expected) @@ -743,23 +716,17 @@ class TestNAObj: def _check_behavior(self, arr, expected): result = libmissing.isnaobj(arr) tm.assert_numpy_array_equal(result, expected) - result = libmissing.isnaobj(arr, inf_as_na=True) - tm.assert_numpy_array_equal(result, expected) arr = np.atleast_2d(arr) expected = np.atleast_2d(expected) result = libmissing.isnaobj(arr) tm.assert_numpy_array_equal(result, expected) - result = libmissing.isnaobj(arr, inf_as_na=True) - tm.assert_numpy_array_equal(result, expected) # Test fortran order arr = arr.copy(order="F") result = libmissing.isnaobj(arr) tm.assert_numpy_array_equal(result, expected) - result = libmissing.isnaobj(arr, inf_as_na=True) - tm.assert_numpy_array_equal(result, expected) def test_basic(self): arr = np.array([1, None, "foo", -5.1, NaT, np.nan]) @@ -868,19 +835,11 @@ def test_checknull_never_na_vals(self, func, value): na_vals + sometimes_na_vals, # type: ignore[operator] ) def test_checknull_old_na_vals(self, value): - assert libmissing.checknull(value, inf_as_na=True) - - @pytest.mark.parametrize("value", inf_vals) - def test_checknull_old_inf_vals(self, value): - assert libmissing.checknull(value, inf_as_na=True) + assert libmissing.checknull(value) @pytest.mark.parametrize("value", int_na_vals) def test_checknull_old_intna_vals(self, value): - assert not libmissing.checknull(value, inf_as_na=True) - - @pytest.mark.parametrize("value", int_na_vals) - def test_checknull_old_never_na_vals(self, value): - assert not libmissing.checknull(value, inf_as_na=True) + assert not libmissing.checknull(value) def test_is_matching_na(self, nulls_fixture, nulls_fixture2): left = nulls_fixture diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index dbd6682c12123..b9cba2fc52728 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -177,12 +177,3 @@ def test_fillna_fill_other(self, data): expected = pd.DataFrame({"A": data, "B": [0.0] * len(result)}) tm.assert_frame_equal(result, expected) - - def test_use_inf_as_na_no_effect(self, data_missing): - ser = pd.Series(data_missing) - expected = ser.isna() - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - result = ser.isna() - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_dtypes.py b/pandas/tests/frame/methods/test_dtypes.py index ab632ac17318e..0697f59cd271f 100644 --- a/pandas/tests/frame/methods/test_dtypes.py +++ b/pandas/tests/frame/methods/test_dtypes.py @@ -10,7 +10,6 @@ DataFrame, Series, date_range, - option_context, ) import pandas._testing as tm @@ -95,14 +94,6 @@ def test_dtypes_gh8722(self, float_string_frame): ) tm.assert_series_equal(result, expected) - # compat, GH 8722 - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with option_context("use_inf_as_na", True): - df = DataFrame([[1]]) - result = df.dtypes - tm.assert_series_equal(result, Series({0: np.dtype("int64")})) - def test_dtypes_timedeltas(self): df = DataFrame( { diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index d88daaff685aa..1a631e760208a 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -773,18 +773,6 @@ def test_sort_index_ascending_bad_value_raises(self, ascending): with pytest.raises(ValueError, match=match): df.sort_index(axis=0, ascending=ascending, na_position="first") - def test_sort_index_use_inf_as_na(self): - # GH 29687 - expected = DataFrame( - {"col1": [1, 2, 3], "col2": [3, 4, 5]}, - index=pd.date_range("2020", periods=3), - ) - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - result = expected.sort_index() - tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize( "ascending", [(True, False), [True, False]], diff --git a/pandas/tests/frame/test_repr.py b/pandas/tests/frame/test_repr.py index 4425d067e67dc..f6e0251d52de1 100644 --- a/pandas/tests/frame/test_repr.py +++ b/pandas/tests/frame/test_repr.py @@ -425,38 +425,18 @@ def test_to_records_with_na_record(self): result = repr(df) assert result == expected - def test_to_records_with_inf_as_na_record(self): - # GH 48526 - expected = """ NaN inf record -0 inf b [0, inf, b] -1 NaN NaN [1, nan, nan] -2 e f [2, e, f]""" - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with option_context("use_inf_as_na", True): - df = DataFrame( - [[np.inf, "b"], [np.nan, np.nan], ["e", "f"]], - columns=[np.nan, np.inf], - ) - df["record"] = df[[np.nan, np.inf]].to_records() - result = repr(df) - assert result == expected - def test_to_records_with_inf_record(self): # GH 48526 expected = """ NaN inf record 0 inf b [0, inf, b] 1 NaN NaN [1, nan, nan] 2 e f [2, e, f]""" - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with option_context("use_inf_as_na", False): - df = DataFrame( - [[np.inf, "b"], [np.nan, np.nan], ["e", "f"]], - columns=[np.nan, np.inf], - ) - df["record"] = df[[np.nan, np.inf]].to_records() - result = repr(df) + df = DataFrame( + [[np.inf, "b"], [np.nan, np.nan], ["e", "f"]], + columns=[np.nan, np.inf], + ) + df["record"] = df[[np.nan, np.inf]].to_records() + result = repr(df) assert result == expected def test_masked_ea_with_formatter(self): diff --git a/pandas/tests/io/parser/common/test_inf.py b/pandas/tests/io/parser/common/test_inf.py index 74596b178d35d..dba952b1f9ebd 100644 --- a/pandas/tests/io/parser/common/test_inf.py +++ b/pandas/tests/io/parser/common/test_inf.py @@ -4,13 +4,9 @@ """ from io import StringIO -import numpy as np import pytest -from pandas import ( - DataFrame, - option_context, -) +from pandas import DataFrame import pandas._testing as tm pytestmark = pytest.mark.filterwarnings( @@ -60,19 +56,3 @@ def test_infinity_parsing(all_parsers, na_filter): ) result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter) tm.assert_frame_equal(result, expected) - - -def test_read_csv_with_use_inf_as_na(all_parsers): - # https://github.com/pandas-dev/pandas/issues/35493 - parser = all_parsers - data = "1.0\nNaN\n3.0" - msg = "use_inf_as_na option is deprecated" - warn = FutureWarning - if parser.engine == "pyarrow": - warn = (FutureWarning, DeprecationWarning) - - with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False): - with option_context("use_inf_as_na", True): - result = parser.read_csv(StringIO(data), header=None) - expected = DataFrame([1.0, np.nan, 3.0]) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index efecd43625eed..91ee13ecd87dd 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -594,11 +594,6 @@ def test_sum_inf(self): arr = np.random.default_rng(2).standard_normal((100, 100)).astype("f4") arr[:, 2] = np.inf - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - tm.assert_almost_equal(s.sum(), s2.sum()) - res = nanops.nansum(arr, axis=1) assert np.isinf(res).all() @@ -1242,16 +1237,6 @@ def test_idxminmax_with_inf(self): with tm.assert_produces_warning(FutureWarning, match=msg): assert np.isnan(s.idxmax(skipna=False)) - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - # Using old-style behavior that treats floating point nan, -inf, and - # +inf as missing - with pd.option_context("mode.use_inf_as_na", True): - assert s.idxmin() == 0 - assert np.isnan(s.idxmin(skipna=False)) - assert s.idxmax() == 0 - np.isnan(s.idxmax(skipna=False)) - def test_sum_uint64(self): # GH 53401 s = Series([10000000000000000000], dtype="uint64") diff --git a/pandas/tests/series/methods/test_count.py b/pandas/tests/series/methods/test_count.py index 9ba163f347198..2172a3205ef55 100644 --- a/pandas/tests/series/methods/test_count.py +++ b/pandas/tests/series/methods/test_count.py @@ -1,11 +1,9 @@ import numpy as np -import pandas as pd from pandas import ( Categorical, Series, ) -import pandas._testing as tm class TestSeriesCount: @@ -16,14 +14,6 @@ def test_count(self, datetime_series): assert datetime_series.count() == np.isfinite(datetime_series).sum() - def test_count_inf_as_na(self): - # GH#29478 - ser = Series([pd.Timestamp("1990/1/1")]) - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("use_inf_as_na", True): - assert ser.count() == 1 - def test_count_categorical(self): ser = Series( Categorical( diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index cafc69c4d0f20..108c3aabb1aa4 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -25,18 +25,6 @@ def test_categorical_nan_handling(self): s.values.codes, np.array([0, 1, -1, 0], dtype=np.int8) ) - def test_isna_for_inf(self): - s = Series(["a", np.inf, np.nan, pd.NA, 1.0]) - msg = "use_inf_as_na option is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pd.option_context("mode.use_inf_as_na", True): - r = s.isna() - dr = s.dropna() - e = Series([False, True, True, True, False]) - de = Series(["a", 1.0], index=[0, 4]) - tm.assert_series_equal(r, e) - tm.assert_series_equal(dr, de) - def test_timedelta64_nan(self): td = Series([timedelta(days=i) for i in range(10)]) diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py index fd8963ad85abc..a732d3f83a40a 100755 --- a/scripts/validate_unwanted_patterns.py +++ b/scripts/validate_unwanted_patterns.py @@ -35,7 +35,6 @@ "_apply_groupings_depr", "__main__", "_transform_template", - "_use_inf_as_na", "_get_plot_backend", "_matplotlib", "_arrow_utils",
xref https://github.com/pandas-dev/pandas/pull/53494
https://api.github.com/repos/pandas-dev/pandas/pulls/57428
2024-02-14T21:08:18Z
2024-02-19T23:28:25Z
2024-02-19T23:28:25Z
2024-02-19T23:28:27Z
DOC: fix SA05 errors in docstrings for pandas.core.resample.Resampler…
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 54e12496cf9c5..5eae5c6b60c17 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -1870,8 +1870,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=SA05 --ignore_functions \ pandas.core.groupby.SeriesGroupBy.first\ pandas.core.groupby.SeriesGroupBy.last\ - pandas.core.resample.Resampler.first\ - pandas.core.resample.Resampler.last\ pandas.core.window.expanding.Expanding.aggregate\ pandas.core.window.rolling.Rolling.aggregate\ pandas.plotting.bootstrap_plot\
Small code change, removing the two functions above for SA05 ignore functions. - [ ] xref #57392 - [ ] [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/57426
2024-02-14T20:03:03Z
2024-02-14T21:13:40Z
2024-02-14T21:13:40Z
2024-02-14T21:25:17Z
CLN: shift with freq and fill_value, to_pydatetime returning Series
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 7edc3c50de96d..aa18e1182dccc 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -112,6 +112,7 @@ Deprecations Removal of prior version deprecations/changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :func:`read_excel`, :func:`read_json`, :func:`read_html`, and :func:`read_xml` no longer accept raw string or byte representation of the data. That type of data must be wrapped in a :py:class:`StringIO` or :py:class:`BytesIO` (:issue:`53767`) +- :meth:`Series.dt.to_pydatetime` now returns a :class:`Series` of :py:class:`datetime.datetime` objects (:issue:`52459`) - All arguments except ``name`` in :meth:`Index.rename` are now keyword only (:issue:`56493`) - All arguments except the first ``path``-like argument in IO writers are now keyword only (:issue:`54229`) - All arguments in :meth:`Index.sort_values` are now keyword only (:issue:`56493`) @@ -120,6 +121,7 @@ Removal of prior version deprecations/changes - Enforced deprecation disallowing parsing datetimes with mixed time zones unless user passes ``utc=True`` to :func:`to_datetime` (:issue:`57275`) - Enforced silent-downcasting deprecation for :ref:`all relevant methods <whatsnew_220.silent_downcasting>` (:issue:`54710`) - In :meth:`DataFrame.stack`, the default value of ``future_stack`` is now ``True``; specifying ``False`` will raise a ``FutureWarning`` (:issue:`55448`) +- Passing both ``freq`` and ``fill_value`` in :meth:`DataFrame.shift` and :meth:`Series.shift` and :meth:`.DataFrameGroupBy.shift` now raises a ``ValueError`` (:issue:`54818`) - Removed :meth:`DateOffset.is_anchored` and :meth:`offsets.Tick.is_anchored` (:issue:`56594`) - Removed ``DataFrame.applymap``, ``Styler.applymap`` and ``Styler.applymap_index`` (:issue:`52364`) - Removed ``DataFrame.bool`` and ``Series.bool`` (:issue:`51756`) diff --git a/pandas/conftest.py b/pandas/conftest.py index 47316a4ba3526..acd802a27ea8c 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -158,10 +158,6 @@ def pytest_collection_modifyitems(items, config) -> None: ("SeriesGroupBy.idxmax", "The behavior of Series.idxmax"), # Docstring divides by zero to show behavior difference ("missing.mask_zero_div_zero", "divide by zero encountered"), - ( - "to_pydatetime", - "The behavior of DatetimeProperties.to_pydatetime is deprecated", - ), ( "pandas.core.generic.NDFrame.first", "first is deprecated and will be removed in a future version. " diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index aeb6ef481e060..f4284cb0d0e5e 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -2918,7 +2918,9 @@ def _dt_month_name(self, locale: str | None = None) -> Self: locale = "C" return type(self)(pc.strftime(self._pa_array, format="%B", locale=locale)) - def _dt_to_pydatetime(self) -> np.ndarray: + def _dt_to_pydatetime(self) -> Series: + from pandas import Series + if pa.types.is_date(self.dtype.pyarrow_dtype): raise ValueError( f"to_pydatetime cannot be called with {self.dtype.pyarrow_dtype} type. " @@ -2927,7 +2929,7 @@ def _dt_to_pydatetime(self) -> np.ndarray: data = self._pa_array.to_pylist() if self._dtype.pyarrow_dtype.unit == "ns": data = [None if ts is None else ts.to_pydatetime(warn=False) for ts in data] - return np.array(data, dtype=object) + return Series(data, dtype=object) def _dt_tz_localize( self, diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 57f2cdef5457a..abb043361483c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5588,14 +5588,9 @@ def shift( ) -> DataFrame: if freq is not None and fill_value is not lib.no_default: # GH#53832 - warnings.warn( - "Passing a 'freq' together with a 'fill_value' silently ignores " - "the fill_value and is deprecated. This will raise in a future " - "version.", - FutureWarning, - stacklevel=find_stack_level(), + raise ValueError( + "Passing a 'freq' together with a 'fill_value' is not allowed." ) - fill_value = lib.no_default if self.empty: return self.copy() diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7614951566bf9..e335929914101 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10271,14 +10271,9 @@ def shift( if freq is not None and fill_value is not lib.no_default: # GH#53832 - warnings.warn( - "Passing a 'freq' together with a 'fill_value' silently ignores " - "the fill_value and is deprecated. This will raise in a future " - "version.", - FutureWarning, - stacklevel=find_stack_level(), + raise ValueError( + "Passing a 'freq' together with a 'fill_value' is not allowed." ) - fill_value = lib.no_default if periods == 0: return self.copy(deep=None) diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index 8a742a0a9d57d..5881f5e040370 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -8,12 +8,10 @@ NoReturn, cast, ) -import warnings import numpy as np from pandas._libs import lib -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_integer_dtype, @@ -213,16 +211,8 @@ def _delegate_method(self, name: str, *args, **kwargs): def to_pytimedelta(self): return cast(ArrowExtensionArray, self._parent.array)._dt_to_pytimedelta() - def to_pydatetime(self): + def to_pydatetime(self) -> Series: # GH#20306 - warnings.warn( - f"The behavior of {type(self).__name__}.to_pydatetime is deprecated, " - "in a future version this will return a Series containing python " - "datetime objects instead of an ndarray. To retain the old behavior, " - "call `np.array` on the result", - FutureWarning, - stacklevel=find_stack_level(), - ) return cast(ArrowExtensionArray, self._parent.array)._dt_to_pydatetime() def isocalendar(self) -> DataFrame: @@ -318,15 +308,9 @@ class DatetimeProperties(Properties): Raises TypeError if the Series does not contain datetimelike values. """ - def to_pydatetime(self) -> np.ndarray: + def to_pydatetime(self) -> Series: """ - Return the data as an array of :class:`datetime.datetime` objects. - - .. deprecated:: 2.1.0 - - The current behavior of dt.to_pydatetime is deprecated. - In a future version this will return a Series containing python - datetime objects instead of a ndarray. + Return the data as a Series of :class:`datetime.datetime` objects. Timezone information is retained if present. @@ -353,8 +337,9 @@ def to_pydatetime(self) -> np.ndarray: dtype: datetime64[ns] >>> s.dt.to_pydatetime() - array([datetime.datetime(2018, 3, 10, 0, 0), - datetime.datetime(2018, 3, 11, 0, 0)], dtype=object) + 0 2018-03-10 00:00:00 + 1 2018-03-11 00:00:00 + dtype: object pandas' nanosecond precision is truncated to microseconds. @@ -365,19 +350,14 @@ def to_pydatetime(self) -> np.ndarray: dtype: datetime64[ns] >>> s.dt.to_pydatetime() - array([datetime.datetime(2018, 3, 10, 0, 0), - datetime.datetime(2018, 3, 10, 0, 0)], dtype=object) + 0 2018-03-10 00:00:00 + 1 2018-03-10 00:00:00 + dtype: object """ # GH#20306 - warnings.warn( - f"The behavior of {type(self).__name__}.to_pydatetime is deprecated, " - "in a future version this will return a Series containing python " - "datetime objects instead of an ndarray. To retain the old behavior, " - "call `np.array` on the result", - FutureWarning, - stacklevel=find_stack_level(), - ) - return self._get_values().to_pydatetime() + from pandas import Series + + return Series(self._get_values().to_pydatetime(), dtype=object) @property def freq(self): diff --git a/pandas/io/sql.py b/pandas/io/sql.py index d816bb2fc09d3..9024961688c6b 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1037,10 +1037,7 @@ def insert_data(self) -> tuple[list[str], list[np.ndarray]]: # GH#53854 to_pydatetime not supported for pyarrow date dtypes d = ser._values.to_numpy(dtype=object) else: - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", category=FutureWarning) - # GH#52459 to_pydatetime will return Index[object] - d = np.asarray(ser.dt.to_pydatetime(), dtype=object) + d = ser.dt.to_pydatetime()._values else: d = ser._values.to_pydatetime() elif ser.dtype.kind == "m": diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index fe6e484fbd6e7..5d634c9aeb14f 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -2676,18 +2676,13 @@ def test_dt_to_pydatetime(): # GH 51859 data = [datetime(2022, 1, 1), datetime(2023, 1, 1)] ser = pd.Series(data, dtype=ArrowDtype(pa.timestamp("ns"))) + result = ser.dt.to_pydatetime() + expected = pd.Series(data, dtype=object) + tm.assert_series_equal(result, expected) + assert all(type(expected.iloc[i]) is datetime for i in range(len(expected))) - msg = "The behavior of ArrowTemporalProperties.to_pydatetime is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = ser.dt.to_pydatetime() - expected = np.array(data, dtype=object) - tm.assert_numpy_array_equal(result, expected) - assert all(type(res) is datetime for res in result) - - msg = "The behavior of DatetimeProperties.to_pydatetime is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = ser.astype("datetime64[ns]").dt.to_pydatetime() - tm.assert_numpy_array_equal(result, expected) + expected = ser.astype("datetime64[ns]").dt.to_pydatetime() + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("date_type", [32, 64]) @@ -2697,10 +2692,8 @@ def test_dt_to_pydatetime_date_error(date_type): [date(2022, 12, 31)], dtype=ArrowDtype(getattr(pa, f"date{date_type}")()), ) - msg = "The behavior of ArrowTemporalProperties.to_pydatetime is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pytest.raises(ValueError, match="to_pydatetime cannot be called with"): - ser.dt.to_pydatetime() + with pytest.raises(ValueError, match="to_pydatetime cannot be called with"): + ser.dt.to_pydatetime() def test_dt_tz_localize_unsupported_tz_options(): diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 5bcfaf8b199bf..72c1a123eac98 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -30,23 +30,20 @@ def test_shift_axis1_with_valid_fill_value_one_array(self): expected2 = DataFrame([12345] * 5, dtype="Float64") tm.assert_frame_equal(res2, expected2) - def test_shift_deprecate_freq_and_fill_value(self, frame_or_series): + def test_shift_disallow_freq_and_fill_value(self, frame_or_series): # Can't pass both! obj = frame_or_series( np.random.default_rng(2).standard_normal(5), index=date_range("1/1/2000", periods=5, freq="h"), ) - msg = ( - "Passing a 'freq' together with a 'fill_value' silently ignores the " - "fill_value" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): + msg = "Passing a 'freq' together with a 'fill_value'" + with pytest.raises(ValueError, match=msg): obj.shift(1, fill_value=1, freq="h") if frame_or_series is DataFrame: obj.columns = date_range("1/1/2000", periods=1, freq="h") - with tm.assert_produces_warning(FutureWarning, match=msg): + with pytest.raises(ValueError, match=msg): obj.shift(1, axis=1, fill_value=1, freq="h") @pytest.mark.parametrize( @@ -717,13 +714,6 @@ def test_shift_with_iterable_freq_and_fill_value(self): df.shift(1, freq="h"), ) - msg = ( - "Passing a 'freq' together with a 'fill_value' silently ignores the " - "fill_value" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - df.shift([1, 2], fill_value=1, freq="h") - def test_shift_with_iterable_check_other_arguments(self): # GH#44424 data = {"a": [1, 2], "b": [4, 5]} diff --git a/pandas/tests/groupby/methods/test_groupby_shift_diff.py b/pandas/tests/groupby/methods/test_groupby_shift_diff.py index 41e0ee93a5941..1256046d81949 100644 --- a/pandas/tests/groupby/methods/test_groupby_shift_diff.py +++ b/pandas/tests/groupby/methods/test_groupby_shift_diff.py @@ -167,14 +167,12 @@ def test_shift_periods_freq(): tm.assert_frame_equal(result, expected) -def test_shift_deprecate_freq_and_fill_value(): +def test_shift_disallow_freq_and_fill_value(): # GH 53832 data = {"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]} df = DataFrame(data, index=date_range(start="20100101", periods=6)) - msg = ( - "Passing a 'freq' together with a 'fill_value' silently ignores the fill_value" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): + msg = "Passing a 'freq' together with a 'fill_value'" + with pytest.raises(ValueError, match=msg): df.groupby(df.index).shift(periods=-2, freq="D", fill_value="1") @@ -247,9 +245,6 @@ def test_group_shift_with_multiple_periods_and_both_fill_and_freq_deprecated(): {"a": [1, 2, 3, 4, 5], "b": [True, True, False, False, True]}, index=date_range("1/1/2000", periods=5, freq="h"), ) - msg = ( - "Passing a 'freq' together with a 'fill_value' silently ignores the " - "fill_value" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): + msg = "Passing a 'freq' together with a 'fill_value'" + with pytest.raises(ValueError, match=msg): df.groupby("b")[["a"]].shift([1, 2], fill_value=1, freq="h") diff --git a/pandas/tests/series/accessors/test_cat_accessor.py b/pandas/tests/series/accessors/test_cat_accessor.py index 2d50b0f36904a..ca2768efd5c68 100644 --- a/pandas/tests/series/accessors/test_cat_accessor.py +++ b/pandas/tests/series/accessors/test_cat_accessor.py @@ -200,9 +200,6 @@ def test_dt_accessor_api_for_categorical(self, idx): if func == "to_period" and getattr(idx, "tz", None) is not None: # dropping TZ warn_cls.append(UserWarning) - if func == "to_pydatetime": - # deprecated to return Index[object] - warn_cls.append(FutureWarning) if warn_cls: warn_cls = tuple(warn_cls) else: diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index 17492f17132fd..5f0057ac50b47 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -114,10 +114,8 @@ def test_dt_namespace_accessor_datetime64(self, freq): for prop in ok_for_dt_methods: getattr(ser.dt, prop) - msg = "The behavior of DatetimeProperties.to_pydatetime is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = ser.dt.to_pydatetime() - assert isinstance(result, np.ndarray) + result = ser.dt.to_pydatetime() + assert isinstance(result, Series) assert result.dtype == object result = ser.dt.tz_localize("US/Eastern") @@ -153,10 +151,8 @@ def test_dt_namespace_accessor_datetime64tz(self): for prop in ok_for_dt_methods: getattr(ser.dt, prop) - msg = "The behavior of DatetimeProperties.to_pydatetime is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = ser.dt.to_pydatetime() - assert isinstance(result, np.ndarray) + result = ser.dt.to_pydatetime() + assert isinstance(result, Series) assert result.dtype == object result = ser.dt.tz_convert("CET")
xref https://github.com/pandas-dev/pandas/pull/52459, https://github.com/pandas-dev/pandas/pull/54818
https://api.github.com/repos/pandas-dev/pandas/pulls/57425
2024-02-14T19:41:30Z
2024-02-20T01:21:52Z
2024-02-20T01:21:52Z
2024-02-27T17:45:37Z
ENH: Preserve Series index on `json_normalize`
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 012fe47c476d1..ab23f0adcb958 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -31,6 +31,7 @@ Other enhancements - :func:`DataFrame.to_excel` now raises an ``UserWarning`` when the character count in a cell exceeds Excel's limitation of 32767 characters (:issue:`56954`) - :func:`read_stata` now returns ``datetime64`` resolutions better matching those natively stored in the stata format (:issue:`55642`) - Allow dictionaries to be passed to :meth:`pandas.Series.str.replace` via ``pat`` parameter (:issue:`51748`) +- Support passing a :class:`Series` input to :func:`json_normalize` that retains the :class:`Series` :class:`Index` (:issue:`51452`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index 49f95430d9bb9..f784004487646 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -19,7 +19,10 @@ from pandas._libs.writers import convert_json_to_lines import pandas as pd -from pandas import DataFrame +from pandas import ( + DataFrame, + Series, +) if TYPE_CHECKING: from collections.abc import Iterable @@ -266,7 +269,7 @@ def _simple_json_normalize( def json_normalize( - data: dict | list[dict], + data: dict | list[dict] | Series, record_path: str | list | None = None, meta: str | list[str | list[str]] | None = None, meta_prefix: str | None = None, @@ -280,7 +283,7 @@ def json_normalize( Parameters ---------- - data : dict or list of dicts + data : dict, list of dicts, or Series of dicts Unserialized JSON objects. record_path : str or list of str, default None Path in each object to list of records. If not passed, data will be @@ -365,6 +368,26 @@ def json_normalize( 1 NaN Mark Reg 130 60 2 2.0 Faye Raker 130 60 + >>> data = [ + ... { + ... "id": 1, + ... "name": "Cole Volk", + ... "fitness": {"height": 130, "weight": 60}, + ... }, + ... {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}}, + ... { + ... "id": 2, + ... "name": "Faye Raker", + ... "fitness": {"height": 130, "weight": 60}, + ... }, + ... ] + >>> series = pd.Series(data, index=pd.Index(["a", "b", "c"])) + >>> pd.json_normalize(series) + id name fitness.height fitness.weight + a 1.0 Cole Volk 130 60 + b NaN Mark Reg 130 60 + c 2.0 Faye Raker 130 60 + >>> data = [ ... { ... "state": "Florida", @@ -455,6 +478,11 @@ def _pull_records(js: dict[str, Any], spec: list | str) -> list: ) return result + if isinstance(data, Series): + index = data.index + else: + index = None + if isinstance(data, list) and not data: return DataFrame() elif isinstance(data, dict): @@ -477,7 +505,7 @@ def _pull_records(js: dict[str, Any], spec: list | str) -> list: and record_prefix is None and max_level is None ): - return DataFrame(_simple_json_normalize(data, sep=sep)) + return DataFrame(_simple_json_normalize(data, sep=sep), index=index) if record_path is None: if any([isinstance(x, dict) for x in y.values()] for y in data): @@ -489,7 +517,7 @@ def _pull_records(js: dict[str, Any], spec: list | str) -> list: # TODO: handle record value which are lists, at least error # reasonably data = nested_to_record(data, sep=sep, max_level=max_level) - return DataFrame(data) + return DataFrame(data, index=index) elif not isinstance(record_path, list): record_path = [record_path] @@ -564,4 +592,6 @@ def _recursive_extract(data, path, seen_meta, level: int = 0) -> None: values[i] = val result[k] = values.repeat(lengths) + if index is not None: + result.index = index.repeat(lengths) return result diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 0f33883feba3a..d83e7b4641e88 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -561,6 +561,14 @@ def test_top_column_with_leading_underscore(self): tm.assert_frame_equal(result, expected) + def test_series_index(self, state_data): + idx = Index([7, 8]) + series = Series(state_data, index=idx) + result = json_normalize(series) + tm.assert_index_equal(result.index, idx) + result = json_normalize(series, "counties") + tm.assert_index_equal(result.index, idx.repeat([3, 2])) + class TestNestedToRecord: def test_flat_stays_flat(self): @@ -891,6 +899,7 @@ def test_series_non_zero_index(self): "elements.a": [1.0, np.nan, np.nan], "elements.b": [np.nan, 2.0, np.nan], "elements.c": [np.nan, np.nan, 3.0], - } + }, + index=[1, 2, 3], ) tm.assert_frame_equal(result, expected)
- [ ] closes #51452 - [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. Passing a Series as input to `json_normalize` was already functional before but undocumented as a feature, and had the issue linked above where it would not preserve the index of the input series.
https://api.github.com/repos/pandas-dev/pandas/pulls/57422
2024-02-14T18:06:34Z
2024-02-14T21:12:56Z
2024-02-14T21:12:56Z
2024-02-14T22:27:33Z
DOC: Resolve SA05 errors for all ExponentialMovingWindow, Expanding, Rolling, and Window
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 51257e6ef4258..054a4b3c79411 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -1433,52 +1433,9 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.core.groupby.SeriesGroupBy.last\ pandas.core.resample.Resampler.first\ pandas.core.resample.Resampler.last\ - pandas.core.window.ewm.ExponentialMovingWindow.corr\ - pandas.core.window.ewm.ExponentialMovingWindow.cov\ - pandas.core.window.ewm.ExponentialMovingWindow.mean\ - pandas.core.window.ewm.ExponentialMovingWindow.std\ - pandas.core.window.ewm.ExponentialMovingWindow.sum\ - pandas.core.window.ewm.ExponentialMovingWindow.var\ pandas.core.window.expanding.Expanding.aggregate\ - pandas.core.window.expanding.Expanding.apply\ - pandas.core.window.expanding.Expanding.corr\ - pandas.core.window.expanding.Expanding.count\ - pandas.core.window.expanding.Expanding.cov\ - pandas.core.window.expanding.Expanding.kurt\ - pandas.core.window.expanding.Expanding.max\ - pandas.core.window.expanding.Expanding.mean\ - pandas.core.window.expanding.Expanding.median\ - pandas.core.window.expanding.Expanding.min\ - pandas.core.window.expanding.Expanding.quantile\ - pandas.core.window.expanding.Expanding.rank\ - pandas.core.window.expanding.Expanding.sem\ - pandas.core.window.expanding.Expanding.skew\ - pandas.core.window.expanding.Expanding.std\ - pandas.core.window.expanding.Expanding.sum\ - pandas.core.window.expanding.Expanding.var\ pandas.core.window.rolling.Rolling.aggregate\ - pandas.core.window.rolling.Rolling.apply\ - pandas.core.window.rolling.Rolling.corr\ - pandas.core.window.rolling.Rolling.count\ - pandas.core.window.rolling.Rolling.cov\ - pandas.core.window.rolling.Rolling.kurt\ - pandas.core.window.rolling.Rolling.max\ - pandas.core.window.rolling.Rolling.mean\ - pandas.core.window.rolling.Rolling.median\ - pandas.core.window.rolling.Rolling.min\ - pandas.core.window.rolling.Rolling.quantile\ - pandas.core.window.rolling.Rolling.rank\ - pandas.core.window.rolling.Rolling.sem\ - pandas.core.window.rolling.Rolling.skew\ - pandas.core.window.rolling.Rolling.std\ - pandas.core.window.rolling.Rolling.sum\ - pandas.core.window.rolling.Rolling.var\ - pandas.core.window.rolling.Window.mean\ - pandas.core.window.rolling.Window.std\ - pandas.core.window.rolling.Window.sum\ - pandas.core.window.rolling.Window.var\ pandas.plotting.bootstrap_plot\ - pandas.plotting.boxplot\ pandas.plotting.radviz # There should be no backslash in the final line, please keep this comment in the last ignored function RET=$(($RET + $?)) ; echo $MSG "DONE" diff --git a/pandas/core/window/doc.py b/pandas/core/window/doc.py index 2a5cbc04921fa..c3ccb471c973e 100644 --- a/pandas/core/window/doc.py +++ b/pandas/core/window/doc.py @@ -24,10 +24,10 @@ def create_section_header(header: str) -> str: template_see_also = dedent( """ - pandas.Series.{window_method} : Calling {window_method} with Series data. - pandas.DataFrame.{window_method} : Calling {window_method} with DataFrames. - pandas.Series.{agg_method} : Aggregating {agg_method} for Series. - pandas.DataFrame.{agg_method} : Aggregating {agg_method} for DataFrame.\n + Series.{window_method} : Calling {window_method} with Series data. + DataFrame.{window_method} : Calling {window_method} with DataFrames. + Series.{agg_method} : Aggregating {agg_method} for Series. + DataFrame.{agg_method} : Aggregating {agg_method} for DataFrame.\n """ ).replace("\n", "", 1)
A small change in a shared template resolved all SA05 errors for the following: ``` pandas.core.window.ewm.ExponentialMovingWindow.corr pandas.core.window.ewm.ExponentialMovingWindow.cov pandas.core.window.ewm.ExponentialMovingWindow.mean pandas.core.window.ewm.ExponentialMovingWindow.std pandas.core.window.ewm.ExponentialMovingWindow.sum pandas.core.window.ewm.ExponentialMovingWindow.var pandas.core.window.expanding.Expanding.apply pandas.core.window.expanding.Expanding.corr pandas.core.window.expanding.Expanding.count pandas.core.window.expanding.Expanding.cov pandas.core.window.expanding.Expanding.kurt pandas.core.window.expanding.Expanding.max pandas.core.window.expanding.Expanding.mean pandas.core.window.expanding.Expanding.median pandas.core.window.expanding.Expanding.min pandas.core.window.expanding.Expanding.quantile pandas.core.window.expanding.Expanding.rank pandas.core.window.expanding.Expanding.sem pandas.core.window.expanding.Expanding.skew pandas.core.window.expanding.Expanding.std pandas.core.window.expanding.Expanding.sum pandas.core.window.expanding.Expanding.var pandas.core.window.rolling.Rolling.apply pandas.core.window.rolling.Rolling.corr pandas.core.window.rolling.Rolling.count pandas.core.window.rolling.Rolling.cov pandas.core.window.rolling.Rolling.kurt pandas.core.window.rolling.Rolling.max pandas.core.window.rolling.Rolling.mean pandas.core.window.rolling.Rolling.median pandas.core.window.rolling.Rolling.min pandas.core.window.rolling.Rolling.quantile pandas.core.window.rolling.Rolling.rank pandas.core.window.rolling.Rolling.sem pandas.core.window.rolling.Rolling.skew pandas.core.window.rolling.Rolling.std pandas.core.window.rolling.Rolling.sum pandas.core.window.rolling.Rolling.var pandas.core.window.rolling.Window.mean pandas.core.window.rolling.Window.std pandas.core.window.rolling.Window.sum pandas.core.window.rolling.Window.var pandas.plotting.boxplot ``` - [x] xref #57392 - [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.
https://api.github.com/repos/pandas-dev/pandas/pulls/57415
2024-02-14T04:33:49Z
2024-02-14T14:49:22Z
2024-02-14T14:49:22Z
2024-02-14T17:26:56Z
DOC: fix SA05 errors in docstring for pandas.core.groupby.DataFrameGroupBy - first, last
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 51257e6ef4258..9ab6fdf4a6d86 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -1427,8 +1427,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then MSG='Partially validate docstrings (SA05)' ; echo $MSG $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=SA05 --ignore_functions \ - pandas.core.groupby.DataFrameGroupBy.first\ - pandas.core.groupby.DataFrameGroupBy.last\ pandas.core.groupby.SeriesGroupBy.first\ pandas.core.groupby.SeriesGroupBy.last\ pandas.core.resample.Resampler.first\ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 1be1cdfcd0f50..103f7b55c0550 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3219,9 +3219,9 @@ def first( -------- DataFrame.groupby : Apply a function groupby to each row or column of a DataFrame. - pandas.core.groupby.DataFrameGroupBy.last : Compute the last non-null entry + core.groupby.DataFrameGroupBy.last : Compute the last non-null entry of each column. - pandas.core.groupby.DataFrameGroupBy.nth : Take the nth row from each group. + core.groupby.DataFrameGroupBy.nth : Take the nth row from each group. Examples -------- @@ -3306,9 +3306,9 @@ def last( -------- DataFrame.groupby : Apply a function groupby to each row or column of a DataFrame. - pandas.core.groupby.DataFrameGroupBy.first : Compute the first non-null entry + core.groupby.DataFrameGroupBy.first : Compute the first non-null entry of each column. - pandas.core.groupby.DataFrameGroupBy.nth : Take the nth row from each group. + core.groupby.DataFrameGroupBy.nth : Take the nth row from each group. Examples --------
- [x] xref #57392 - [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. fixing SA05 errors in docstrings for: pandas.core.groupby.DataFrameGroupBy.first pandas.core.groupby.DataFrameGroupBy.last
https://api.github.com/repos/pandas-dev/pandas/pulls/57414
2024-02-14T02:29:31Z
2024-02-14T17:08:27Z
2024-02-14T17:08:27Z
2024-02-14T17:08:35Z
Backport PR #57388 on branch 2.2.x (BUG: map(na_action=ignore) not respected for Arrow & masked types)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 94e26ff6aa46a..9733aff0e6eb5 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :meth:`CategoricalIndex.difference` raising ``KeyError`` when other contains null values other than NaN (:issue:`57318`) - Fixed regression in :meth:`DataFrame.groupby` raising ``ValueError`` when grouping by a :class:`Series` in some cases (:issue:`57276`) - Fixed regression in :meth:`DataFrame.loc` raising ``IndexError`` for non-unique, masked dtype indexes where result has more than 10,000 rows (:issue:`57027`) +- Fixed regression in :meth:`DataFrame.map` with ``na_action="ignore"`` not being respected for NumPy nullable and :class:`ArrowDtypes` (:issue:`57316`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) - Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) - Fixed regression in :meth:`DataFrame.sort_index` not producing a stable sort for a index with duplicates (:issue:`57151`) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 621a32a049f3b..f8b07bd73d315 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -1414,7 +1414,7 @@ def to_numpy( def map(self, mapper, na_action=None): if is_numeric_dtype(self.dtype): - return map_array(self.to_numpy(), mapper, na_action=None) + return map_array(self.to_numpy(), mapper, na_action=na_action) else: return super().map(mapper, na_action) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 7c49ce5343158..0bc0d9f8d7a7d 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -1333,7 +1333,7 @@ def max(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs): return self._wrap_reduction_result("max", result, skipna=skipna, axis=axis) def map(self, mapper, na_action=None): - return map_array(self.to_numpy(), mapper, na_action=None) + return map_array(self.to_numpy(), mapper, na_action=na_action) def any(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs): """ diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index e041093bbf5bc..d9a3033b8380e 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -3379,3 +3379,10 @@ def test_to_numpy_timestamp_to_int(): result = ser.to_numpy(dtype=np.int64) expected = np.array([1577853000000000000]) tm.assert_numpy_array_equal(result, expected) + + +def test_map_numeric_na_action(): + ser = pd.Series([32, 40, None], dtype="int64[pyarrow]") + result = ser.map(lambda x: 42, na_action="ignore") + expected = pd.Series([42.0, 42.0, np.nan], dtype="float64") + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/test_masked.py b/pandas/tests/extension/test_masked.py index 3efc561d6a125..651f783b44d1f 100644 --- a/pandas/tests/extension/test_masked.py +++ b/pandas/tests/extension/test_masked.py @@ -179,6 +179,15 @@ def test_map(self, data_missing, na_action): expected = data_missing.to_numpy() tm.assert_numpy_array_equal(result, expected) + def test_map_na_action_ignore(self, data_missing_for_sorting): + zero = data_missing_for_sorting[2] + result = data_missing_for_sorting.map(lambda x: zero, na_action="ignore") + if data_missing_for_sorting.dtype.kind == "b": + expected = np.array([False, pd.NA, False], dtype=object) + else: + expected = np.array([zero, np.nan, zero]) + tm.assert_numpy_array_equal(result, expected) + def _get_expected_exception(self, op_name, obj, other): try: dtype = tm.get_dtype(obj)
Backport PR #57388: BUG: map(na_action=ignore) not respected for Arrow & masked types
https://api.github.com/repos/pandas-dev/pandas/pulls/57413
2024-02-14T00:49:58Z
2024-02-14T02:12:17Z
2024-02-14T02:12:17Z
2024-02-14T02:12:17Z
Remove downcast from Index.fillna
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index d9f545969d9f7..662bf04595026 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2559,7 +2559,7 @@ def notna(self) -> npt.NDArray[np.bool_]: notnull = notna - def fillna(self, value=None, downcast=lib.no_default): + def fillna(self, value=None): """ Fill NA/NaN values with the specified value. @@ -2568,12 +2568,6 @@ def fillna(self, value=None, downcast=lib.no_default): value : scalar Scalar value to use to fill holes (e.g. 0). This value cannot be a list-likes. - downcast : dict, default is None - A dict of item->dtype of what to downcast if possible, - or the string 'infer' which will try to downcast to an appropriate - equal type (e.g. float64 to int64 if possible). - - .. deprecated:: 2.1.0 Returns ------- @@ -2592,28 +2586,13 @@ def fillna(self, value=None, downcast=lib.no_default): """ if not is_scalar(value): raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}") - if downcast is not lib.no_default: - warnings.warn( - f"The 'downcast' keyword in {type(self).__name__}.fillna is " - "deprecated and will be removed in a future version. " - "It was previously silently ignored.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - downcast = None if self.hasnans: result = self.putmask(self._isnan, value) - if downcast is None: - # no need to care metadata other than name - # because it can't have freq if it has NaTs - # _with_infer needed for test_fillna_categorical - return Index._with_infer(result, name=self.name) - raise NotImplementedError( - f"{type(self).__name__}.fillna does not support 'downcast' " - "argument values other than 'None'." - ) + # no need to care metadata other than name + # because it can't have freq if it has NaTs + # _with_infer needed for test_fillna_categorical + return Index._with_infer(result, name=self.name) return self._view() def dropna(self, how: AnyAll = "any") -> Self: diff --git a/pandas/tests/indexes/test_old_base.py b/pandas/tests/indexes/test_old_base.py index cc496dbee86d3..fa1b9f250f35f 100644 --- a/pandas/tests/indexes/test_old_base.py +++ b/pandas/tests/indexes/test_old_base.py @@ -597,13 +597,6 @@ def test_fillna(self, index): idx = type(index)(values) - msg = "does not support 'downcast'" - msg2 = r"The 'downcast' keyword in .*Index\.fillna is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg2): - with pytest.raises(NotImplementedError, match=msg): - # For now at least, we only raise if there are NAs present - idx.fillna(idx[0], downcast="infer") - expected = np.array([False] * len(idx), dtype=bool) expected[1] = True tm.assert_numpy_array_equal(idx._isnan, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. I think this is covered by the other whatsnews
https://api.github.com/repos/pandas-dev/pandas/pulls/57410
2024-02-14T00:03:23Z
2024-02-14T02:12:46Z
2024-02-14T02:12:46Z
2024-02-14T09:03:30Z
DOC: fix SA05 errors in docstrings for pandas.PeriodIndex.asfreq, arr…
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index bebe3b54d9457..10eb3034f4f7e 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -1155,9 +1155,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then MSG='Partially validate docstrings (SA05)' ; echo $MSG $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=SA05 --ignore_functions \ - pandas.PeriodIndex.asfreq\ - pandas.arrays.ArrowStringArray\ - pandas.arrays.StringArray\ pandas.core.groupby.DataFrameGroupBy.first\ pandas.core.groupby.DataFrameGroupBy.last\ pandas.core.groupby.SeriesGroupBy.first\ diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 5a803c9064db9..1b9f803bafc5d 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -315,7 +315,7 @@ class StringArray(BaseStringArray, NumpyExtensionArray): # type: ignore[misc] See Also -------- - :func:`pandas.array` + :func:`array` The recommended function for creating a StringArray. Series.str The string methods are available on Series backed by diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index ba02c63c00ce4..fc5ce33d641ee 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -105,7 +105,7 @@ class ArrowStringArray(ObjectStringArrayMixin, ArrowExtensionArray, BaseStringAr See Also -------- - :func:`pandas.array` + :func:`array` The recommended function for creating a ArrowStringArray. Series.str The string methods are available on Series backed by diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index a7315d40f0236..a970b949750a3 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -185,7 +185,7 @@ def _resolution_obj(self) -> Resolution: @doc( PeriodArray.asfreq, - other="pandas.arrays.PeriodArray", + other="arrays.PeriodArray", other_name="PeriodArray", **_shared_doc_kwargs, )
…ays - ArrowStringArray, StringArray - [x] xref #57392 - [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.
https://api.github.com/repos/pandas-dev/pandas/pulls/57408
2024-02-13T22:18:15Z
2024-02-14T02:13:30Z
2024-02-14T02:13:30Z
2024-02-14T04:13:20Z
CLN: Misc pre-COW stuff
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index b4cd6d82bb57f..5409c9b1fc0b9 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -72,7 +72,6 @@ get_obj, ) from pandas._testing.contexts import ( - assert_cow_warning, decompress_file, ensure_clean, raises_chained_assignment_error, @@ -583,7 +582,6 @@ def shares_memory(left, right) -> bool: "assert_series_equal", "assert_sp_array_equal", "assert_timedelta_array_equal", - "assert_cow_warning", "at", "BOOL_DTYPES", "box_expected", diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index 3570ebaeffed5..a04322cf97798 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -228,29 +228,3 @@ def raises_chained_assignment_error(warn=True, extra_warnings=(), extra_match=() warning, match="|".join((match, *extra_match)), ) - - -def assert_cow_warning(warn=True, match=None, **kwargs): - """ - Assert that a warning is raised in the CoW warning mode. - - Parameters - ---------- - warn : bool, default True - By default, check that a warning is raised. Can be turned off by passing False. - match : str - The warning message to match against, if different from the default. - kwargs - Passed through to assert_produces_warning - """ - from pandas._testing import assert_produces_warning - - if not warn: - from contextlib import nullcontext - - return nullcontext() - - if not match: - match = "Setting a value on a view" - - return assert_produces_warning(FutureWarning, match=match, **kwargs) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2e96366b2d17b..80c8a1e8ef5c7 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -131,29 +131,6 @@ _dtype_obj = np.dtype("object") -COW_WARNING_GENERAL_MSG = """\ -Setting a value on a view: behaviour will change in pandas 3.0. -You are mutating a Series or DataFrame object, and currently this mutation will -also have effect on other Series or DataFrame objects that share data with this -object. In pandas 3.0 (with Copy-on-Write), updating one Series or DataFrame object -will never modify another. -""" - - -COW_WARNING_SETITEM_MSG = """\ -Setting a value on a view: behaviour will change in pandas 3.0. -Currently, the mutation will also have effect on the object that shares data -with this object. For example, when setting a value in a Series that was -extracted from a column of a DataFrame, that DataFrame will also be updated: - - ser = df["col"] - ser[0] = 0 <--- in pandas 2, this also updates `df` - -In pandas 3.0 (with Copy-on-Write), updating one Series/DataFrame will never -modify another, and thus in the example above, `df` will not be changed. -""" - - def maybe_split(meth: F) -> F: """ If we have a multi-column block, split and operate block-wise. Otherwise diff --git a/pandas/errors/cow.py b/pandas/errors/cow.py index 9a3f6f4cc8efc..1e7829c88ae7e 100644 --- a/pandas/errors/cow.py +++ b/pandas/errors/cow.py @@ -22,33 +22,3 @@ "using 'df.method({col: value}, inplace=True)' instead, to perform " "the operation inplace on the original object.\n\n" ) - - -_chained_assignment_warning_msg = ( - "ChainedAssignmentError: behaviour will change in pandas 3.0!\n" - "You are setting values through chained assignment. Currently this works " - "in certain cases, but when using Copy-on-Write (which will become the " - "default behaviour in pandas 3.0) this will never work to update the " - "original DataFrame or Series, because the intermediate object on which " - "we are setting values will behave as a copy.\n" - "A typical example is when you are setting values in a column of a " - "DataFrame, like:\n\n" - 'df["col"][row_indexer] = value\n\n' - 'Use `df.loc[row_indexer, "col"] = values` instead, to perform the ' - "assignment in a single step and ensure this keeps updating the original `df`.\n\n" - "See the caveats in the documentation: " - "https://pandas.pydata.org/pandas-docs/stable/user_guide/" - "indexing.html#returning-a-view-versus-a-copy\n" -) - -_chained_assignment_warning_method_msg = ( - "A value is trying to be set on a copy of a DataFrame or Series " - "through chained assignment using an inplace method.\n" - "The behavior will change in pandas 3.0. This inplace method will " - "never work because the intermediate object on which we are setting " - "values always behaves as a copy.\n\n" - "For example, when doing 'df[col].method(value, inplace=True)', try " - "using 'df.method({col: value}, inplace=True)' or " - "df[col] = df[col].method(value) instead, to perform " - "the operation inplace on the original object.\n\n" -) diff --git a/pandas/tests/copy_view/test_chained_assignment_deprecation.py b/pandas/tests/copy_view/test_chained_assignment_deprecation.py index 76e3df4afb52c..4aef69a6fde98 100644 --- a/pandas/tests/copy_view/test_chained_assignment_deprecation.py +++ b/pandas/tests/copy_view/test_chained_assignment_deprecation.py @@ -7,7 +7,6 @@ import pandas._testing as tm -# TODO(CoW-warn) expand the cases @pytest.mark.parametrize( "indexer", [0, [0, 1], slice(0, 2), np.array([True, False, True])] ) diff --git a/pandas/tests/copy_view/test_core_functionalities.py b/pandas/tests/copy_view/test_core_functionalities.py index 70d7112ddbd89..ad16bafdf0ee4 100644 --- a/pandas/tests/copy_view/test_core_functionalities.py +++ b/pandas/tests/copy_view/test_core_functionalities.py @@ -46,7 +46,7 @@ def test_setitem_with_view_invalidated_does_not_copy(request): df["b"] = 100 arr = get_array(df, "a") view = None # noqa: F841 - # TODO(CoW-warn) false positive? -> block gets split because of `df["b"] = 100` + # TODO(CoW) block gets split because of `df["b"] = 100` # which introduces additional refs, even when those of `view` go out of scopes df.iloc[0, 0] = 100 # Setitem split the block. Since the old block shared data with view diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 1e4897368cc7a..64f46f218d2b3 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -218,7 +218,7 @@ def test_fillna_copy_frame(self, data_missing): super().test_fillna_copy_frame(data_missing) @pytest.mark.xfail(reason="Fails with CoW") - def test_equals_same_data_different_object(self, data, request): + def test_equals_same_data_different_object(self, data): super().test_equals_same_data_different_object(data) @pytest.mark.xfail(reason="failing on np.array(self, dtype=str)") diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 97176b20376ff..59bdd43d48ba0 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -321,7 +321,6 @@ def test_setitem(self, float_frame, using_infer_string): # so raise/warn smaller = float_frame[:2] - # With CoW, adding a new column doesn't raise a warning smaller["col10"] = ["1", "2"] if using_infer_string: diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 1b6e1341a9c40..abf89c2b0d096 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -207,8 +207,6 @@ def test_multiindex_assignment_single_dtype(self): ) # arr can be losslessly cast to int, so this setitem is inplace - # INFO(CoW-warn) this does not warn because we directly took .values - # above, so no reference to a pandas object is alive for `view` df.loc[4, "c"] = arr exp = Series(arr, index=[8, 10], name="c", dtype="int64") result = df.loc[4, "c"] diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 718ea69960775..c9e0aa2ffd77c 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -324,7 +324,6 @@ def test_detect_chained_assignment_warning_stacklevel(self, rhs): df = DataFrame(np.arange(25).reshape(5, 5)) df_original = df.copy() chained = df.loc[:3] - # INFO(CoW) no warning, and original dataframe not changed chained[2] = rhs tm.assert_frame_equal(df, df_original) diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py index ce95f5a76e0cc..fd8963ad85abc 100755 --- a/scripts/validate_unwanted_patterns.py +++ b/scripts/validate_unwanted_patterns.py @@ -49,9 +49,6 @@ "_global_config", "_chained_assignment_msg", "_chained_assignment_method_msg", - "_chained_assignment_warning_msg", - "_chained_assignment_warning_method_msg", - "_check_cacher", "_version_meson", # The numba extensions need this to mock the iloc object "_iLocIndexer",
null
https://api.github.com/repos/pandas-dev/pandas/pulls/57406
2024-02-13T20:48:48Z
2024-02-13T23:00:41Z
2024-02-13T23:00:41Z
2024-02-13T23:00:44Z
CLN: Enforce nonkeyword deprecations
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index e07ee3cbe2867..58292ae0ee4de 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -105,7 +105,10 @@ Deprecations Removal of prior version deprecations/changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :func:`read_excel`, :func:`read_json`, :func:`read_html`, and :func:`read_xml` no longer accept raw string or byte representation of the data. That type of data must be wrapped in a :py:class:`StringIO` or :py:class:`BytesIO` (:issue:`53767`) +- All arguments except ``name`` in :meth:`Index.rename` are now keyword only (:issue:`56493`) - All arguments except the first ``path``-like argument in IO writers are now keyword only (:issue:`54229`) +- All arguments in :meth:`Index.sort_values` are now keyword only (:issue:`56493`) +- All arguments in :meth:`Series.to_dict` are now keyword only (:issue:`56493`) - Changed the default value of ``observed`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` to ``True`` (:issue:`51811`) - Enforced silent-downcasting deprecation for :ref:`all relevant methods <whatsnew_220.silent_downcasting>` (:issue:`54710`) - Removed ``DataFrame.applymap``, ``Styler.applymap`` and ``Styler.applymap_index`` (:issue:`52364`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 76c5549fc8f86..06b38fff57198 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -63,7 +63,6 @@ from pandas.util._decorators import ( Appender, Substitution, - deprecate_nonkeyword_arguments, doc, ) from pandas.util._exceptions import ( @@ -3195,9 +3194,6 @@ def to_xml( ) -> None: ... - @deprecate_nonkeyword_arguments( - version="3.0", allowed_args=["self", "path_or_buffer"], name="to_xml" - ) @doc( storage_options=_shared_docs["storage_options"], compression_options=_shared_docs["compression_options"] % "path_or_buffer", @@ -3205,6 +3201,7 @@ def to_xml( def to_xml( self, path_or_buffer: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None, + *, index: bool = True, root_name: str | None = "data", row_name: str | None = "row", diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index d9f545969d9f7..96f52cb5be3c0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -71,7 +71,6 @@ from pandas.util._decorators import ( Appender, cache_readonly, - deprecate_nonkeyword_arguments, doc, ) from pandas.util._exceptions import ( @@ -1891,10 +1890,7 @@ def rename(self, name, *, inplace: Literal[False] = ...) -> Self: def rename(self, name, *, inplace: Literal[True]) -> None: ... - @deprecate_nonkeyword_arguments( - version="3.0", allowed_args=["self", "name"], name="rename" - ) - def rename(self, name, inplace: bool = False) -> Self | None: + def rename(self, name, *, inplace: bool = False) -> Self | None: """ Alter Index or MultiIndex name. @@ -5503,11 +5499,9 @@ def sort_values( ) -> Self | tuple[Self, np.ndarray]: ... - @deprecate_nonkeyword_arguments( - version="3.0", allowed_args=["self"], name="sort_values" - ) def sort_values( self, + *, return_indexer: bool = False, ascending: bool = True, na_position: NaPosition = "last", diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 597832e51d122..a8e8ae140041a 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -27,7 +27,6 @@ from pandas.compat.numpy import function as nv from pandas.util._decorators import ( cache_readonly, - deprecate_nonkeyword_arguments, doc, ) @@ -592,11 +591,9 @@ def sort_values( ) -> Self | tuple[Self, np.ndarray | RangeIndex]: ... - @deprecate_nonkeyword_arguments( - version="3.0", allowed_args=["self"], name="sort_values" - ) def sort_values( self, + *, return_indexer: bool = False, ascending: bool = True, na_position: NaPosition = "last", diff --git a/pandas/core/series.py b/pandas/core/series.py index de76c05ef7943..1672c29f15763 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -46,7 +46,6 @@ from pandas.util._decorators import ( Appender, Substitution, - deprecate_nonkeyword_arguments, doc, ) from pandas.util._exceptions import find_stack_level @@ -1736,11 +1735,9 @@ def to_dict(self, *, into: type[dict] = ...) -> dict: # error: Incompatible default for argument "into" (default has type "type[ # dict[Any, Any]]", argument has type "type[MutableMappingT] | MutableMappingT") - @deprecate_nonkeyword_arguments( - version="3.0", allowed_args=["self"], name="to_dict" - ) def to_dict( self, + *, into: type[MutableMappingT] | MutableMappingT = dict, # type: ignore[assignment] ) -> MutableMappingT: """
xref https://github.com/pandas-dev/pandas/pull/56493
https://api.github.com/repos/pandas-dev/pandas/pulls/57405
2024-02-13T19:55:52Z
2024-02-14T00:46:53Z
2024-02-14T00:46:53Z
2024-02-14T02:11:06Z
DOC: fix SA05 errors in docstring for pandas.DataFrame - agg, aggregate, boxplot
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 39ccf904858d5..d3a79779bb369 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -143,9 +143,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then MSG='Partially validate docstrings (SA05)' ; echo $MSG $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=SA05 --ignore_functions \ - pandas.DataFrame.agg\ - pandas.DataFrame.aggregate\ - pandas.DataFrame.boxplot\ pandas.PeriodIndex.asfreq\ pandas.arrays.ArrowStringArray\ pandas.arrays.StringArray\ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 76c5549fc8f86..927518b766cc2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9752,11 +9752,11 @@ def _gotitem( -------- DataFrame.apply : Perform any type of operations. DataFrame.transform : Perform transformation type operations. - pandas.DataFrame.groupby : Perform operations over groups. - pandas.DataFrame.resample : Perform operations over resampled bins. - pandas.DataFrame.rolling : Perform operations over rolling window. - pandas.DataFrame.expanding : Perform operations over expanding window. - pandas.core.window.ewm.ExponentialMovingWindow : Perform operation over exponential + DataFrame.groupby : Perform operations over groups. + DataFrame.resample : Perform operations over resampled bins. + DataFrame.rolling : Perform operations over rolling window. + DataFrame.expanding : Perform operations over expanding window. + core.window.ewm.ExponentialMovingWindow : Perform operation over exponential weighted window. """ ) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 941022389c00a..edd619c264c7a 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -335,7 +335,7 @@ def hist_frame( See Also -------- -pandas.Series.plot.hist: Make a histogram. +Series.plot.hist: Make a histogram. matplotlib.pyplot.boxplot : Matplotlib equivalent plot. Notes
All SA05 Errors resolved in the following cases: 1. scripts/validate_docstrings.py --format=actions --errors=SA05 pandas.DataFrame.agg 2. scripts/validate_docstrings.py --format=actions --errors=SA05 pandas.DataFrame.aggregate 3. scripts/validate_docstrings.py --format=actions --errors=SA05 pandas.DataFrame.boxplot - [x] xref https://github.com/pandas-dev/pandas/issues/57392 - [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.
https://api.github.com/repos/pandas-dev/pandas/pulls/57404
2024-02-13T18:41:13Z
2024-02-13T19:56:34Z
2024-02-13T19:56:34Z
2024-02-13T20:04:58Z
BUG: wrong future Warning on string assignment in certain condition
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 9733aff0e6eb5..5e814ec2a1b92 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :meth:`CategoricalIndex.difference` raising ``KeyError`` when other contains null values other than NaN (:issue:`57318`) - Fixed regression in :meth:`DataFrame.groupby` raising ``ValueError`` when grouping by a :class:`Series` in some cases (:issue:`57276`) - Fixed regression in :meth:`DataFrame.loc` raising ``IndexError`` for non-unique, masked dtype indexes where result has more than 10,000 rows (:issue:`57027`) +- Fixed regression in :meth:`DataFrame.loc` which was unnecessarily throwing "incompatible dtype warning" when expanding with partial row indexer and multiple columns (see `PDEP6 <https://pandas.pydata.org/pdeps/0006-ban-upcasting.html>`_) (:issue:`56503`) - Fixed regression in :meth:`DataFrame.map` with ``na_action="ignore"`` not being respected for NumPy nullable and :class:`ArrowDtypes` (:issue:`57316`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) - Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 17c1ad5e4d8d9..9e00eb657f800 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -646,6 +646,20 @@ def infer_fill_value(val): return np.nan +def construct_1d_array_from_inferred_fill_value( + value: object, length: int +) -> ArrayLike: + # Find our empty_value dtype by constructing an array + # from our value and doing a .take on it + from pandas.core.algorithms import take_nd + from pandas.core.construction import sanitize_array + from pandas.core.indexes.base import Index + + arr = sanitize_array(value, Index(range(1)), copy=False) + taker = -1 * np.ones(length, dtype=np.intp) + return take_nd(arr, taker) + + def maybe_fill(arr: np.ndarray) -> np.ndarray: """ Fill numpy.ndarray with NaN, unless we have a integer or boolean dtype. diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index c6759a9f54509..c7a938dbc4449 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -50,6 +50,7 @@ ABCSeries, ) from pandas.core.dtypes.missing import ( + construct_1d_array_from_inferred_fill_value, infer_fill_value, is_valid_na_for_dtype, isna, @@ -61,7 +62,6 @@ from pandas.core.construction import ( array as pd_array, extract_array, - sanitize_array, ) from pandas.core.indexers import ( check_array_indexer, @@ -854,7 +854,6 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None: if self.ndim != 2: return - orig_key = key if isinstance(key, tuple) and len(key) > 1: # key may be a tuple if we are .loc # if length of key is > 1 set key to column part @@ -872,7 +871,7 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None: keys = self.obj.columns.union(key, sort=False) diff = Index(key).difference(self.obj.columns, sort=False) - if len(diff) and com.is_null_slice(orig_key[0]): + if len(diff): # e.g. if we are doing df.loc[:, ["A", "B"]] = 7 and "B" # is a new column, add the new columns with dtype=np.void # so that later when we go through setitem_single_column @@ -1878,12 +1877,9 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc") -> None: self.obj[key] = empty_value elif not is_list_like(value): - # Find our empty_value dtype by constructing an array - # from our value and doing a .take on it - arr = sanitize_array(value, Index(range(1)), copy=False) - taker = -1 * np.ones(len(self.obj), dtype=np.intp) - empty_value = algos.take_nd(arr, taker) - self.obj[key] = empty_value + self.obj[key] = construct_1d_array_from_inferred_fill_value( + value, len(self.obj) + ) else: # FIXME: GH#42099#issuecomment-864326014 self.obj[key] = infer_fill_value(value) @@ -2165,6 +2161,17 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None: else: # set value into the column (first attempting to operate inplace, then # falling back to casting if necessary) + dtype = self.obj.dtypes.iloc[loc] + if dtype == np.void: + # This means we're expanding, with multiple columns, e.g. + # df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]}) + # df.loc[df.index <= 2, ['F', 'G']] = (1, 'abc') + # Columns F and G will initially be set to np.void. + # Here, we replace those temporary `np.void` columns with + # columns of the appropriate dtype, based on `value`. + self.obj.iloc[:, loc] = construct_1d_array_from_inferred_fill_value( + value, len(self.obj) + ) self.obj._mgr.column_setitem(loc, plane_indexer, value) def _setitem_single_block(self, indexer, value, name: str) -> None: diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 20e7651f8af83..658fafd3ea2cc 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -1369,3 +1369,19 @@ def test_full_setter_loc_incompatible_dtype(): df.loc[:, "a"] = {0: 3, 1: 4} expected = DataFrame({"a": [3, 4]}) tm.assert_frame_equal(df, expected) + + +def test_setitem_partial_row_multiple_columns(): + # https://github.com/pandas-dev/pandas/issues/56503 + df = DataFrame({"A": [1, 2, 3], "B": [4.0, 5, 6]}) + # should not warn + df.loc[df.index <= 1, ["F", "G"]] = (1, "abc") + expected = DataFrame( + { + "A": [1, 2, 3], + "B": [4.0, 5, 6], + "F": [1.0, 1, float("nan")], + "G": ["abc", "abc", float("nan")], + } + ) + tm.assert_frame_equal(df, expected)
- [ ] closes #56503 (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. is this it? finally? 🤞
https://api.github.com/repos/pandas-dev/pandas/pulls/57402
2024-02-13T14:41:08Z
2024-02-16T17:57:46Z
2024-02-16T17:57:46Z
2024-02-16T17:57:55Z
Fix for issue #57268 - ENH: Preserve input start/end type in interval…
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 2ada386f76b87..941ad4612b73c 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -211,7 +211,7 @@ Strings Interval ^^^^^^^^ -- +- Bug in :func:`interval_range` where start and end numeric types were always cast to 64 bit (:issue:`57268`) - Indexing diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 46d1ee49c22a0..7695193a15608 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1101,9 +1101,23 @@ def interval_range( breaks: np.ndarray | TimedeltaIndex | DatetimeIndex if is_number(endpoint): + dtype: np.dtype = np.dtype("int64") if com.all_not_none(start, end, freq): + if ( + isinstance(start, (float, np.float16)) + or isinstance(end, (float, np.float16)) + or isinstance(freq, (float, np.float16)) + ): + dtype = np.dtype("float64") + elif ( + isinstance(start, (np.integer, np.floating)) + and isinstance(end, (np.integer, np.floating)) + and start.dtype == end.dtype + ): + dtype = start.dtype # 0.1 ensures we capture end breaks = np.arange(start, end + (freq * 0.1), freq) + breaks = maybe_downcast_numeric(breaks, dtype) else: # compute the period/start/end if unspecified (at most one) if periods is None: @@ -1122,7 +1136,7 @@ def interval_range( # expected "ndarray[Any, Any]" [ breaks = maybe_downcast_numeric( breaks, # type: ignore[arg-type] - np.dtype("int64"), + dtype, ) else: # delegate to the appropriate range function @@ -1131,4 +1145,9 @@ def interval_range( else: breaks = timedelta_range(start=start, end=end, periods=periods, freq=freq) - return IntervalIndex.from_breaks(breaks, name=name, closed=closed) + return IntervalIndex.from_breaks( + breaks, + name=name, + closed=closed, + dtype=IntervalDtype(subtype=breaks.dtype, closed=closed), + ) diff --git a/pandas/tests/indexes/interval/test_interval_range.py b/pandas/tests/indexes/interval/test_interval_range.py index e8de59f84bcc6..7aea481b49221 100644 --- a/pandas/tests/indexes/interval/test_interval_range.py +++ b/pandas/tests/indexes/interval/test_interval_range.py @@ -220,6 +220,20 @@ def test_float_subtype(self, start, end, freq): expected = "int64" if is_integer(start + end) else "float64" assert result == expected + @pytest.mark.parametrize( + "start, end, expected", + [ + (np.int8(1), np.int8(10), np.dtype("int8")), + (np.int8(1), np.float16(10), np.dtype("float64")), + (np.float32(1), np.float32(10), np.dtype("float32")), + (1, 10, np.dtype("int64")), + (1, 10.0, np.dtype("float64")), + ], + ) + def test_interval_dtype(self, start, end, expected): + result = interval_range(start=start, end=end).dtype.subtype + assert result == expected + def test_interval_range_fractional_period(self): # float value for periods expected = interval_range(start=0, periods=10)
…_range - [ ] closes #57268 - [ ] [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/57399
2024-02-13T09:28:49Z
2024-02-15T17:35:06Z
2024-02-15T17:35:06Z
2024-02-15T17:57:56Z
TST: Fix test_str_encode on big endian machines
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 30a504ebd0e0b..f441ecfff02d4 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -26,6 +26,7 @@ import operator import pickle import re +import sys import numpy as np import pytest @@ -2172,14 +2173,21 @@ def test_str_removeprefix(val): @pytest.mark.parametrize( "encoding, exp", [ - ["utf8", b"abc"], - ["utf32", b"\xff\xfe\x00\x00a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00"], + ("utf8", {"little": b"abc", "big": "abc"}), + ( + "utf32", + { + "little": b"\xff\xfe\x00\x00a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00", + "big": b"\x00\x00\xfe\xff\x00\x00\x00a\x00\x00\x00b\x00\x00\x00c", + }, + ), ], + ids=["utf8", "utf32"], ) def test_str_encode(errors, encoding, exp): ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string())) result = ser.str.encode(encoding, errors) - expected = pd.Series([exp, None], dtype=ArrowDtype(pa.binary())) + expected = pd.Series([exp[sys.byteorder], None], dtype=ArrowDtype(pa.binary())) tm.assert_series_equal(result, expected)
I couldn't find a way to specify the endianness when creating the `ArrowDtype`, so just pick the right result based on native byte order. - [x] closes #57373 (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). - [n/a] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [n/a] 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/57394
2024-02-13T04:36:58Z
2024-02-13T17:09:52Z
2024-02-13T17:09:52Z
2024-02-13T23:20:58Z
TST: Fix IntervalIndex constructor tests on big-endian systems
diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index b0289ded55604..4a9eb4dd9fc0c 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -40,12 +40,12 @@ class ConstructorTests: (Index(np.arange(-10, 11, dtype=np.int64)), np.int64), (Index(np.arange(10, 31, dtype=np.uint64)), np.uint64), (Index(np.arange(20, 30, 0.5), dtype=np.float64), np.float64), - (date_range("20180101", periods=10), "<M8[ns]"), + (date_range("20180101", periods=10), "M8[ns]"), ( date_range("20180101", periods=10, tz="US/Eastern"), "datetime64[ns, US/Eastern]", ), - (timedelta_range("1 day", periods=10), "<m8[ns]"), + (timedelta_range("1 day", periods=10), "m8[ns]"), ], ) @pytest.mark.parametrize("name", [None, "foo"])
Two tests cases specify the expected data to be little-endian. However, none of the other cases do so, and the test creates native endian data, causing these tests to fail only in these specific cases. - [n/a] 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). - [n/a] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [n/a] 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/57393
2024-02-13T03:41:59Z
2024-02-13T17:23:46Z
2024-02-13T17:23:46Z
2024-02-13T23:20:35Z
TST: Ensure Matplotlib is always cleaned up
diff --git a/pandas/conftest.py b/pandas/conftest.py index 868bd365fa0ba..254d605e13460 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -28,6 +28,7 @@ timezone, ) from decimal import Decimal +import gc import operator import os from typing import ( @@ -1863,6 +1864,39 @@ def ip(): return InteractiveShell(config=c) +@pytest.fixture +def mpl_cleanup(): + """ + Ensure Matplotlib is cleaned up around a test. + + Before a test is run: + + 1) Set the backend to "template" to avoid requiring a GUI. + + After a test is run: + + 1) Reset units registry + 2) Reset rc_context + 3) Close all figures + + See matplotlib/testing/decorators.py#L24. + """ + mpl = pytest.importorskip("matplotlib") + mpl_units = pytest.importorskip("matplotlib.units") + plt = pytest.importorskip("matplotlib.pyplot") + orig_units_registry = mpl_units.registry.copy() + try: + with mpl.rc_context(): + mpl.use("template") + yield + finally: + mpl_units.registry.clear() + mpl_units.registry.update(orig_units_registry) + plt.close("all") + # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501 + gc.collect(1) + + @pytest.fixture( params=[ getattr(pd.offsets, o) diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py index ef7bfb11d81d8..70ddd65c02d14 100644 --- a/pandas/tests/io/formats/style/test_matplotlib.py +++ b/pandas/tests/io/formats/style/test_matplotlib.py @@ -1,5 +1,3 @@ -import gc - import numpy as np import pytest @@ -16,25 +14,7 @@ from pandas.io.formats.style import Styler - -@pytest.fixture(autouse=True) -def mpl_cleanup(): - # matplotlib/testing/decorators.py#L24 - # 1) Resets units registry - # 2) Resets rc_context - # 3) Closes all figures - mpl = pytest.importorskip("matplotlib") - mpl_units = pytest.importorskip("matplotlib.units") - plt = pytest.importorskip("matplotlib.pyplot") - orig_units_registry = mpl_units.registry.copy() - with mpl.rc_context(): - mpl.use("template") - yield - mpl_units.registry.clear() - mpl_units.registry.update(orig_units_registry) - plt.close("all") - # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501 - gc.collect(1) +pytestmark = pytest.mark.usefixtures("mpl_cleanup") @pytest.fixture diff --git a/pandas/tests/plotting/conftest.py b/pandas/tests/plotting/conftest.py index d688bbd47595c..eb5a1f1f6382e 100644 --- a/pandas/tests/plotting/conftest.py +++ b/pandas/tests/plotting/conftest.py @@ -1,5 +1,3 @@ -import gc - import numpy as np import pytest @@ -10,23 +8,8 @@ @pytest.fixture(autouse=True) -def mpl_cleanup(): - # matplotlib/testing/decorators.py#L24 - # 1) Resets units registry - # 2) Resets rc_context - # 3) Closes all figures - mpl = pytest.importorskip("matplotlib") - mpl_units = pytest.importorskip("matplotlib.units") - plt = pytest.importorskip("matplotlib.pyplot") - orig_units_registry = mpl_units.registry.copy() - with mpl.rc_context(): - mpl.use("template") - yield - mpl_units.registry.clear() - mpl_units.registry.update(orig_units_registry) - plt.close("all") - # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501 - gc.collect(1) +def autouse_mpl_cleanup(mpl_cleanup): + pass @pytest.fixture diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index ead36ee08b407..7186056f90299 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -155,7 +155,7 @@ def test_scikit_learn(): clf.predict(digits.data[-1:]) -def test_seaborn(): +def test_seaborn(mpl_cleanup): seaborn = pytest.importorskip("seaborn") tips = DataFrame( {"day": pd.date_range("2023", freq="D", periods=5), "total_bill": range(5)}
The seaborn test also uses Matplotlib but was not wrapped in the cleanup fixture, As there are now 3 files that need this fixture, refactor to reduce code duplication. The leftover figure from `test_seaborn` would cause a DeprecationWarning from Matplotlib 3.8 for closing the figures on the backend change (from the `mpl.use("template")` in the fixture), but this probably depends on if pytest chose to run it before the other tests or not. - [n/a] 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). - [n/a] 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/57389
2024-02-13T00:59:30Z
2024-02-13T02:54:54Z
2024-02-13T02:54:54Z
2024-02-13T03:18:26Z
BUG: map(na_action=ignore) not respected for Arrow & masked types
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index 94e26ff6aa46a..9733aff0e6eb5 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :meth:`CategoricalIndex.difference` raising ``KeyError`` when other contains null values other than NaN (:issue:`57318`) - Fixed regression in :meth:`DataFrame.groupby` raising ``ValueError`` when grouping by a :class:`Series` in some cases (:issue:`57276`) - Fixed regression in :meth:`DataFrame.loc` raising ``IndexError`` for non-unique, masked dtype indexes where result has more than 10,000 rows (:issue:`57027`) +- Fixed regression in :meth:`DataFrame.map` with ``na_action="ignore"`` not being respected for NumPy nullable and :class:`ArrowDtypes` (:issue:`57316`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) - Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) - Fixed regression in :meth:`DataFrame.sort_index` not producing a stable sort for a index with duplicates (:issue:`57151`) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 435d3e4751f6f..cbcc9b465762f 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -1430,7 +1430,7 @@ def to_numpy( def map(self, mapper, na_action=None): if is_numeric_dtype(self.dtype): - return map_array(self.to_numpy(), mapper, na_action=None) + return map_array(self.to_numpy(), mapper, na_action=na_action) else: return super().map(mapper, na_action) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 302ce996fb4f2..c1ed3dacb9a95 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -1335,7 +1335,7 @@ def max(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs): return self._wrap_reduction_result("max", result, skipna=skipna, axis=axis) def map(self, mapper, na_action=None): - return map_array(self.to_numpy(), mapper, na_action=None) + return map_array(self.to_numpy(), mapper, na_action=na_action) @overload def any( diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 30a504ebd0e0b..0e6fdb9598c1d 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -3489,3 +3489,10 @@ def test_to_numpy_timestamp_to_int(): result = ser.to_numpy(dtype=np.int64) expected = np.array([1577853000000000000]) tm.assert_numpy_array_equal(result, expected) + + +def test_map_numeric_na_action(): + ser = pd.Series([32, 40, None], dtype="int64[pyarrow]") + result = ser.map(lambda x: 42, na_action="ignore") + expected = pd.Series([42.0, 42.0, np.nan], dtype="float64") + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/test_masked.py b/pandas/tests/extension/test_masked.py index 3efc561d6a125..651f783b44d1f 100644 --- a/pandas/tests/extension/test_masked.py +++ b/pandas/tests/extension/test_masked.py @@ -179,6 +179,15 @@ def test_map(self, data_missing, na_action): expected = data_missing.to_numpy() tm.assert_numpy_array_equal(result, expected) + def test_map_na_action_ignore(self, data_missing_for_sorting): + zero = data_missing_for_sorting[2] + result = data_missing_for_sorting.map(lambda x: zero, na_action="ignore") + if data_missing_for_sorting.dtype.kind == "b": + expected = np.array([False, pd.NA, False], dtype=object) + else: + expected = np.array([zero, np.nan, zero]) + tm.assert_numpy_array_equal(result, expected) + def _get_expected_exception(self, op_name, obj, other): try: dtype = tm.get_dtype(obj)
```python In [5]: df = DataFrame({"a": [1, NA, 2], "b": [NA, 4, NA]}, dtype="Int64") In [6]: df.map(lambda x: 42, na_action="ignore") # pd.NA's lost Out[6]: a b 0 42 42 1 42 42 2 42 42 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/57388
2024-02-13T00:52:13Z
2024-02-14T00:49:24Z
2024-02-14T00:49:24Z
2024-02-14T02:11:13Z
CLN: Python 2 pickle/hdf support
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 0758d58ed3912..82b4ab6af0818 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -88,6 +88,7 @@ Other API changes ^^^^^^^^^^^^^^^^^ - 3rd party ``py.path`` objects are no longer explicitly supported in IO methods. Use :py:class:`pathlib.Path` objects instead (:issue:`57091`) - :attr:`MultiIndex.codes`, :attr:`MultiIndex.levels`, and :attr:`MultiIndex.names` now returns a ``tuple`` instead of a ``FrozenList`` (:issue:`53531`) +- pickle and HDF (``.h5``) files created with Python 2 are no longer explicitly supported (:issue:`57387`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py index d3e93ebeb8fbb..c565544075ecf 100644 --- a/pandas/io/pickle.py +++ b/pandas/io/pickle.py @@ -184,6 +184,7 @@ def read_pickle( 3 3 8 4 4 9 """ + # TypeError for Cython complaints about object.__new__ vs Tick.__new__ excs_to_catch = (AttributeError, ImportError, ModuleNotFoundError, TypeError) with get_handle( filepath_or_buffer, @@ -194,20 +195,14 @@ def read_pickle( ) as handles: # 1) try standard library Pickle # 2) try pickle_compat (older pandas version) to handle subclass changes - # 3) try pickle_compat with latin-1 encoding upon a UnicodeDecodeError try: - # TypeError for Cython complaints about object.__new__ vs Tick.__new__ - try: - with warnings.catch_warnings(record=True): - # We want to silence any warnings about, e.g. moved modules. - warnings.simplefilter("ignore", Warning) - return pickle.load(handles.handle) - except excs_to_catch: - # e.g. - # "No module named 'pandas.core.sparse.series'" - # "Can't get attribute '__nat_unpickle' on <module 'pandas._libs.tslib" - return pc.load(handles.handle, encoding=None) - except UnicodeDecodeError: - # e.g. can occur for files written in py27; see GH#28645 and GH#31988 - return pc.load(handles.handle, encoding="latin-1") + with warnings.catch_warnings(record=True): + # We want to silence any warnings about, e.g. moved modules. + warnings.simplefilter("ignore", Warning) + return pickle.load(handles.handle) + except excs_to_catch: + # e.g. + # "No module named 'pandas.core.sparse.series'" + # "Can't get attribute '__nat_unpickle' on <module 'pandas._libs.tslib" + return pc.load(handles.handle, encoding=None) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 97b9b905dfd62..4d6bf2d3d2ecd 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -132,13 +132,6 @@ _default_encoding = "UTF-8" -def _ensure_decoded(s): - """if we have bytes, decode them to unicode""" - if isinstance(s, np.bytes_): - s = s.decode("UTF-8") - return s - - def _ensure_encoding(encoding: str | None) -> str: # set the encoding if we need if encoding is None: @@ -1730,8 +1723,8 @@ def _create_storer( if value is not None and not isinstance(value, (Series, DataFrame)): raise TypeError("value must be None, Series, or DataFrame") - pt = _ensure_decoded(getattr(group._v_attrs, "pandas_type", None)) - tt = _ensure_decoded(getattr(group._v_attrs, "table_type", None)) + pt = getattr(group._v_attrs, "pandas_type", None) + tt = getattr(group._v_attrs, "table_type", None) # infer the pt from the passed value if pt is None: @@ -1798,7 +1791,7 @@ def _create_storer( "worm": WORMTable, } try: - cls = _TABLE_MAP[tt] + cls = _TABLE_MAP[tt] # type: ignore[index] except KeyError as err: raise TypeError( f"cannot properly create the storer for: [_TABLE_MAP] [group->" @@ -2145,13 +2138,13 @@ def convert( # preventing the original recarry from being free'ed values = values[self.cname].copy() - val_kind = _ensure_decoded(self.kind) + val_kind = self.kind values = _maybe_convert(values, val_kind, encoding, errors) kwargs = {} - kwargs["name"] = _ensure_decoded(self.index_name) + kwargs["name"] = self.index_name if self.freq is not None: - kwargs["freq"] = _ensure_decoded(self.freq) + kwargs["freq"] = self.freq factory: type[Index | DatetimeIndex] = Index if lib.is_np_dtype(values.dtype, "M") or isinstance( @@ -2210,7 +2203,7 @@ def maybe_set_size(self, min_itemsize=None) -> None: min_itemsize can be an integer or a dict with this columns name with an integer size """ - if _ensure_decoded(self.kind) == "string": + if self.kind == "string": if isinstance(min_itemsize, dict): min_itemsize = min_itemsize.get(self.name) @@ -2231,7 +2224,7 @@ def validate_and_set(self, handler: AppendableTable, append: bool) -> None: def validate_col(self, itemsize=None): """validate this column: return the compared against itemsize""" # validate this column for string truncation (or reset to the max size) - if _ensure_decoded(self.kind) == "string": + if self.kind == "string": c = self.col if c is not None: if itemsize is None: @@ -2561,14 +2554,14 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): assert isinstance(converted, np.ndarray) # for mypy # use the meta if needed - meta = _ensure_decoded(self.meta) + meta = self.meta metadata = self.metadata ordered = self.ordered tz = self.tz assert dtype_name is not None # convert to the correct dtype - dtype = _ensure_decoded(dtype_name) + dtype = dtype_name # reverse converts if dtype.startswith("datetime64"): @@ -2618,7 +2611,7 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): converted = converted.astype("O", copy=False) # convert nans / decode - if _ensure_decoded(kind) == "string": + if kind == "string": converted = _unconvert_string_array( converted, nan_rep=nan_rep, encoding=encoding, errors=errors ) @@ -2706,18 +2699,19 @@ def is_old_version(self) -> bool: @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: - version = tuple(int(x) for x in version.split(".")) - if len(version) == 2: - version = version + (0,) - except AttributeError: - version = (0, 0, 0) - return version + version = getattr(self.group._v_attrs, "pandas_version", None) + if isinstance(version, str): + version_tup = tuple(int(x) for x in version.split(".")) + if len(version_tup) == 2: + version_tup = version_tup + (0,) + assert len(version_tup) == 3 # needed for mypy + return version_tup + else: + return (0, 0, 0) @property def pandas_type(self): - return _ensure_decoded(getattr(self.group._v_attrs, "pandas_type", None)) + return getattr(self.group._v_attrs, "pandas_type", None) def __repr__(self) -> str: """return a pretty representation of myself""" @@ -2854,9 +2848,7 @@ def _alias_to_class(self, alias): return self._reverse_index_map.get(alias, Index) def _get_index_factory(self, attrs): - index_class = self._alias_to_class( - _ensure_decoded(getattr(attrs, "index_class", "")) - ) + index_class = self._alias_to_class(getattr(attrs, "index_class", "")) factory: Callable @@ -2892,12 +2884,7 @@ def f(values, freq=None, tz=None): factory = TimedeltaIndex if "tz" in attrs: - if isinstance(attrs["tz"], bytes): - # created by python2 - kwargs["tz"] = attrs["tz"].decode("utf-8") - else: - # created by python3 - kwargs["tz"] = attrs["tz"] + kwargs["tz"] = attrs["tz"] assert index_class is DatetimeIndex # just checking return factory, kwargs @@ -2929,9 +2916,9 @@ def set_attrs(self) -> None: def get_attrs(self) -> None: """retrieve our attributes""" self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None)) - self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict")) + self.errors = getattr(self.attrs, "errors", "strict") for n in self.attributes: - setattr(self, n, _ensure_decoded(getattr(self.attrs, n, None))) + setattr(self, n, getattr(self.attrs, n, None)) def write(self, obj, **kwargs) -> None: self.set_attrs() @@ -2948,7 +2935,7 @@ def read_array(self, key: str, start: int | None = None, stop: int | None = None if isinstance(node, tables.VLArray): ret = node[0][start:stop] else: - dtype = _ensure_decoded(getattr(attrs, "value_type", None)) + dtype = getattr(attrs, "value_type", None) shape = getattr(attrs, "shape", None) if shape is not None: @@ -2973,7 +2960,7 @@ def read_array(self, key: str, start: int | None = None, stop: int | None = None def read_index( self, key: str, start: int | None = None, stop: int | None = None ) -> Index: - variety = _ensure_decoded(getattr(self.attrs, f"{key}_variety")) + variety = getattr(self.attrs, f"{key}_variety") if variety == "multi": return self.read_multi_index(key, start=start, stop=stop) @@ -3063,12 +3050,11 @@ def read_index_node( # have written a sentinel. Here we replace it with the original. if "shape" in node._v_attrs and np.prod(node._v_attrs.shape) == 0: data = np.empty(node._v_attrs.shape, dtype=node._v_attrs.value_type) - kind = _ensure_decoded(node._v_attrs.kind) + kind = node._v_attrs.kind name = None if "name" in node._v_attrs: name = _ensure_str(node._v_attrs.name) - name = _ensure_decoded(name) attrs = node._v_attrs factory, kwargs = self._get_index_factory(attrs) @@ -3584,7 +3570,7 @@ def get_attrs(self) -> None: self.info = getattr(self.attrs, "info", None) or {} self.nan_rep = getattr(self.attrs, "nan_rep", None) self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None)) - self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict")) + self.errors = getattr(self.attrs, "errors", "strict") self.levels: list[Hashable] = getattr(self.attrs, "levels", None) or [] self.index_axes = [a for a in self.indexables if a.is_an_indexable] self.values_axes = [a for a in self.indexables if not a.is_an_indexable] @@ -4926,7 +4912,6 @@ def _set_tz( name = None values = values.ravel() - tz = _ensure_decoded(tz) values = DatetimeIndex(values, name=name) values = values.tz_localize("UTC").tz_convert(tz) elif coerce: @@ -5228,8 +5213,6 @@ def _dtype_to_kind(dtype_str: str) -> str: """ Find the "kind" string describing the given dtype name. """ - dtype_str = _ensure_decoded(dtype_str) - if dtype_str.startswith(("string", "bytes")): kind = "string" elif dtype_str.startswith("float"): diff --git a/pandas/tests/io/data/legacy_hdf/datetimetz_object.h5 b/pandas/tests/io/data/legacy_hdf/datetimetz_object.h5 deleted file mode 100644 index 8cb4eda470398..0000000000000 Binary files a/pandas/tests/io/data/legacy_hdf/datetimetz_object.h5 and /dev/null differ diff --git a/pandas/tests/io/data/legacy_hdf/gh26443.h5 b/pandas/tests/io/data/legacy_hdf/gh26443.h5 deleted file mode 100644 index 45aa64324530f..0000000000000 Binary files a/pandas/tests/io/data/legacy_hdf/gh26443.h5 and /dev/null differ diff --git a/pandas/tests/io/data/legacy_hdf/legacy_table_fixed_datetime_py2.h5 b/pandas/tests/io/data/legacy_hdf/legacy_table_fixed_datetime_py2.h5 deleted file mode 100644 index 18cfae15a3a78..0000000000000 Binary files a/pandas/tests/io/data/legacy_hdf/legacy_table_fixed_datetime_py2.h5 and /dev/null differ diff --git a/pandas/tests/io/data/legacy_hdf/legacy_table_fixed_py2.h5 b/pandas/tests/io/data/legacy_hdf/legacy_table_fixed_py2.h5 deleted file mode 100644 index 540251d9fae86..0000000000000 Binary files a/pandas/tests/io/data/legacy_hdf/legacy_table_fixed_py2.h5 and /dev/null differ diff --git a/pandas/tests/io/data/legacy_hdf/legacy_table_py2.h5 b/pandas/tests/io/data/legacy_hdf/legacy_table_py2.h5 deleted file mode 100644 index 3863d714a315b..0000000000000 Binary files a/pandas/tests/io/data/legacy_hdf/legacy_table_py2.h5 and /dev/null differ diff --git a/pandas/tests/io/data/legacy_hdf/periodindex_0.20.1_x86_64_darwin_2.7.13.h5 b/pandas/tests/io/data/legacy_hdf/periodindex_0.20.1_x86_64_darwin_2.7.13.h5 deleted file mode 100644 index 6fb92d3c564bd..0000000000000 Binary files a/pandas/tests/io/data/legacy_hdf/periodindex_0.20.1_x86_64_darwin_2.7.13.h5 and /dev/null differ diff --git a/pandas/tests/io/data/legacy_msgpack/0.20.3/0.20.3_x86_64_darwin_3.5.2.msgpack b/pandas/tests/io/data/legacy_msgpack/0.20.3/0.20.3_x86_64_darwin_3.5.2.msgpack deleted file mode 100644 index 7a546a82ae766..0000000000000 Binary files a/pandas/tests/io/data/legacy_msgpack/0.20.3/0.20.3_x86_64_darwin_3.5.2.msgpack and /dev/null differ diff --git a/pandas/tests/io/data/pickle/test_mi_py27.pkl b/pandas/tests/io/data/pickle/test_mi_py27.pkl deleted file mode 100644 index 89021dd828108..0000000000000 Binary files a/pandas/tests/io/data/pickle/test_mi_py27.pkl and /dev/null differ diff --git a/pandas/tests/io/data/pickle/test_py27.pkl b/pandas/tests/io/data/pickle/test_py27.pkl deleted file mode 100644 index 5308b864bc0c7..0000000000000 Binary files a/pandas/tests/io/data/pickle/test_py27.pkl and /dev/null differ diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index c8563ee4af4a8..e33ddaf3b81f0 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -5,7 +5,6 @@ import numpy as np import pytest -from pandas._libs.tslibs import Timestamp from pandas.compat import is_platform_windows import pandas as pd @@ -171,50 +170,6 @@ def test_pytables_native2_read(datapath): assert isinstance(d1, DataFrame) -def test_legacy_table_fixed_format_read_py2(datapath): - # GH 24510 - # legacy table with fixed format written in Python 2 - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "legacy_table_fixed_py2.h5"), mode="r" - ) as store: - result = store.select("df") - expected = DataFrame( - [[1, 2, 3, "D"]], - columns=["A", "B", "C", "D"], - index=Index(["ABC"], name="INDEX_NAME"), - ) - tm.assert_frame_equal(expected, result) - - -def test_legacy_table_fixed_format_read_datetime_py2(datapath): - # GH 31750 - # legacy table with fixed format and datetime64 column written in Python 2 - expected = DataFrame( - [[Timestamp("2020-02-06T18:00")]], - columns=["A"], - index=Index(["date"]), - dtype="M8[ns]", - ) - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "legacy_table_fixed_datetime_py2.h5"), - mode="r", - ) as store: - result = store.select("df") - tm.assert_frame_equal(expected, result) - - -def test_legacy_table_read_py2(datapath): - # issue: 24925 - # legacy table written in Python 2 - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "legacy_table_py2.h5"), mode="r" - ) as store: - result = store.select("table") - - expected = DataFrame({"a": ["a", "b"], "b": [2, 3]}) - tm.assert_frame_equal(expected, result) - - def test_read_hdf_open_store(tmp_path, setup_path): # GH10330 # No check for non-string path_or-buf, and no test of open store @@ -348,34 +303,6 @@ def test_read_hdf_series_mode_r(tmp_path, format, setup_path): tm.assert_series_equal(result, series) -@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning") -@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") -def test_read_py2_hdf_file_in_py3(datapath): - # GH 16781 - - # tests reading a PeriodIndex DataFrame written in Python2 in Python3 - - # the file was generated in Python 2.7 like so: - # - # df = DataFrame([1.,2,3], index=pd.PeriodIndex( - # ['2015-01-01', '2015-01-02', '2015-01-05'], freq='B')) - # df.to_hdf('periodindex_0.20.1_x86_64_darwin_2.7.13.h5', 'p') - - expected = DataFrame( - [1.0, 2, 3], - index=pd.PeriodIndex(["2015-01-01", "2015-01-02", "2015-01-05"], freq="B"), - ) - - with ensure_clean_store( - datapath( - "io", "data", "legacy_hdf", "periodindex_0.20.1_x86_64_darwin_2.7.13.h5" - ), - mode="r", - ) as store: - result = store["p"] - tm.assert_frame_equal(result, expected) - - def test_read_infer_string(tmp_path, setup_path): # GH#54431 pytest.importorskip("pyarrow") diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 8c61830ebe038..b455235669636 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -312,23 +312,6 @@ def test_store_timezone(setup_path): tm.assert_frame_equal(result, df) -def test_legacy_datetimetz_object(datapath): - # legacy from < 0.17.0 - # 8260 - expected = DataFrame( - { - "A": Timestamp("20130102", tz="US/Eastern").as_unit("ns"), - "B": Timestamp("20130603", tz="CET").as_unit("ns"), - }, - index=range(5), - ) - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "datetimetz_object.h5"), mode="r" - ) as store: - result = store["df"] - tm.assert_frame_equal(result, expected) - - def test_dst_transitions(setup_path): # make sure we are not failing on transitions with ensure_clean_store(setup_path) as store: @@ -362,17 +345,3 @@ def test_read_with_where_tz_aware_index(tmp_path, setup_path): store.append(key, expected, format="table", append=True) result = pd.read_hdf(path, key, where="DATE > 20151130") tm.assert_frame_equal(result, expected) - - -def test_py2_created_with_datetimez(datapath): - # The test HDF5 file was created in Python 2, but could not be read in - # Python 3. - # - # GH26443 - index = DatetimeIndex(["2019-01-01T18:00"], dtype="M8[ns, America/New_York]") - expected = DataFrame({"data": 123}, index=index) - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "gh26443.h5"), mode="r" - ) as store: - result = store["key"] - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index b43f430b8895b..886bff332a420 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -289,7 +289,7 @@ def test_read_expands_user_home_dir( ( pd.read_hdf, "tables", - ("io", "data", "legacy_hdf", "datetimetz_object.h5"), + ("io", "data", "legacy_hdf", "pytables_native2.h5"), ), (pd.read_stata, "os", ("io", "data", "stata", "stata10_115.dta")), (pd.read_sas, "os", ("io", "sas", "data", "test1.sas7bdat")), diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 38a0888909663..ed8d4371e0f3a 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -399,31 +399,6 @@ def test_read(self, protocol, get_random_path): tm.assert_frame_equal(df, df2) -@pytest.mark.parametrize( - ["pickle_file", "excols"], - [ - ("test_py27.pkl", Index(["a", "b", "c"])), - ( - "test_mi_py27.pkl", - pd.MultiIndex.from_arrays([["a", "b", "c"], ["A", "B", "C"]]), - ), - ], -) -def test_unicode_decode_error(datapath, pickle_file, excols): - # pickle file written with py27, should be readable without raising - # UnicodeDecodeError, see GH#28645 and GH#31988 - path = datapath("io", "data", "pickle", pickle_file) - df = pd.read_pickle(path) - - # just test the columns are correct since the values are random - tm.assert_index_equal(df.columns, excols) - - -# --------------------- -# tests for buffer I/O -# --------------------- - - def test_pickle_buffer_roundtrip(): with tm.ensure_clean() as path: df = DataFrame(
xref https://github.com/pandas-dev/pandas/pull/57155
https://api.github.com/repos/pandas-dev/pandas/pulls/57387
2024-02-12T22:40:44Z
2024-02-14T00:48:13Z
2024-02-14T00:48:13Z
2024-02-14T02:10:51Z
CLN: ._data, PeriodIndex arguments
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index a3e44e6373145..85ee5230b31be 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -26,7 +26,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc>=1.21.3 - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/ci/deps/actions-311-downstream_compat.yaml b/ci/deps/actions-311-downstream_compat.yaml index d6bf9ec7843de..8751cfd52f97d 100644 --- a/ci/deps/actions-311-downstream_compat.yaml +++ b/ci/deps/actions-311-downstream_compat.yaml @@ -28,7 +28,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc>=1.21.3 - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/ci/deps/actions-311.yaml b/ci/deps/actions-311.yaml index 95cd1a4d46ef4..535c260582eec 100644 --- a/ci/deps/actions-311.yaml +++ b/ci/deps/actions-311.yaml @@ -26,7 +26,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc>=1.21.3 - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/ci/deps/actions-312.yaml b/ci/deps/actions-312.yaml index a442ed6feeb5d..8b3f19f55e4b6 100644 --- a/ci/deps/actions-312.yaml +++ b/ci/deps/actions-312.yaml @@ -26,7 +26,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc>=1.21.3 - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/ci/deps/actions-39-minimum_versions.yaml b/ci/deps/actions-39-minimum_versions.yaml index 115ccf01ccaad..d59da897c0d33 100644 --- a/ci/deps/actions-39-minimum_versions.yaml +++ b/ci/deps/actions-39-minimum_versions.yaml @@ -29,7 +29,7 @@ dependencies: - beautifulsoup4=4.11.2 - blosc=1.21.3 - bottleneck=1.3.6 - - fastparquet=2022.12.0 + - fastparquet=2023.04.0 - fsspec=2022.11.0 - html5lib=1.1 - hypothesis=6.46.1 diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index b162a78e7f115..4cc9b1fbe2491 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -26,7 +26,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc>=1.21.3 - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/ci/deps/circle-310-arm64.yaml b/ci/deps/circle-310-arm64.yaml index a19ffd485262d..869aae8596681 100644 --- a/ci/deps/circle-310-arm64.yaml +++ b/ci/deps/circle-310-arm64.yaml @@ -27,7 +27,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc>=1.21.3 - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 7d0ddcc5d22d9..33ce6f0218b98 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -361,7 +361,7 @@ Dependency Minimum Version pip extra Notes PyTables 3.8.0 hdf5 HDF5-based reading / writing blosc 1.21.3 hdf5 Compression for HDF5; only available on ``conda`` zlib hdf5 Compression for HDF5 -fastparquet 2022.12.0 - Parquet reading / writing (pyarrow is default) +fastparquet 2023.04.0 - Parquet reading / writing (pyarrow is default) pyarrow 10.0.1 parquet, feather Parquet, ORC, and feather reading / writing pyreadstat 1.2.0 spss SPSS files (.sav) reading odfpy 1.4.1 excel Open document format (.odf, .ods, .odt) reading / writing diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 915b7744302c0..d51a725d99f2a 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -76,7 +76,7 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+---------------------+ | Package | New Minimum Version | +=================+=====================+ -| | | +| fastparquet | 2023.04.0 | +-----------------+---------------------+ See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. @@ -118,6 +118,7 @@ Removal of prior version deprecations/changes - Removed ``Series.ravel`` (:issue:`56053`) - Removed ``Series.view`` (:issue:`56054`) - Removed ``StataReader.close`` (:issue:`49228`) +- Removed ``_data`` from :class:`DataFrame`, :class:`Series`, :class:`.arrays.ArrowExtensionArray` (:issue:`52003`) - Removed ``axis`` argument from :meth:`DataFrame.groupby`, :meth:`Series.groupby`, :meth:`DataFrame.rolling`, :meth:`Series.rolling`, :meth:`DataFrame.resample`, and :meth:`Series.resample` (:issue:`51203`) - Removed ``axis`` argument from all groupby operations (:issue:`50405`) - Removed ``convert_dtype`` from :meth:`Series.apply` (:issue:`52257`) @@ -126,12 +127,14 @@ Removal of prior version deprecations/changes - Removed ``pandas.value_counts``, use :meth:`Series.value_counts` instead (:issue:`53493`) - Removed ``read_gbq`` and ``DataFrame.to_gbq``. Use ``pandas_gbq.read_gbq`` and ``pandas_gbq.to_gbq`` instead https://pandas-gbq.readthedocs.io/en/latest/api.html (:issue:`55525`) - Removed ``use_nullable_dtypes`` from :func:`read_parquet` (:issue:`51853`) +- Removed ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`) - Removed deprecated argument ``obj`` in :meth:`.DataFrameGroupBy.get_group` and :meth:`.SeriesGroupBy.get_group` (:issue:`53545`) - Removed deprecated behavior of :meth:`Series.agg` using :meth:`Series.apply` (:issue:`53325`) - Removed support for ``errors="ignore"`` in :func:`to_datetime`, :func:`to_timedelta` and :func:`to_numeric` (:issue:`55734`) - Removed the ``ArrayManager`` (:issue:`55043`) - Removed the ``fastpath`` argument from the :class:`Series` constructor (:issue:`55466`) - Removed the ``is_boolean``, ``is_integer``, ``is_floating``, ``holds_integer``, ``is_numeric``, ``is_categorical``, ``is_object``, and ``is_interval`` attributes of :class:`Index` (:issue:`50042`) +- Removed the ``ordinal`` keyword in :class:`PeriodIndex`, use :meth:`PeriodIndex.from_ordinals` instead (:issue:`55960`) - Removed unused arguments ``*args`` and ``**kwargs`` in :class:`Resampler` methods (:issue:`50977`) - Unrecognized timezones when parsing strings to datetimes now raises a ``ValueError`` (:issue:`51477`) diff --git a/environment.yml b/environment.yml index 5a2dd0b697084..36d1bf27a4cd2 100644 --- a/environment.yml +++ b/environment.yml @@ -29,7 +29,7 @@ dependencies: - beautifulsoup4>=4.11.2 - blosc - bottleneck>=1.3.6 - - fastparquet>=2022.12.0 + - fastparquet>=2023.04.0 - fsspec>=2022.11.0 - html5lib>=1.1 - hypothesis>=6.46.1 diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index bcfe1385f0528..3a438b76b1263 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -25,7 +25,7 @@ "blosc": "1.21.3", "bottleneck": "1.3.6", "dataframe-api-compat": "0.1.7", - "fastparquet": "2022.12.0", + "fastparquet": "2023.04.0", "fsspec": "2022.11.0", "html5lib": "1.1", "hypothesis": "6.46.1", diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index ba02c63c00ce4..54d85570e551b 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -9,7 +9,6 @@ Union, cast, ) -import warnings import numpy as np @@ -21,7 +20,6 @@ pa_version_under10p1, pa_version_under13p0, ) -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_bool_dtype, @@ -272,17 +270,6 @@ def astype(self, dtype, copy: bool = True): return super().astype(dtype, copy=copy) - @property - def _data(self): - # dask accesses ._data directlys - warnings.warn( - f"{type(self).__name__}._data is a deprecated and will be removed " - "in a future version, use ._pa_array instead", - FutureWarning, - stacklevel=find_stack_level(), - ) - return self._pa_array - # ------------------------------------------------------------------------ # String methods interface diff --git a/pandas/core/generic.py b/pandas/core/generic.py index afdbf157a04fa..6074d0424b5ac 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -486,23 +486,6 @@ def _constructor(self) -> Callable[..., Self]: """ raise AbstractMethodError(self) - # ---------------------------------------------------------------------- - # Internals - - @final - @property - def _data(self): - # GH#33054 retained because some downstream packages uses this, - # e.g. fastparquet - # GH#33333 - warnings.warn( - f"{type(self).__name__}._data is deprecated and will be removed in " - "a future version. Use public APIs instead.", - DeprecationWarning, - stacklevel=find_stack_level(), - ) - return self._mgr - # ---------------------------------------------------------------------- # Axis _AXIS_ORDERS: list[Literal["index", "columns"]] diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index a7315d40f0236..ac91600590ea8 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -5,7 +5,6 @@ timedelta, ) from typing import TYPE_CHECKING -import warnings import numpy as np @@ -22,7 +21,6 @@ cache_readonly, doc, ) -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_integer from pandas.core.dtypes.dtypes import PeriodDtype @@ -94,11 +92,6 @@ class PeriodIndex(DatetimeIndexOpsMixin): ---------- data : array-like (1d int np.ndarray or PeriodArray), optional Optional period-like data to construct index with. - ordinal : array-like of int, optional - The period offsets from the proleptic Gregorian epoch. - - .. deprecated:: 2.2.0 - Use PeriodIndex.from_ordinals instead. freq : str or period object, optional One of pandas period strings or corresponding objects. dtype : str or PeriodDtype, default None @@ -107,11 +100,6 @@ class PeriodIndex(DatetimeIndexOpsMixin): Make a copy of input ndarray. name : str, default None Name of the resulting PeriodIndex. - **fields : optional - Date fields such as year, month, etc. - - .. deprecated:: 2.2.0 - Use PeriodIndex.from_fields instead. Attributes ---------- @@ -219,84 +207,29 @@ def second(self) -> Index: def __new__( cls, data=None, - ordinal=None, freq=None, dtype: Dtype | None = None, copy: bool = False, name: Hashable | None = None, - **fields, ) -> Self: - valid_field_set = { - "year", - "month", - "day", - "quarter", - "hour", - "minute", - "second", - } - refs = None if not copy and isinstance(data, (Index, ABCSeries)): refs = data._references - if not set(fields).issubset(valid_field_set): - argument = next(iter(set(fields) - valid_field_set)) - raise TypeError(f"__new__() got an unexpected keyword argument {argument}") - elif len(fields): - # GH#55960 - warnings.warn( - "Constructing PeriodIndex from fields is deprecated. Use " - "PeriodIndex.from_fields instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - - if ordinal is not None: - # GH#55960 - warnings.warn( - "The 'ordinal' keyword in PeriodIndex is deprecated and will " - "be removed in a future version. Use PeriodIndex.from_ordinals " - "instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - name = maybe_extract_name(name, data, cls) - if data is None and ordinal is None: - # range-based. - if not fields: - # test_pickle_compat_construction - cls._raise_scalar_data_error(None) - data = cls.from_fields(**fields, freq=freq)._data - copy = False + freq = validate_dtype_freq(dtype, freq) - elif fields: - if data is not None: - raise ValueError("Cannot pass both data and fields") - raise ValueError("Cannot pass both ordinal and fields") + # PeriodIndex allow PeriodIndex(period_index, freq=different) + # Let's not encourage that kind of behavior in PeriodArray. - else: - freq = validate_dtype_freq(dtype, freq) - - # PeriodIndex allow PeriodIndex(period_index, freq=different) - # Let's not encourage that kind of behavior in PeriodArray. - - if freq and isinstance(data, cls) and data.freq != freq: - # TODO: We can do some of these with no-copy / coercion? - # e.g. D -> 2D seems to be OK - data = data.asfreq(freq) - - if data is None and ordinal is not None: - ordinal = np.asarray(ordinal, dtype=np.int64) - dtype = PeriodDtype(freq) - data = PeriodArray(ordinal, dtype=dtype) - elif data is not None and ordinal is not None: - raise ValueError("Cannot pass both data and ordinal") - else: - # don't pass copy here, since we copy later. - data = period_array(data=data, freq=freq) + if freq and isinstance(data, cls) and data.freq != freq: + # TODO: We can do some of these with no-copy / coercion? + # e.g. D -> 2D seems to be OK + data = data.asfreq(freq) + + # don't pass copy here, since we copy later. + data = period_array(data=data, freq=freq) if copy: data = data.copy() diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index b849baa8cab62..680800d7f5e4c 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -376,8 +376,4 @@ def test_inspect_getmembers(self): # GH38740 pytest.importorskip("jinja2") df = DataFrame() - msg = "DataFrame._data is deprecated" - with tm.assert_produces_warning( - DeprecationWarning, match=msg, check_stacklevel=False - ): - inspect.getmembers(df) + inspect.getmembers(df) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index cdb34a00b952c..0b607d91baf65 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -303,13 +303,6 @@ def test_copy_and_deepcopy(self, frame_or_series, shape, func): assert obj_copy is not obj tm.assert_equal(obj_copy, obj) - def test_data_deprecated(self, frame_or_series): - obj = frame_or_series() - msg = "(Series|DataFrame)._data is deprecated" - with tm.assert_produces_warning(DeprecationWarning, match=msg): - mgr = obj._data - assert mgr is obj._mgr - class TestNDFrame: # tests that don't fit elsewhere diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index 892eb7b4a00d1..519c09015427e 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -66,40 +66,10 @@ def test_from_ordinals(self): Period(ordinal=-1000, freq="Y") Period(ordinal=0, freq="Y") - msg = "The 'ordinal' keyword in PeriodIndex is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - idx1 = PeriodIndex(ordinal=[-1, 0, 1], freq="Y") - with tm.assert_produces_warning(FutureWarning, match=msg): - idx2 = PeriodIndex(ordinal=np.array([-1, 0, 1]), freq="Y") + idx1 = PeriodIndex.from_ordinals(ordinals=[-1, 0, 1], freq="Y") + idx2 = PeriodIndex.from_ordinals(ordinals=np.array([-1, 0, 1]), freq="Y") tm.assert_index_equal(idx1, idx2) - alt1 = PeriodIndex.from_ordinals([-1, 0, 1], freq="Y") - tm.assert_index_equal(alt1, idx1) - - alt2 = PeriodIndex.from_ordinals(np.array([-1, 0, 1]), freq="Y") - tm.assert_index_equal(alt2, idx2) - - def test_keyword_mismatch(self): - # GH#55961 we should get exactly one of data/ordinals/**fields - per = Period("2016-01-01", "D") - depr_msg1 = "The 'ordinal' keyword in PeriodIndex is deprecated" - depr_msg2 = "Constructing PeriodIndex from fields is deprecated" - - err_msg1 = "Cannot pass both data and ordinal" - with pytest.raises(ValueError, match=err_msg1): - with tm.assert_produces_warning(FutureWarning, match=depr_msg1): - PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq) - - err_msg2 = "Cannot pass both data and fields" - with pytest.raises(ValueError, match=err_msg2): - with tm.assert_produces_warning(FutureWarning, match=depr_msg2): - PeriodIndex(data=[per], year=[per.year], freq=per.freq) - - err_msg3 = "Cannot pass both ordinal and fields" - with pytest.raises(ValueError, match=err_msg3): - with tm.assert_produces_warning(FutureWarning, match=depr_msg2): - PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq) - def test_construction_base_constructor(self): # GH 13664 arr = [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")] @@ -158,18 +128,14 @@ def test_constructor_field_arrays(self): years = np.arange(1990, 2010).repeat(4)[2:-2] quarters = np.tile(np.arange(1, 5), 20)[2:-2] - depr_msg = "Constructing PeriodIndex from fields is deprecated" - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - index = PeriodIndex(year=years, quarter=quarters, freq="Q-DEC") + index = PeriodIndex.from_fields(year=years, quarter=quarters, freq="Q-DEC") expected = period_range("1990Q3", "2009Q2", freq="Q-DEC") tm.assert_index_equal(index, expected) - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - index2 = PeriodIndex(year=years, quarter=quarters, freq="2Q-DEC") + index2 = PeriodIndex.from_fields(year=years, quarter=quarters, freq="2Q-DEC") tm.assert_numpy_array_equal(index.asi8, index2.asi8) - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - index = PeriodIndex(year=years, quarter=quarters) + index = PeriodIndex.from_fields(year=years, quarter=quarters) tm.assert_index_equal(index, expected) years = [2007, 2007, 2007] @@ -177,16 +143,13 @@ def test_constructor_field_arrays(self): msg = "Mismatched Period array lengths" with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - PeriodIndex(year=years, month=months, freq="M") + PeriodIndex.from_fields(year=years, month=months, freq="M") with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - PeriodIndex(year=years, month=months, freq="2M") + PeriodIndex.from_fields(year=years, month=months, freq="2M") years = [2007, 2007, 2007] months = [1, 2, 3] - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - idx = PeriodIndex(year=years, month=months, freq="M") + idx = PeriodIndex.from_fields(year=years, month=months, freq="M") exp = period_range("2007-01", periods=3, freq="M") tm.assert_index_equal(idx, exp) @@ -210,25 +173,17 @@ def test_constructor_nano(self): def test_constructor_arrays_negative_year(self): years = np.arange(1960, 2000, dtype=np.int64).repeat(4) quarters = np.tile(np.array([1, 2, 3, 4], dtype=np.int64), 40) - - msg = "Constructing PeriodIndex from fields is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - pindex = PeriodIndex(year=years, quarter=quarters) + pindex = PeriodIndex.from_fields(year=years, quarter=quarters) tm.assert_index_equal(pindex.year, Index(years)) tm.assert_index_equal(pindex.quarter, Index(quarters)) - alt = PeriodIndex.from_fields(year=years, quarter=quarters) - tm.assert_index_equal(alt, pindex) - def test_constructor_invalid_quarters(self): - depr_msg = "Constructing PeriodIndex from fields is deprecated" msg = "Quarter must be 1 <= q <= 4" with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - PeriodIndex( - year=range(2000, 2004), quarter=list(range(4)), freq="Q-DEC" - ) + PeriodIndex.from_fields( + year=range(2000, 2004), quarter=list(range(4)), freq="Q-DEC" + ) def test_period_range_fractional_period(self): msg = "Non-integer 'periods' in pd.date_range, pd.timedelta_range" @@ -434,9 +389,7 @@ def test_constructor_floats(self, floats): def test_constructor_year_and_quarter(self): year = Series([2001, 2002, 2003]) quarter = year - 2000 - msg = "Constructing PeriodIndex from fields is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - idx = PeriodIndex(year=year, quarter=quarter) + idx = PeriodIndex.from_fields(year=year, quarter=quarter) strs = [f"{t[0]:d}Q{t[1]:d}" for t in zip(quarter, year)] lops = list(map(Period, strs)) p = PeriodIndex(lops) diff --git a/pandas/tests/indexes/test_old_base.py b/pandas/tests/indexes/test_old_base.py index cc496dbee86d3..485822d4e4d59 100644 --- a/pandas/tests/indexes/test_old_base.py +++ b/pandas/tests/indexes/test_old_base.py @@ -86,6 +86,7 @@ def test_pickle_compat_construction(self, simple_index): r"kind, None was passed", r"__new__\(\) missing 1 required positional argument: 'data'", r"__new__\(\) takes at least 2 arguments \(1 given\)", + r"'NoneType' object is not iterable", ] ) with pytest.raises(TypeError, match=msg): @@ -275,9 +276,7 @@ def test_ensure_copied_data(self, index): if isinstance(index, PeriodIndex): # .values an object array of Period, thus copied - depr_msg = "The 'ordinal' keyword in PeriodIndex is deprecated" - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) + result = index_type.from_ordinals(ordinals=index.asi8, **init_kwargs) tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") elif isinstance(index, IntervalIndex): # checked in test_interval.py diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 691308633a796..2b94983bd33c3 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -164,11 +164,7 @@ def test_inspect_getmembers(self): # GH38782 pytest.importorskip("jinja2") ser = Series(dtype=object) - msg = "Series._data is deprecated" - with tm.assert_produces_warning( - DeprecationWarning, match=msg, check_stacklevel=False - ): - inspect.getmembers(ser) + inspect.getmembers(ser) def test_unknown_attribute(self): # GH#9680 diff --git a/pyproject.toml b/pyproject.toml index c0d8c859d0c12..9d71cfd3cbb64 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -92,7 +92,7 @@ all = ['adbc-driver-postgresql>=0.8.0', #'blosc>=1.21.3', 'bottleneck>=1.3.6', 'dataframe-api-compat>=0.1.7', - 'fastparquet>=2022.12.0', + 'fastparquet>=2023.04.0', 'fsspec>=2022.11.0', 'gcsfs>=2022.11.0', 'html5lib>=1.1', diff --git a/requirements-dev.txt b/requirements-dev.txt index 162e6caebcd8a..96c497d35b958 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,7 +18,7 @@ pytz beautifulsoup4>=4.11.2 blosc bottleneck>=1.3.6 -fastparquet>=2022.12.0 +fastparquet>=2023.04.0 fsspec>=2022.11.0 html5lib>=1.1 hypothesis>=6.46.1
xref https://github.com/pandas-dev/pandas/pull/52003, https://github.com/pandas-dev/pandas/pull/55963 Bumped fastparquet as they updated their `_data` usage in https://github.com/dask/fastparquet/commit/7d9703b82090c5fc8ae3b013ae558f3b06fa287c
https://api.github.com/repos/pandas-dev/pandas/pulls/57385
2024-02-12T21:49:32Z
2024-02-14T17:43:54Z
2024-02-14T17:43:54Z
2024-02-14T17:43:57Z
DOC: add an example to `PeriodIndex.to_timestamp` to clarify the behavior in case len(index)<3
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index ab79622ddd8be..d3760abb8eaf3 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -636,6 +636,20 @@ def to_timestamp(self, freq=None, how: str = "start") -> DatetimeArray: >>> idx.to_timestamp() DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'], dtype='datetime64[ns]', freq='MS') + + The frequency will not be inferred if the index contains less than + three elements, or if the values of index are not strictly monotonic: + + >>> idx = pd.PeriodIndex(["2023-01", "2023-02"], freq="M") + >>> idx.to_timestamp() + DatetimeIndex(['2023-01-01', '2023-02-01'], dtype='datetime64[ns]', freq=None) + + >>> idx = pd.PeriodIndex( + ... ["2023-01", "2023-02", "2023-02", "2023-03"], freq="2M" + ... ) + >>> idx.to_timestamp() + DatetimeIndex(['2023-01-01', '2023-02-01', '2023-02-01', '2023-03-01'], + dtype='datetime64[ns]', freq=None) """ from pandas.core.arrays import DatetimeArray
xref #56213 added an example to `PeriodIndex.to_timestamp` to clarify the behavior in case `len(index) < 3`
https://api.github.com/repos/pandas-dev/pandas/pulls/57384
2024-02-12T21:10:29Z
2024-02-15T16:09:12Z
2024-02-15T16:09:12Z
2024-02-15T16:09:12Z
Backport PR #57379 on branch 2.2.x (Fix numpy-dev CI warnings)
diff --git a/pandas/_libs/src/vendored/ujson/python/objToJSON.c b/pandas/_libs/src/vendored/ujson/python/objToJSON.c index 8bba95dd456de..74ca8ead3d936 100644 --- a/pandas/_libs/src/vendored/ujson/python/objToJSON.c +++ b/pandas/_libs/src/vendored/ujson/python/objToJSON.c @@ -447,8 +447,15 @@ static void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { npyarr->curdim--; npyarr->dataptr -= npyarr->stride * npyarr->index[npyarr->stridedim]; npyarr->stridedim -= npyarr->inc; - npyarr->dim = PyArray_DIM(npyarr->array, npyarr->stridedim); - npyarr->stride = PyArray_STRIDE(npyarr->array, npyarr->stridedim); + + if (!PyArray_Check(npyarr->array)) { + PyErr_SetString(PyExc_TypeError, + "NpyArrayPassThru_iterEnd received a non-array object"); + return; + } + const PyArrayObject *arrayobj = (const PyArrayObject *)npyarr->array; + npyarr->dim = PyArray_DIM(arrayobj, npyarr->stridedim); + npyarr->stride = PyArray_STRIDE(arrayobj, npyarr->stridedim); npyarr->dataptr += npyarr->stride; NpyArr_freeItemValue(obj, tc); @@ -467,12 +474,19 @@ static int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { NpyArr_freeItemValue(obj, tc); - if (PyArray_ISDATETIME(npyarr->array)) { + if (!PyArray_Check(npyarr->array)) { + PyErr_SetString(PyExc_TypeError, + "NpyArr_iterNextItem received a non-array object"); + return 0; + } + PyArrayObject *arrayobj = (PyArrayObject *)npyarr->array; + + if (PyArray_ISDATETIME(arrayobj)) { GET_TC(tc)->itemValue = obj; Py_INCREF(obj); - ((PyObjectEncoder *)tc->encoder)->npyType = PyArray_TYPE(npyarr->array); + ((PyObjectEncoder *)tc->encoder)->npyType = PyArray_TYPE(arrayobj); // Also write the resolution (unit) of the ndarray - PyArray_Descr *dtype = PyArray_DESCR(npyarr->array); + PyArray_Descr *dtype = PyArray_DESCR(arrayobj); ((PyObjectEncoder *)tc->encoder)->valueUnit = get_datetime_metadata_from_dtype(dtype).base; ((PyObjectEncoder *)tc->encoder)->npyValue = npyarr->dataptr; @@ -505,8 +519,15 @@ static int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { npyarr->curdim++; npyarr->stridedim += npyarr->inc; - npyarr->dim = PyArray_DIM(npyarr->array, npyarr->stridedim); - npyarr->stride = PyArray_STRIDE(npyarr->array, npyarr->stridedim); + if (!PyArray_Check(npyarr->array)) { + PyErr_SetString(PyExc_TypeError, + "NpyArr_iterNext received a non-array object"); + return 0; + } + const PyArrayObject *arrayobj = (const PyArrayObject *)npyarr->array; + + npyarr->dim = PyArray_DIM(arrayobj, npyarr->stridedim); + npyarr->stride = PyArray_STRIDE(arrayobj, npyarr->stridedim); npyarr->index[npyarr->stridedim] = 0; ((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = npyarr; @@ -1610,7 +1631,14 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { if (!values) { goto INVALID; } - pc->columnLabelsLen = PyArray_DIM(pc->newObj, 0); + + if (!PyArray_Check(pc->newObj)) { + PyErr_SetString(PyExc_TypeError, + "Object_beginTypeContext received a non-array object"); + goto INVALID; + } + const PyArrayObject *arrayobj = (const PyArrayObject *)pc->newObj; + pc->columnLabelsLen = PyArray_DIM(arrayobj, 0); pc->columnLabels = NpyArr_encodeLabels((PyArrayObject *)values, enc, pc->columnLabelsLen); if (!pc->columnLabels) {
Backport PR #57379: Fix numpy-dev CI warnings
https://api.github.com/repos/pandas-dev/pandas/pulls/57383
2024-02-12T20:33:11Z
2024-02-12T21:50:47Z
2024-02-12T21:50:47Z
2024-02-12T21:50:47Z
Backport PR #57340 on branch 2.2.x (REGR: shift raising for axis=1 and empty df)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index eb6e50c1be160..434a8fd3ea6b4 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.groupby` raising ``ValueError`` when grouping by a :class:`Series` in some cases (:issue:`57276`) - Fixed regression in :meth:`DataFrame.loc` raising ``IndexError`` for non-unique, masked dtype indexes where result has more than 10,000 rows (:issue:`57027`) - Fixed regression in :meth:`DataFrame.merge` raising ``ValueError`` for certain types of 3rd-party extension arrays (:issue:`57316`) +- Fixed regression in :meth:`DataFrame.shift` raising ``AssertionError`` for ``axis=1`` and empty :class:`DataFrame` (:issue:`57301`) - Fixed regression in :meth:`DataFrame.sort_index` not producing a stable sort for a index with duplicates (:issue:`57151`) - Fixed regression in :meth:`DataFrame.to_dict` with ``orient='list'`` and datetime or timedelta types returning integers (:issue:`54824`) - Fixed regression in :meth:`DataFrame.to_json` converting nullable integers to floats (:issue:`57224`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 734756cb8f7c8..b531ddc418df1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5859,6 +5859,9 @@ def shift( ) fill_value = lib.no_default + if self.empty: + return self.copy() + axis = self._get_axis_number(axis) if is_list_like(periods): diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index b21aa2d687682..abb30595fdcb8 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -756,3 +756,9 @@ def test_shift_with_iterable_check_other_arguments(self): msg = "Cannot specify `suffix` if `periods` is an int." with pytest.raises(ValueError, match=msg): df.shift(1, suffix="fails") + + def test_shift_axis_one_empty(self): + # GH#57301 + df = DataFrame() + result = df.shift(1, axis=1) + tm.assert_frame_equal(result, df)
Backport PR #57340: REGR: shift raising for axis=1 and empty df
https://api.github.com/repos/pandas-dev/pandas/pulls/57381
2024-02-12T18:25:35Z
2024-02-12T20:33:27Z
2024-02-12T20:33:27Z
2024-02-12T20:33:27Z
Backport PR #57341 on branch 2.2.x (REGR: assert_series_equal defaulting to check_exact=True for Index)
diff --git a/doc/source/whatsnew/v2.2.1.rst b/doc/source/whatsnew/v2.2.1.rst index eb6e50c1be160..47ca96c6eef44 100644 --- a/doc/source/whatsnew/v2.2.1.rst +++ b/doc/source/whatsnew/v2.2.1.rst @@ -17,6 +17,7 @@ Fixed regressions - Fixed performance regression in :meth:`Series.combine_first` (:issue:`55845`) - Fixed regression in :func:`concat` changing long-standing behavior that always sorted the non-concatenation axis when the axis was a :class:`DatetimeIndex` (:issue:`57006`) - Fixed regression in :func:`merge_ordered` raising ``TypeError`` for ``fill_method="ffill"`` and ``how="left"`` (:issue:`57010`) +- Fixed regression in :func:`pandas.testing.assert_series_equal` defaulting to ``check_exact=True`` when checking the :class:`Index` (:issue:`57067`) - Fixed regression in :func:`wide_to_long` raising an ``AttributeError`` for string columns (:issue:`57066`) - Fixed regression in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, :meth:`.SeriesGroupBy.idxmax` ignoring the ``skipna`` argument (:issue:`57040`) - Fixed regression in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, :meth:`.SeriesGroupBy.idxmax` where values containing the minimum or maximum value for the dtype could produce incorrect results (:issue:`57040`) diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 3de982498e996..41d2a7344a4ed 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -902,6 +902,7 @@ def assert_series_equal( >>> tm.assert_series_equal(a, b) """ __tracebackhide__ = True + check_exact_index = False if check_exact is lib.no_default else check_exact if ( check_exact is lib.no_default and rtol is lib.no_default @@ -944,7 +945,7 @@ def assert_series_equal( right.index, exact=check_index_type, check_names=check_names, - check_exact=check_exact, + check_exact=check_exact_index, check_categorical=check_categorical, check_order=not check_like, rtol=rtol, diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py index 784a0347cf92b..1878e7d838064 100644 --- a/pandas/tests/util/test_assert_series_equal.py +++ b/pandas/tests/util/test_assert_series_equal.py @@ -474,3 +474,11 @@ def test_assert_series_equal_int_tol(): tm.assert_extension_array_equal( left.astype("Int64").values, right.astype("Int64").values, rtol=1.5 ) + + +def test_assert_series_equal_index_exact_default(): + # GH#57067 + ser1 = Series(np.zeros(6, dtype=int), [0, 0.2, 0.4, 0.6, 0.8, 1]) + ser2 = Series(np.zeros(6, dtype=int), np.linspace(0, 1, 6)) + tm.assert_series_equal(ser1, ser2) + tm.assert_frame_equal(ser1.to_frame(), ser2.to_frame())
Backport PR #57341: REGR: assert_series_equal defaulting to check_exact=True for Index
https://api.github.com/repos/pandas-dev/pandas/pulls/57380
2024-02-12T18:23:50Z
2024-02-12T20:33:18Z
2024-02-12T20:33:18Z
2024-02-12T20:33:19Z
Fix numpy-dev CI warnings
diff --git a/pandas/_libs/src/vendored/ujson/python/objToJSON.c b/pandas/_libs/src/vendored/ujson/python/objToJSON.c index 8bba95dd456de..74ca8ead3d936 100644 --- a/pandas/_libs/src/vendored/ujson/python/objToJSON.c +++ b/pandas/_libs/src/vendored/ujson/python/objToJSON.c @@ -447,8 +447,15 @@ static void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { npyarr->curdim--; npyarr->dataptr -= npyarr->stride * npyarr->index[npyarr->stridedim]; npyarr->stridedim -= npyarr->inc; - npyarr->dim = PyArray_DIM(npyarr->array, npyarr->stridedim); - npyarr->stride = PyArray_STRIDE(npyarr->array, npyarr->stridedim); + + if (!PyArray_Check(npyarr->array)) { + PyErr_SetString(PyExc_TypeError, + "NpyArrayPassThru_iterEnd received a non-array object"); + return; + } + const PyArrayObject *arrayobj = (const PyArrayObject *)npyarr->array; + npyarr->dim = PyArray_DIM(arrayobj, npyarr->stridedim); + npyarr->stride = PyArray_STRIDE(arrayobj, npyarr->stridedim); npyarr->dataptr += npyarr->stride; NpyArr_freeItemValue(obj, tc); @@ -467,12 +474,19 @@ static int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { NpyArr_freeItemValue(obj, tc); - if (PyArray_ISDATETIME(npyarr->array)) { + if (!PyArray_Check(npyarr->array)) { + PyErr_SetString(PyExc_TypeError, + "NpyArr_iterNextItem received a non-array object"); + return 0; + } + PyArrayObject *arrayobj = (PyArrayObject *)npyarr->array; + + if (PyArray_ISDATETIME(arrayobj)) { GET_TC(tc)->itemValue = obj; Py_INCREF(obj); - ((PyObjectEncoder *)tc->encoder)->npyType = PyArray_TYPE(npyarr->array); + ((PyObjectEncoder *)tc->encoder)->npyType = PyArray_TYPE(arrayobj); // Also write the resolution (unit) of the ndarray - PyArray_Descr *dtype = PyArray_DESCR(npyarr->array); + PyArray_Descr *dtype = PyArray_DESCR(arrayobj); ((PyObjectEncoder *)tc->encoder)->valueUnit = get_datetime_metadata_from_dtype(dtype).base; ((PyObjectEncoder *)tc->encoder)->npyValue = npyarr->dataptr; @@ -505,8 +519,15 @@ static int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { npyarr->curdim++; npyarr->stridedim += npyarr->inc; - npyarr->dim = PyArray_DIM(npyarr->array, npyarr->stridedim); - npyarr->stride = PyArray_STRIDE(npyarr->array, npyarr->stridedim); + if (!PyArray_Check(npyarr->array)) { + PyErr_SetString(PyExc_TypeError, + "NpyArr_iterNext received a non-array object"); + return 0; + } + const PyArrayObject *arrayobj = (const PyArrayObject *)npyarr->array; + + npyarr->dim = PyArray_DIM(arrayobj, npyarr->stridedim); + npyarr->stride = PyArray_STRIDE(arrayobj, npyarr->stridedim); npyarr->index[npyarr->stridedim] = 0; ((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = npyarr; @@ -1610,7 +1631,14 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { if (!values) { goto INVALID; } - pc->columnLabelsLen = PyArray_DIM(pc->newObj, 0); + + if (!PyArray_Check(pc->newObj)) { + PyErr_SetString(PyExc_TypeError, + "Object_beginTypeContext received a non-array object"); + goto INVALID; + } + const PyArrayObject *arrayobj = (const PyArrayObject *)pc->newObj; + pc->columnLabelsLen = PyArray_DIM(arrayobj, 0); pc->columnLabels = NpyArr_encodeLabels((PyArrayObject *)values, enc, pc->columnLabelsLen); if (!pc->columnLabels) {
null
https://api.github.com/repos/pandas-dev/pandas/pulls/57379
2024-02-12T18:18:43Z
2024-02-12T20:33:04Z
2024-02-12T20:33:04Z
2024-02-12T20:33:11Z