Skip to content

Commit

Permalink
BUG: DatetimeIndex.diff raising TypeError (pandas-dev#55761)
Browse files Browse the repository at this point in the history
* BUG: DatetimeIndex.diff raising TypeError

* add test and whatsnew

* typing

* use Index

(cherry picked from commit f04da3c)
  • Loading branch information
lukemanley committed Nov 4, 2023
1 parent b3ae92d commit e09b84e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.1.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Fixed regressions

Bug fixes
~~~~~~~~~
-
- Bug in :meth:`DatetimeIndex.diff` raising ``TypeError`` (:issue:`55080`)
-

.. ---------------------------------------------------------------------------
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7024,7 +7024,8 @@ def infer_objects(self, copy: bool = True) -> Index:
result._references.add_index_reference(result)
return result

def diff(self, periods: int = 1):
@final
def diff(self, periods: int = 1) -> Index:
"""
Computes the difference between consecutive values in the Index object.
Expand All @@ -7050,7 +7051,7 @@ def diff(self, periods: int = 1):
Index([nan, 10.0, 10.0, 10.0, 10.0], dtype='float64')
"""
return self._constructor(self.to_series().diff(periods))
return Index(self.to_series().diff(periods))

def round(self, decimals: int = 0):
"""
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,11 @@ def test_where_cast_str(self, simple_index):

result = index.where(mask, ["foo"])
tm.assert_index_equal(result, expected)

@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_diff(self, unit):
# GH 55080
dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
result = dti.diff(1)
expected = pd.TimedeltaIndex([pd.NaT, 10, 10], unit=unit).as_unit(unit)
tm.assert_index_equal(result, expected)

0 comments on commit e09b84e

Please sign in to comment.