Skip to content

Added validation check for integer value for series.df #56688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jan 7, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v2.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ Performance improvements

Bug fixes
~~~~~~~~~
- Fixed bug in :meth:`Series.diff` and :meth:`algorithms.diff` allowing non-integer values for the ``periods`` argument. (:issue:`56607`)


Categorical
^^^^^^^^^^^
Expand Down
8 changes: 7 additions & 1 deletion pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
is_complex_dtype,
is_dict_like,
is_extension_array_dtype,
is_float,
is_float_dtype,
is_integer,
is_integer_dtype,
Expand Down Expand Up @@ -1361,7 +1362,12 @@ def diff(arr, n: int, axis: AxisInt = 0):
shifted
"""

n = int(n)
# added a check on the integer value of period
# see https://github.com/pandas-dev/pandas/issues/56607
if not lib.is_integer(n):
if not (is_float(n) and n.is_integer()):
raise ValueError("periods must be an integer")
n = int(n)
na = np.nan
dtype = arr.dtype

Expand Down
4 changes: 4 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
)
from pandas.core.dtypes.common import (
is_dict_like,
is_float,
is_integer,
is_iterator,
is_list_like,
Expand Down Expand Up @@ -3102,6 +3103,9 @@ def diff(self, periods: int = 1) -> Series:
--------
{examples}
"""
if not lib.is_integer(periods):
if not (is_float(periods) and periods.is_integer()):
raise ValueError("periods must be an integer")
result = algorithms.diff(self._values, periods)
return self._constructor(result, index=self.index, copy=False).__finalize__(
self, method="diff"
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/series/methods/test_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@


class TestSeriesDiff:
def test_diff_series_requires_integer(self):
series = Series(np.random.default_rng(2).standard_normal(2))
with pytest.raises(ValueError, match="periods must be an integer"):
series.diff(1.5)

def test_diff_np(self):
# TODO(__array_function__): could make np.diff return a Series
# matching ser.diff()
Expand Down