TimedeltaIndex#

class TimedeltaIndex#

Immutable ndarray-like of timedelta64 data.

Example#

import pandasCore as pd

# Create TimedeltaIndex
idx = pd.TimedeltaIndex([1, 2, 3], name='my_index')
print(len(idx))  # 3

Attributes#

Attribute

Description

Example

components

Return a DataFrame of the components (days, hours, minutes, etc.)

days

Number of days for each element

dtype

Return the dtype object of the underlying data

empty

Indicator whether TimedeltaIndex is empty

has_duplicates

Return if the index has duplicate values

is_monotonic_decreasing

Return if the index is monotonic decreasing

is_monotonic_increasing

Return if the index is monotonic increasing

is_unique

Return if the index has unique values

microseconds

Number of microseconds (0-999999) for each element

name

Return the name of the TimedeltaIndex

nanoseconds

Number of nanoseconds (0-999) for each element

ndim

Number of dimensions of the underlying data

nlevels

Number of levels in this index

seconds

Number of seconds (0-86399) for each element

shape

Return a tuple of the shape of the underlying data

size

Return the number of elements in the TimedeltaIndex

str

Vectorized string functions for Index.

View

Construction#

Method

Description

Example

__init__() (*args, **kwargs) | () | (data: object = None, unit: object = None, freq: object = None, closed: object = None, dtype: object = None, copy: bool = False, name: object = None)

Create an empty TimedeltaIndex

View

Indexing / Selection#

Method

Description

Example

__getitem__() (arg0: object)

take() (indices: collections.abc.Sequence[typing.SupportsInt], axis: object = 0, allow_fill: bool = True, fill_value: object = None, **kwargs)

Take elements at specified positions.

where() (cond: collections.abc.Sequence[bool], other: object = None)

Replace values where the condition is False.

Data Manipulation#

Method

Description

Example

drop() (labels: object, errors: str = 'raise')

Drop specified labels from index

droplevel() (level: typing.SupportsInt = 0)

Return index with requested level(s) removed.

insert() (loc: typing.SupportsInt, item: object)

Insert value at position

reindex() (target: object, method: object = None, level: object = None, limit: object = None, tolerance: object = None)

