From a7803571550c424c4aba1c431894a7424b5e6f19 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Tue, 13 Dec 2022 23:51:03 +0100 Subject: [PATCH 1/2] Disallow cumprod for timedelta --- pandas/core/arrays/timedeltas.py | 7 ++++--- pandas/tests/series/test_cumulative.py | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index e68b56c57c176..aa1b826ef0876 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -417,12 +417,13 @@ def _accumulate(self, name: str, *, skipna: bool = True, **kwargs): data = self._ndarray.copy() - if name in {"cumsum", "cumprod"}: - # TODO: cumprod should not work here GH#48111 - func = np.cumsum if name == "cumsum" else np.cumprod + if name == "cumsum": + func = np.cumsum result = cast(np.ndarray, nanops.na_accum_func(data, func, skipna=skipna)) return type(self)._simple_new(result, freq=None, dtype=self.dtype) + elif name == "cumprod": + raise TypeError("cumprod not supported for Timedelta.") else: return super()._accumulate(name, skipna=skipna, **kwargs) diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py index f970d88e310e1..6fbc78bf3ff0f 100644 --- a/pandas/tests/series/test_cumulative.py +++ b/pandas/tests/series/test_cumulative.py @@ -129,3 +129,9 @@ def test_cummethods_bool_in_object_dtype(self, method, expected): ser = pd.Series([False, True, np.nan, False]) result = getattr(ser, method)() tm.assert_series_equal(result, expected) + + def test_cumprod_timedelta(self): + # GH#48111 + ser = pd.Series([pd.Timedelta(days=1), pd.Timedelta(days=3)]) + with pytest.raises(TypeError, match="cumprod not supported for Timedelta"): + ser.cumprod() From ed2ff6d5b89d72af9090e32e93619f1160d2b661 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Thu, 15 Dec 2022 21:37:49 +0100 Subject: [PATCH 2/2] Add whatsnew --- doc/source/whatsnew/v2.0.0.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 5c635f2d9d3be..215e9c2a85bba 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -485,6 +485,7 @@ Other API changes or :attr:`~DataFrame.iloc` (thus, ``df.loc[:, :]`` or ``df.iloc[:, :]``) now returns a new DataFrame (shallow copy) instead of the original DataFrame, consistent with other methods to get a full slice (for example ``df.loc[:]`` or ``df[:]``) (:issue:`49469`) +- Disallow computing ``cumprod`` for :class:`Timedelta` object; previously this returned incorrect values (:issue:`50246`) - .. ---------------------------------------------------------------------------