timedeltas.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. """ implement the TimedeltaIndex """
  2. from __future__ import annotations
  3. from pandas._libs import (
  4. index as libindex,
  5. lib,
  6. )
  7. from pandas._libs.tslibs import (
  8. Resolution,
  9. Timedelta,
  10. to_offset,
  11. )
  12. from pandas._typing import DtypeObj
  13. from pandas.core.dtypes.common import (
  14. is_dtype_equal,
  15. is_scalar,
  16. is_timedelta64_dtype,
  17. )
  18. from pandas.core.dtypes.generic import ABCSeries
  19. from pandas.core.arrays import datetimelike as dtl
  20. from pandas.core.arrays.timedeltas import TimedeltaArray
  21. import pandas.core.common as com
  22. from pandas.core.indexes.base import (
  23. Index,
  24. maybe_extract_name,
  25. )
  26. from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin
  27. from pandas.core.indexes.extension import inherit_names
  28. @inherit_names(
  29. ["__neg__", "__pos__", "__abs__", "total_seconds", "round", "floor", "ceil"]
  30. + TimedeltaArray._field_ops,
  31. TimedeltaArray,
  32. wrap=True,
  33. )
  34. @inherit_names(
  35. [
  36. "components",
  37. "to_pytimedelta",
  38. "sum",
  39. "std",
  40. "median",
  41. "_format_native_types",
  42. ],
  43. TimedeltaArray,
  44. )
  45. class TimedeltaIndex(DatetimeTimedeltaMixin):
  46. """
  47. Immutable Index of timedelta64 data.
  48. Represented internally as int64, and scalars returned Timedelta objects.
  49. Parameters
  50. ----------
  51. data : array-like (1-dimensional), optional
  52. Optional timedelta-like data to construct index with.
  53. unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional
  54. Which is an integer/float number.
  55. freq : str or pandas offset object, optional
  56. One of pandas date offset strings or corresponding objects. The string
  57. 'infer' can be passed in order to set the frequency of the index as the
  58. inferred frequency upon creation.
  59. copy : bool
  60. Make a copy of input ndarray.
  61. name : object
  62. Name to be stored in the index.
  63. Attributes
  64. ----------
  65. days
  66. seconds
  67. microseconds
  68. nanoseconds
  69. components
  70. inferred_freq
  71. Methods
  72. -------
  73. to_pytimedelta
  74. to_series
  75. round
  76. floor
  77. ceil
  78. to_frame
  79. mean
  80. See Also
  81. --------
  82. Index : The base pandas Index type.
  83. Timedelta : Represents a duration between two dates or times.
  84. DatetimeIndex : Index of datetime64 data.
  85. PeriodIndex : Index of Period data.
  86. timedelta_range : Create a fixed-frequency TimedeltaIndex.
  87. Notes
  88. -----
  89. To learn more about the frequency strings, please see `this link
  90. <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
  91. """
  92. _typ = "timedeltaindex"
  93. _data_cls = TimedeltaArray
  94. @property
  95. def _engine_type(self) -> type[libindex.TimedeltaEngine]:
  96. return libindex.TimedeltaEngine
  97. _data: TimedeltaArray
  98. # Use base class method instead of DatetimeTimedeltaMixin._get_string_slice
  99. _get_string_slice = Index._get_string_slice
  100. # error: Signature of "_resolution_obj" incompatible with supertype
  101. # "DatetimeIndexOpsMixin"
  102. @property
  103. def _resolution_obj(self) -> Resolution | None: # type: ignore[override]
  104. return self._data._resolution_obj
  105. # -------------------------------------------------------------------
  106. # Constructors
  107. def __new__(
  108. cls,
  109. data=None,
  110. unit=None,
  111. freq=lib.no_default,
  112. closed=None,
  113. dtype=None,
  114. copy: bool = False,
  115. name=None,
  116. ):
  117. name = maybe_extract_name(name, data, cls)
  118. if is_scalar(data):
  119. cls._raise_scalar_data_error(data)
  120. if unit in {"Y", "y", "M"}:
  121. raise ValueError(
  122. "Units 'M', 'Y', and 'y' are no longer supported, as they do not "
  123. "represent unambiguous timedelta values durations."
  124. )
  125. if (
  126. isinstance(data, TimedeltaArray)
  127. and freq is lib.no_default
  128. and (dtype is None or is_dtype_equal(dtype, data.dtype))
  129. ):
  130. if copy:
  131. data = data.copy()
  132. return cls._simple_new(data, name=name)
  133. if (
  134. isinstance(data, TimedeltaIndex)
  135. and freq is lib.no_default
  136. and name is None
  137. and (dtype is None or is_dtype_equal(dtype, data.dtype))
  138. ):
  139. if copy:
  140. return data.copy()
  141. else:
  142. return data._view()
  143. # - Cases checked above all return/raise before reaching here - #
  144. tdarr = TimedeltaArray._from_sequence_not_strict(
  145. data, freq=freq, unit=unit, dtype=dtype, copy=copy
  146. )
  147. refs = None
  148. if not copy and isinstance(data, (ABCSeries, Index)):
  149. refs = data._references
  150. return cls._simple_new(tdarr, name=name, refs=refs)
  151. # -------------------------------------------------------------------
  152. def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
  153. """
  154. Can we compare values of the given dtype to our own?
  155. """
  156. return is_timedelta64_dtype(dtype) # aka self._data._is_recognized_dtype
  157. # -------------------------------------------------------------------
  158. # Indexing Methods
  159. def get_loc(self, key):
  160. """
  161. Get integer location for requested label
  162. Returns
  163. -------
  164. loc : int, slice, or ndarray[int]
  165. """
  166. self._check_indexing_error(key)
  167. try:
  168. key = self._data._validate_scalar(key, unbox=False)
  169. except TypeError as err:
  170. raise KeyError(key) from err
  171. return Index.get_loc(self, key)
  172. def _parse_with_reso(self, label: str):
  173. # the "with_reso" is a no-op for TimedeltaIndex
  174. parsed = Timedelta(label)
  175. return parsed, None
  176. def _parsed_string_to_bounds(self, reso, parsed: Timedelta):
  177. # reso is unused, included to match signature of DTI/PI
  178. lbound = parsed.round(parsed.resolution_string)
  179. rbound = lbound + to_offset(parsed.resolution_string) - Timedelta(1, "ns")
  180. return lbound, rbound
  181. # -------------------------------------------------------------------
  182. @property
  183. def inferred_type(self) -> str:
  184. return "timedelta64"
  185. def timedelta_range(
  186. start=None,
  187. end=None,
  188. periods: int | None = None,
  189. freq=None,
  190. name=None,
  191. closed=None,
  192. *,
  193. unit: str | None = None,
  194. ) -> TimedeltaIndex:
  195. """
  196. Return a fixed frequency TimedeltaIndex with day as the default.
  197. Parameters
  198. ----------
  199. start : str or timedelta-like, default None
  200. Left bound for generating timedeltas.
  201. end : str or timedelta-like, default None
  202. Right bound for generating timedeltas.
  203. periods : int, default None
  204. Number of periods to generate.
  205. freq : str or DateOffset, default 'D'
  206. Frequency strings can have multiples, e.g. '5H'.
  207. name : str, default None
  208. Name of the resulting TimedeltaIndex.
  209. closed : str, default None
  210. Make the interval closed with respect to the given frequency to
  211. the 'left', 'right', or both sides (None).
  212. unit : str, default None
  213. Specify the desired resolution of the result.
  214. .. versionadded:: 2.0.0
  215. Returns
  216. -------
  217. TimedeltaIndex
  218. Notes
  219. -----
  220. Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,
  221. exactly three must be specified. If ``freq`` is omitted, the resulting
  222. ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between
  223. ``start`` and ``end`` (closed on both sides).
  224. To learn more about the frequency strings, please see `this link
  225. <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
  226. Examples
  227. --------
  228. >>> pd.timedelta_range(start='1 day', periods=4)
  229. TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'],
  230. dtype='timedelta64[ns]', freq='D')
  231. The ``closed`` parameter specifies which endpoint is included. The default
  232. behavior is to include both endpoints.
  233. >>> pd.timedelta_range(start='1 day', periods=4, closed='right')
  234. TimedeltaIndex(['2 days', '3 days', '4 days'],
  235. dtype='timedelta64[ns]', freq='D')
  236. The ``freq`` parameter specifies the frequency of the TimedeltaIndex.
  237. Only fixed frequencies can be passed, non-fixed frequencies such as
  238. 'M' (month end) will raise.
  239. >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H')
  240. TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00',
  241. '1 days 18:00:00', '2 days 00:00:00'],
  242. dtype='timedelta64[ns]', freq='6H')
  243. Specify ``start``, ``end``, and ``periods``; the frequency is generated
  244. automatically (linearly spaced).
  245. >>> pd.timedelta_range(start='1 day', end='5 days', periods=4)
  246. TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00',
  247. '5 days 00:00:00'],
  248. dtype='timedelta64[ns]', freq=None)
  249. **Specify a unit**
  250. >>> pd.timedelta_range("1 Day", periods=3, freq="100000D", unit="s")
  251. TimedeltaIndex(['1 days 00:00:00', '100001 days 00:00:00',
  252. '200001 days 00:00:00'],
  253. dtype='timedelta64[s]', freq='100000D')
  254. """
  255. if freq is None and com.any_none(periods, start, end):
  256. freq = "D"
  257. freq, _ = dtl.maybe_infer_freq(freq)
  258. tdarr = TimedeltaArray._generate_range(
  259. start, end, periods, freq, closed=closed, unit=unit
  260. )
  261. return TimedeltaIndex._simple_new(tdarr, name=name)