Skip to content

Commit 0bf70c7

Browse files
authored
Backport PR #55761 on branch 2.1.x (BUG: DatetimeIndex.diff raising TypeError) (#55819)
* Backport PR #55473: TST: sort index with sliced MultiIndex * BUG: DatetimeIndex.diff raising TypeError (#55761) * BUG: DatetimeIndex.diff raising TypeError * add test and whatsnew * typing * use Index (cherry picked from commit f04da3c) * fix whatsnew
1 parent 8a616b9 commit 0bf70c7

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-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

+3-2
Original file line numberDiff line numberDiff line change
@@ -7024,7 +7024,8 @@ def infer_objects(self, copy: bool = True) -> Index:
70247024
result._references.add_index_reference(result)
70257025
return result
70267026

7027-
def diff(self, periods: int = 1):
7027+
@final
7028+
def diff(self, periods: int = 1) -> Index:
70287029
"""
70297030
Computes the difference between consecutive values in the Index object.
70307031
@@ -7050,7 +7051,7 @@ def diff(self, periods: int = 1):
70507051
Index([nan, 10.0, 10.0, 10.0, 10.0], dtype='float64')
70517052
70527053
"""
7053-
return self._constructor(self.to_series().diff(periods))
7054+
return Index(self.to_series().diff(periods))
70547055

70557056
def round(self, decimals: int = 0):
70567057
"""

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)