TimedeltaIndex ============== .. currentmodule:: pandasCore .. class:: TimedeltaIndex Immutable ndarray-like of timedelta64 data. Example ------- .. code-block:: python import pandasCore as pd # Create TimedeltaIndex idx = pd.TimedeltaIndex([1, 2, 3], name='my_index') print(len(idx)) # 3 Attributes ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Attribute - Description - Example * - :attr:`~TimedeltaIndex.components` - Return a DataFrame of the components (days, hours, minutes, etc.) - * - :attr:`~TimedeltaIndex.days` - Number of days for each element - * - :attr:`~TimedeltaIndex.dtype` - Return the dtype object of the underlying data - * - :attr:`~TimedeltaIndex.empty` - Indicator whether TimedeltaIndex is empty - * - :attr:`~TimedeltaIndex.has_duplicates` - Return if the index has duplicate values - * - :attr:`~TimedeltaIndex.is_monotonic_decreasing` - Return if the index is monotonic decreasing - * - :attr:`~TimedeltaIndex.is_monotonic_increasing` - Return if the index is monotonic increasing - * - :attr:`~TimedeltaIndex.is_unique` - Return if the index has unique values - * - :attr:`~TimedeltaIndex.microseconds` - Number of microseconds (0-999999) for each element - * - :attr:`~TimedeltaIndex.name` - Return the name of the TimedeltaIndex - * - :attr:`~TimedeltaIndex.nanoseconds` - Number of nanoseconds (0-999) for each element - * - :attr:`~TimedeltaIndex.ndim` - Number of dimensions of the underlying data - * - :attr:`~TimedeltaIndex.nlevels` - Number of levels in this index - * - :attr:`~TimedeltaIndex.seconds` - Number of seconds (0-86399) for each element - * - :attr:`~TimedeltaIndex.shape` - Return a tuple of the shape of the underlying data - * - :attr:`~TimedeltaIndex.size` - Return the number of elements in the TimedeltaIndex - * - :attr:`~TimedeltaIndex.str` - Vectorized string functions for Index. - :ref:`View ` Construction ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.__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 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.__getitem__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.take` ``(indices: collections.abc.Sequence[typing.SupportsInt], axis: object = 0, allow_fill: bool = True, fill_value: object = None, **kwargs)`` - Take elements at specified positions. - * - :meth:`~TimedeltaIndex.where` ``(cond: collections.abc.Sequence[bool], other: object = None)`` - Replace values where the condition is False. - Data Manipulation ----------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.drop` ``(labels: object, errors: str = 'raise')`` - Drop specified labels from index - * - :meth:`~TimedeltaIndex.droplevel` ``(level: typing.SupportsInt = 0)`` - Return index with requested level(s) removed. - * - :meth:`~TimedeltaIndex.insert` ``(loc: typing.SupportsInt, item: object)`` - Insert value at position - * - :meth:`~TimedeltaIndex.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... - * - :meth:`~TimedeltaIndex.rename` ``(name: object, *, inplace: bool = False)`` - Alter TimedeltaIndex name. - * - :meth:`~TimedeltaIndex.set_names` ``(names: object, *, level: object = None, inplace: bool = False)`` - Set TimedeltaIndex name - Missing Data ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.dropna` ``(how: str = 'any')`` - Return index with NA values removed. - * - :meth:`~TimedeltaIndex.fillna` ``(value: object = None, downcast: object = None)`` - Fill NA/NaT values with the specified value - * - :meth:`~TimedeltaIndex.isna` ``()`` - Detect missing values - * - :meth:`~TimedeltaIndex.isnull` ``()`` - Detect missing values (alias for isna) - * - :meth:`~TimedeltaIndex.notna` ``()`` - Detect existing (non-missing) values - * - :meth:`~TimedeltaIndex.notnull` ``()`` - Detect existing (non-missing) values (alias for notna) - Statistics ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.max` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the maximum value. - * - :meth:`~TimedeltaIndex.mean` ``(*, skipna: bool = True, axis: object = 0)`` - Return the mean of the values. - * - :meth:`~TimedeltaIndex.median` ``(skipna: bool = True)`` - Return the median of the values. - * - :meth:`~TimedeltaIndex.min` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the minimum value. - * - :meth:`~TimedeltaIndex.nunique` ``(dropna: bool = True)`` - Return number of unique elements - * - :meth:`~TimedeltaIndex.std` ``(*args, **kwargs)`` - Return standard deviation. - * - :meth:`~TimedeltaIndex.sum` ``(*args, **kwargs)`` - Return the sum of the values. - * - :meth:`~TimedeltaIndex.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 ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.groupby` ``(values: object)`` - Group the index labels by a key function. - * - :meth:`~TimedeltaIndex.map` ``(mapper: collections.abc.Callable, na_action: object = None)`` - Map values using an input mapping or function. - Comparison ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.__eq__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.__ge__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.__gt__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.__le__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.__lt__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.__ne__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.equals` ``(other: pandasCore.TimedeltaIndex)`` - Check if this index equals another - Sorting ------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.argsort` ``(*args, **kwargs)`` - Return indices that would sort the index - * - :meth:`~TimedeltaIndex.searchsorted` ``(value: object, side: str = 'left', sorter: object = None)`` - Find indices where elements should be inserted - * - :meth:`~TimedeltaIndex.sort_values` ``(*, return_indexer: bool = False, ascending: bool = True, na_position: str = 'last', key: object = None)`` - Sort values - Reshaping --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.to_frame` ``(index: bool = True, name: object = None)`` - Create a DataFrame with a column containing the Index. - * - :meth:`~TimedeltaIndex.transpose` ``(*args, **kwargs) | (*args, **kwargs) | (*args, **kwargs)`` - Return the transpose - Combining --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.append` ``(other: pandasCore.TimedeltaIndex)`` - Append another TimedeltaIndex - * - :meth:`~TimedeltaIndex.join` ``(other: pandasCore.TimedeltaIndex, *, how: str = 'left', level: object = None, return_indexers: bool = False, sort: bool = False)`` - Join with another index - Time Series ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.asof` ``(label: typing.SupportsInt)`` - Return the label at or before the given value - * - :meth:`~TimedeltaIndex.diff` ``(periods: typing.SupportsInt = 1)`` - Compute difference between consecutive elements - * - :meth:`~TimedeltaIndex.shift` ``(periods: typing.SupportsInt = 1, freq: str | None = None)`` - Shift index by desired number of periods. - I/O --- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.to_flat_index` ``()`` - Convert a MultiIndex to an Index of tuples - * - :meth:`~TimedeltaIndex.to_list` ``()`` - Return a list of the TimedeltaIndex values as nanoseconds - * - :meth:`~TimedeltaIndex.to_numpy` ``(dtype: object = None, copy: bool = False, na_value: object = None, **kwargs)`` - A NumPy ndarray representing the values in this Index. - * - :meth:`~TimedeltaIndex.to_pytimedelta` ``(*args, **kwargs)`` - Return Timedelta representation for each element. - * - :meth:`~TimedeltaIndex.to_series` ``(index: object = None, name: object = None)`` - Create a Series with both index and values equal to the index keys. - * - :meth:`~TimedeltaIndex.tolist` ``()`` - Return a list of the TimedeltaIndex values as nanoseconds - Conversion ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.astype` ``(dtype: object, copy: bool = True)`` - Cast to a specified dtype. - * - :meth:`~TimedeltaIndex.copy` ``(name: object = None, deep: bool = False)`` - Make a copy of this TimedeltaIndex. - * - :meth:`~TimedeltaIndex.infer_objects` ``(copy: bool = True)`` - Attempt to infer better dtypes for object columns. - * - :meth:`~TimedeltaIndex.view` ``(cls: object = None)`` - Return a view of the index. - Iteration --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.__contains__` ``(arg0: object)`` - - * - :meth:`~TimedeltaIndex.__iter__` ``()`` - - * - :meth:`~TimedeltaIndex.__len__` ``()`` - - Set Operations -------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.difference` ``(other: pandasCore.TimedeltaIndex, sort: object = None)`` - Return elements in self but not in other - * - :meth:`~TimedeltaIndex.drop_duplicates` ``(*, keep: str = 'first')`` - Return index with duplicate values removed. - * - :meth:`~TimedeltaIndex.duplicated` ``(keep: str = 'first')`` - Return boolean array marking duplicates - * - :meth:`~TimedeltaIndex.intersection` ``(other: pandasCore.TimedeltaIndex, sort: bool = False)`` - Form intersection with another index - * - :meth:`~TimedeltaIndex.isin` ``(values: object, level: object = None)`` - Check membership for each value - * - :meth:`~TimedeltaIndex.symmetric_difference` ``(other: pandasCore.TimedeltaIndex, result_name: object = None, sort: object = None)`` - Compute symmetric difference of two Index objects. - * - :meth:`~TimedeltaIndex.union` ``(other: pandasCore.TimedeltaIndex, sort: object = None)`` - Form union with another index - * - :meth:`~TimedeltaIndex.unique` ``(level: object = None)`` - Return unique values in the index. - Datetime Methods ---------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.ceil` ``(*args, **kwargs)`` - Perform ceil operation on the data to the specified freq. - * - :meth:`~TimedeltaIndex.floor` ``(*args, **kwargs)`` - Perform floor operation on the data to the specified freq. - * - :meth:`~TimedeltaIndex.round` ``(*args, **kwargs)`` - Perform round operation on the data to the specified freq. - Other Methods ------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~TimedeltaIndex.__hash__` - - * - :meth:`~TimedeltaIndex.__repr__` ``()`` - - * - :meth:`~TimedeltaIndex.__str__` ``()`` - - * - :meth:`~TimedeltaIndex.all` ``(*args, **kwargs)`` - Return whether all elements are truthy (non-zero) - * - :meth:`~TimedeltaIndex.any` ``(*args, **kwargs)`` - Return whether any element is truthy (non-zero) - * - :meth:`~TimedeltaIndex.argmax` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the position of the maximum value. - * - :meth:`~TimedeltaIndex.argmin` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return the position of the minimum value. - * - :meth:`~TimedeltaIndex.as_unit` ``(unit: str)`` - Convert to a new unit resolution. - * - :meth:`~TimedeltaIndex.asof_locs` ``(where: collections.abc.Sequence[typing.SupportsInt], mask: collections.abc.Sequence[bool] | None = None)`` - Return the locations (indices) of labels in the index. - * - :meth:`~TimedeltaIndex.delete` ``(loc: typing.SupportsInt)`` - Delete element at specified position - * - :meth:`~TimedeltaIndex.factorize` ``(sort: bool = False, use_na_sentinel: bool = True)`` - Encode the index as an enumerated type - * - :meth:`~TimedeltaIndex.format` ``(name: bool = False, formatter: object = None, na_rep: str = 'NaT', date_format: object = None)`` - Format index as vector of strings - * - :meth:`~TimedeltaIndex.get_indexer` ``(target: pandasCore.TimedeltaIndex, method: object = None, limit: object = None, tolerance: object = None)`` - Compute indexer for target index - * - :meth:`~TimedeltaIndex.get_indexer_for` ``(target: collections.abc.Sequence[typing.SupportsInt])`` - Get indexer for a list of values - * - :meth:`~TimedeltaIndex.get_indexer_non_unique` ``(target: pandasCore.TimedeltaIndex)`` - Compute indexer and mask for new index given the current index. - * - :meth:`~TimedeltaIndex.get_level_values` ``(level: object)`` - Return an Index of values for requested level. - * - :meth:`~TimedeltaIndex.get_loc` ``(key: typing.SupportsInt)`` - Get integer location for a label - * - :meth:`~TimedeltaIndex.get_slice_bound` ``(label: typing.SupportsInt, side: str)`` - Get slice bound for label - * - :meth:`~TimedeltaIndex.holds_integer` ``()`` - Check if index holds integer values - * - :meth:`~TimedeltaIndex.identical` ``(other: pandasCore.TimedeltaIndex)`` - Check if two indexes are identical (values + name) - * - :meth:`~TimedeltaIndex.item` ``()`` - Return the first element as a scalar - * - :meth:`~TimedeltaIndex.memory_usage` ``(deep: bool = False)`` - Return memory usage in bytes - * - :meth:`~TimedeltaIndex.putmask` ``(mask: collections.abc.Sequence[bool], value: typing.SupportsInt)`` - Return a new TimedeltaIndex with values put where mask is True. - * - :meth:`~TimedeltaIndex.ravel` ``(order: str = 'C')`` - Return a flattened array of the index values. - * - :meth:`~TimedeltaIndex.repeat` ``(repeats: typing.SupportsInt, axis: object = None)`` - Repeat elements of the index - * - :meth:`~TimedeltaIndex.slice` ``(start: typing.SupportsInt, stop: typing.SupportsInt, step: typing.SupportsInt = 1)`` - Slice the index - * - :meth:`~TimedeltaIndex.slice_indexer` ``(start: object = None, end: object = None, step: object = None)`` - Compute slice indexer for input labels. - * - :meth:`~TimedeltaIndex.slice_locs` ``(start: object = None, end: object = None, step: object = None)`` - Compute slice locations for input labels. - * - :meth:`~TimedeltaIndex.sort` ``(ascending: bool = True)`` - Return a sorted copy of the index. - * - :meth:`~TimedeltaIndex.sortlevel` ``(level: object = None, ascending: object = True, sort_remaining: object = None, na_position: str = 'first')`` - Sort index by level - * - :meth:`~TimedeltaIndex.total_seconds` ``(*args, **kwargs)`` - Return total duration of each element expressed in seconds. - Code Examples ------------- The following examples are extracted from the test suite. .. _example-timedeltaindex-str-0: .. dropdown:: str (test_timedelta_period_str.py:76) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 66 :emphasize-lines: 11 def test_timedeltaindex_str_call_with_data(): """Test TimedeltaIndex.str(data) call.""" print("Testing TimedeltaIndex.str(data) call...") # Create a TimedeltaIndex tdi = pandasCore.TimedeltaIndex(['1 days', '2 days']) # Call TimedeltaIndex.str with the index as argument try: str_accessor = pandasCore.TimedeltaIndex.str(tdi) print(f" TimedeltaIndex.str(tdi) returned: {type(str_accessor)}") print(" PASSED: TimedeltaIndex.str(data) call works") except Exception as e: # Expected to raise error since TimedeltaIndex doesn't contain strings print(f" Error (expected for non-string data): {e}") print(" PASSED: Appropriate error raised for non-string Index") # ============================================================================= # PeriodIndex.str tests # ============================================================================= .. _example-timedeltaindex-dunder-initdunder--1: .. dropdown:: __init__ (test_index_methods.py:23) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 13 :emphasize-lines: 11 global tests_run tests_run += 1 idx = pandasCore.Index([3, 1, 2]) result = idx.sort() assert len(result) == 3, f"Expected 3 elements, got {len(result)}" def test_timedeltaindex_sortlevel(): """Test TimedeltaIndex.sortlevel""" global tests_run tests_run += 1 idx = pandasCore.TimedeltaIndex(['1 day', '2 days', '1 hour']) result = idx.sortlevel() # Returns tuple of (sorted_index, indexer) assert len(result) == 2, f"Expected tuple of 2, got {len(result)}" def test_timedeltaindex_to_flat_index(): """Test TimedeltaIndex.to_flat_index""" global tests_run tests_run += 1 idx = pandasCore.TimedeltaIndex(['1 day', '2 days']) result = idx.to_flat_index()