From 04be7f4c0284488976ad8166bb4a8537316ac20a Mon Sep 17 00:00:00 2001 From: Brock Date: Mon, 22 Nov 2021 12:16:29 -0800 Subject: [PATCH 1/2] BUG: DataFrame.diff(np_int_obj) --- doc/source/whatsnew/v1.4.0.rst | 1 + pandas/core/frame.py | 2 +- pandas/tests/frame/methods/test_diff.py | 7 +++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 1f656f267783f..655c875277ea2 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -741,6 +741,7 @@ Other - Bug in :meth:`Series.to_frame` and :meth:`Index.to_frame` ignoring the ``name`` argument when ``name=None`` is explicitly passed (:issue:`44212`) - Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`) - Bug in :meth:`FloatingArray.equals` failing to consider two arrays equal if they contain ``np.nan`` values (:issue:`44382`) +- Bug in :meth:`DataFrame.diff` when passing a NumPy integer object instead of an ``int`` object (:issue:`44572`) - .. ***DO NOT USE THIS SECTION*** diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0960ab4a81149..8fbbd54ad63d5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8612,7 +8612,7 @@ def melt( ), ) def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: - if not isinstance(periods, int): + if not lib.is_integer(periods): if not (is_float(periods) and periods.is_integer()): raise ValueError("periods must be an integer") periods = int(periods) diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py index 5fd6928f11f44..fe227db894feb 100644 --- a/pandas/tests/frame/methods/test_diff.py +++ b/pandas/tests/frame/methods/test_diff.py @@ -17,6 +17,13 @@ def test_diff_requires_integer(self): with pytest.raises(ValueError, match="periods must be an integer"): df.diff(1.5) + def test_diff_allows_np_integer(self): + # np.int64 is OK GH#44572 + df = DataFrame(np.random.randn(2, 2)) + res = df.diff(np.int64(1)) + expected = df.diff(1) + tm.assert_frame_equal(res, expected) + def test_diff(self, datetime_frame): the_diff = datetime_frame.diff(1) From 7a4c4239ef91cb7c03e62cd2a9b1eb19b93bf7f8 Mon Sep 17 00:00:00 2001 From: Brock Date: Tue, 23 Nov 2021 07:57:53 -0800 Subject: [PATCH 2/2] mypy fixup --- pandas/core/frame.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5bcbd0f47a83a..33df7a9f0ac1f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8613,7 +8613,11 @@ def melt( ) def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: if not lib.is_integer(periods): - if not (is_float(periods) and periods.is_integer()): + if not ( + is_float(periods) + # error: "int" has no attribute "is_integer" + and periods.is_integer() # type: ignore[attr-defined] + ): raise ValueError("periods must be an integer") periods = int(periods)