Create index with target’s values (move/add/delete values as necess…

rename() (name: object, *, inplace: bool = False)

Alter TimedeltaIndex name.

set_names() (names: object, *, level: object = None, inplace: bool = False)

Set TimedeltaIndex name

Missing Data#

Method

Description

Example

dropna() (how: str = 'any')

Return index with NA values removed.

fillna() (value: object = None, downcast: object = None)

Fill NA/NaT values with the specified value

isna() ()

Detect missing values

isnull() ()

Detect missing values (alias for isna)

notna() ()

Detect existing (non-missing) values

notnull() ()

Detect existing (non-missing) values (alias for notna)

Statistics#

Method

Description

Example

max() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the maximum value.

mean() (*, skipna: bool = True, axis: object = 0)

Return the mean of the values.

median() (skipna: bool = True)

Return the median of the values.

min() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the minimum value.

nunique() (dropna: bool = True)

Return number of unique elements

std() (*args, **kwargs)

Return standard deviation.

sum() (*args, **kwargs)

Return the sum of the values.

value_counts() (normalize: bool = False, sort: bool = True, ascending: bool = False, bins: object = None, dropna: bool = True)

Return a dict containing counts of unique values.

Aggregation#

Method

Description

Example

groupby() (values: object)

Group the index labels by a key function.

map() (mapper: collections.abc.Callable, na_action: object = None)

Map values using an input mapping or function.

Comparison#

Method

Description

Example

__eq__() (arg0: object)

__ge__() (arg0: object)

__gt__() (arg0: object)

__le__() (arg0: object)

__lt__() (arg0: object)

__ne__() (arg0: object)

equals() (other: pandasCore.TimedeltaIndex)

Check if this index equals another

Sorting#

Method

Description

Example

argsort() (*args, **kwargs)

Return indices that would sort the index

searchsorted() (value: object, side: str = 'left', sorter: object = None)

Find indices where elements should be inserted

sort_values() (*, return_indexer: bool = False, ascending: bool = True, na_position: str = 'last', key: object = None)

Sort values

Reshaping#

Method

Description

Example

to_frame() (index: bool = True, name: object = None)

Create a DataFrame with a column containing the Index.

transpose() (*args, **kwargs) | (*args, **kwargs) | (*args, **kwargs)

Return the transpose

Combining#

Method

Description

Example

append() (other: pandasCore.TimedeltaIndex)

Append another TimedeltaIndex

join() (other: pandasCore.TimedeltaIndex, *, how: str = 'left', level: object = None, return_indexers: bool = False, sort: bool = False)

Join with another index

Time Series#

Method

Description

Example

asof() (label: typing.SupportsInt)

Return the label at or before the given value

diff() (periods: typing.SupportsInt = 1)

Compute difference between consecutive elements

shift() (periods: typing.SupportsInt = 1, freq: str | None = None)

Shift index by desired number of periods.

I/O#

Method

Description

Example

to_flat_index() ()

Convert a MultiIndex to an Index of tuples

to_list() ()

Return a list of the TimedeltaIndex values as nanoseconds

to_numpy() (dtype: object = None, copy: bool = False, na_value: object = None, **kwargs)

A NumPy ndarray representing the values in this Index.

to_pytimedelta() (*args, **kwargs)

Return Timedelta representation for each element.

to_series() (index: object = None, name: object = None)

Create a Series with both index and values equal to the index keys.

tolist() ()

Return a list of the TimedeltaIndex values as nanoseconds

Conversion#

Method

Description

Example

astype() (dtype: object, copy: bool = True)

Cast to a specified dtype.

copy() (name: object = None, deep: bool = False)

Make a copy of this TimedeltaIndex.

infer_objects() (copy: bool = True)

Attempt to infer better dtypes for object columns.

view() (cls: object = None)

Return a view of the index.

Iteration#

Method

Description

Example

__contains__() (arg0: object)

__iter__() ()

__len__() ()

Set Operations#

Method

Description

Example

difference() (other: pandasCore.TimedeltaIndex, sort: object = None)

Return elements in self but not in other

drop_duplicates() (*, keep: str = 'first')

Return index with duplicate values removed.

duplicated() (keep: str = 'first')

Return boolean array marking duplicates

intersection() (other: pandasCore.TimedeltaIndex, sort: bool = False)

Form intersection with another index

isin() (values: object, level: object = None)

Check membership for each value

symmetric_difference() (other: pandasCore.TimedeltaIndex, result_name: object = None, sort: object = None)

Compute symmetric difference of two Index objects.

union() (other: pandasCore.TimedeltaIndex, sort: object = None)

Form union with another index

unique() (level: object = None)

Return unique values in the index.

Datetime Methods#

Method

Description

Example

ceil() (*args, **kwargs)

Perform ceil operation on the data to the specified freq.

floor() (*args, **kwargs)

Perform floor operation on the data to the specified freq.

round() (*args, **kwargs)

Perform round operation on the data to the specified freq.

Other Methods#

Method

Description

Example

__hash__()

__repr__() ()

__str__() ()

all() (*args, **kwargs)

Return whether all elements are truthy (non-zero)

any() (*args, **kwargs)

Return whether any element is truthy (non-zero)

argmax() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the position of the maximum value.

argmin() (axis: object = None, skipna: bool = True, *args, **kwargs)

Return the position of the minimum value.

as_unit() (unit: str)

Convert to a new unit resolution.

asof_locs() (where: collections.abc.Sequence[typing.SupportsInt], mask: collections.abc.Sequence[bool] | None = None)

Return the locations (indices) of labels in the index.

delete() (loc: typing.SupportsInt)

Delete element at specified position

factorize() (sort: bool = False, use_na_sentinel: bool = True)

Encode the index as an enumerated type

format() (name: bool = False, formatter: object = None, na_rep: str = 'NaT', date_format: object = None)

Format index as vector of strings

get_indexer() (target: pandasCore.TimedeltaIndex, method: object = None, limit: object = None, tolerance: object = None)

Compute indexer for target index

get_indexer_for() (target: collections.abc.Sequence[typing.SupportsInt])

Get indexer for a list of values

get_indexer_non_unique() (target: pandasCore.TimedeltaIndex)

Compute indexer and mask for new index given the current index.

get_level_values() (level: object)

Return an Index of values for requested level.

get_loc() (key: typing.SupportsInt)

Get integer location for a label

get_slice_bound() (label: typing.SupportsInt, side: str)

Get slice bound for label

holds_integer() ()

Check if index holds integer values

identical() (other: pandasCore.TimedeltaIndex)

Check if two indexes are identical (values + name)

item() ()

Return the first element as a scalar

memory_usage() (deep: bool = False)

Return memory usage in bytes

putmask() (mask: collections.abc.Sequence[bool], value: typing.SupportsInt)

Return a new TimedeltaIndex with values put where mask is True.

ravel() (order: str = 'C')

Return a flattened array of the index values.

repeat() (repeats: typing.SupportsInt, axis: object = None)

Repeat elements of the index

slice() (start: typing.SupportsInt, stop: typing.SupportsInt, step: typing.SupportsInt = 1)

Slice the index

slice_indexer() (start: object = None, end: object = None, step: object = None)

Compute slice indexer for input labels.

slice_locs() (start: object = None, end: object = None, step: object = None)

Compute slice locations for input labels.

sort() (ascending: bool = True)

Return a sorted copy of the index.

sortlevel() (level: object = None, ascending: object = True, sort_remaining: object = None, na_position: str = 'first')

Sort index by level

total_seconds() (*args, **kwargs)

Return total duration of each element expressed in seconds.

Code Examples#

The following examples are extracted from the test suite.

str (test_timedelta_period_str.py:76)
66def test_timedeltaindex_str_call_with_data():
67    """Test TimedeltaIndex.str(data) call."""
68    print("Testing TimedeltaIndex.str(data) call...")
69
70    # Create a TimedeltaIndex
71    tdi = pandasCore.TimedeltaIndex(['1 days', '2 days'])
72
73    # Call TimedeltaIndex.str with the index as argument
74    try:
75        str_accessor = pandasCore.TimedeltaIndex.str(tdi)
76        print(f"  TimedeltaIndex.str(tdi) returned: {type(str_accessor)}")
77        print("  PASSED: TimedeltaIndex.str(data) call works")
78    except Exception as e:
79        # Expected to raise error since TimedeltaIndex doesn't contain strings
80        print(f"  Error (expected for non-string data): {e}")
81        print("  PASSED: Appropriate error raised for non-string Index")
82
83# =============================================================================
84# PeriodIndex.str tests
85# =============================================================================
__init__ (test_index_methods.py:23)
13    global tests_run
14    tests_run += 1
15    idx = pandasCore.Index([3, 1, 2])
16    result = idx.sort()
17    assert len(result) == 3, f"Expected 3 elements, got {len(result)}"
18
19def test_timedeltaindex_sortlevel():
20    """Test TimedeltaIndex.sortlevel"""
21    global tests_run
22    tests_run += 1
23    idx = pandasCore.TimedeltaIndex(['1 day', '2 days', '1 hour'])
24    result = idx.sortlevel()
25    # Returns tuple of (sorted_index, indexer)
26    assert len(result) == 2, f"Expected tuple of 2, got {len(result)}"
27
28def test_timedeltaindex_to_flat_index():
29    """Test TimedeltaIndex.to_flat_index"""
30    global tests_run
31    tests_run += 1
32    idx = pandasCore.TimedeltaIndex(['1 day', '2 days'])
33    result = idx.to_flat_index()