Skip to content

Commit f04da3c

Browse files
authored
BUG: DatetimeIndex.diff raising TypeError (#55761)
* BUG: DatetimeIndex.diff raising TypeError * add test and whatsnew * typing * use Index
1 parent 386a1eb commit f04da3c

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

doc/source/whatsnew/v2.1.3.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Fixed regressions
2121

2222
Bug fixes
2323
~~~~~~~~~
24-
-
24+
- Bug in :meth:`DatetimeIndex.diff` raising ``TypeError`` (:issue:`55080`)
2525
-
2626

2727
.. ---------------------------------------------------------------------------

pandas/core/indexes/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -6991,7 +6991,7 @@ def infer_objects(self, copy: bool = True) -> Index:
69916991
return result
69926992

69936993
@final
6994-
def diff(self, periods: int = 1) -> Self:
6994+
def diff(self, periods: int = 1) -> Index:
69956995
"""
69966996
Computes the difference between consecutive values in the Index object.
69976997
@@ -7017,7 +7017,7 @@ def diff(self, periods: int = 1) -> Self:
70177017
Index([nan, 10.0, 10.0, 10.0, 10.0], dtype='float64')
70187018
70197019
"""
7020-
return self._constructor(self.to_series().diff(periods))
7020+
return Index(self.to_series().diff(periods))
70217021

70227022
@final
70237023
def round(self, decimals: int = 0) -> Self:

pandas/tests/indexes/test_datetimelike.py

+8
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,11 @@ def test_where_cast_str(self, simple_index):
159159

160160
result = index.where(mask, ["foo"])
161161
tm.assert_index_equal(result, expected)
162+
163+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
164+
def test_diff(self, unit):
165+
# GH 55080
166+
dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
167+
result = dti.diff(1)
168+
expected = pd.TimedeltaIndex([pd.NaT, 10, 10], unit=unit).as_unit(unit)
169+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)