📜  Python| Pandas TimedeltaIndex.difference(1)

📅  最后修改于: 2023-12-03 15:04:22.120000             🧑  作者: Mango

Python | Pandas TimedeltaIndex.difference

The TimedeltaIndex class in Pandas provides a way to represent an index of durations or differences. The difference() function of this class returns the difference between the consecutive elements of this index.

Syntax
TimedeltaIndex.difference(self, periods=1, axis=0)
Parameters
  • periods: The number of periods to shift by. Defaults to 1.
  • axis: The axis to operate on. Defaults to 0.
Returns

A TimedeltaIndex representing the differences between consecutive elements of the original index.

Example
import pandas as pd
from datetime import timedelta

# Create a timedelta index
tdi = pd.TimedeltaIndex([timedelta(days=1), timedelta(hours=6), timedelta(minutes=30), timedelta(seconds=10)])
print(tdi)

# Get the difference between consecutive elements
diff = tdi.difference()
print(diff)

Output:

TimedeltaIndex(['1 days', '0 days 06:00:00', '0 days 00:30:00', '0 days 00:00:10'], dtype='timedelta64[ns]', freq=None)
TimedeltaIndex(['0 days 17:00:00', '0 days 05:30:00', '0 days 00:29:50'], dtype='timedelta64[ns]', freq=None)

In the above example, we create a TimedeltaIndex with four elements of different durations. We then call the difference() function to get the difference between consecutive elements. The resulting TimedeltaIndex contains the differences as expected.

Note that the first element of the resulting TimedeltaIndex is 0 days 17:00:00 because that is the difference between the second and first elements of the original index. Similarly, the second element of the resulting TimedeltaIndex is 0 days 05:30:00 because that is the difference between the third and second elements of the original index, and so on.