timedeltas.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. """ implement the TimedeltaIndex """
  2. from datetime import datetime
  3. import warnings
  4. import numpy as np
  5. from pandas._libs import (
  6. NaT, Timedelta, index as libindex, join as libjoin, lib)
  7. import pandas.compat as compat
  8. from pandas.util._decorators import Appender, Substitution
  9. from pandas.core.dtypes.common import (
  10. _TD_DTYPE, ensure_int64, is_float, is_integer, is_list_like, is_scalar,
  11. is_timedelta64_dtype, is_timedelta64_ns_dtype, pandas_dtype)
  12. import pandas.core.dtypes.concat as _concat
  13. from pandas.core.dtypes.missing import isna
  14. from pandas.core.accessor import delegate_names
  15. from pandas.core.arrays import datetimelike as dtl
  16. from pandas.core.arrays.timedeltas import TimedeltaArray, _is_convertible_to_td
  17. from pandas.core.base import _shared_docs
  18. import pandas.core.common as com
  19. from pandas.core.indexes.base import Index, _index_shared_docs
  20. from pandas.core.indexes.datetimelike import (
  21. DatetimeIndexOpsMixin, DatetimelikeDelegateMixin, maybe_unwrap_index,
  22. wrap_arithmetic_op)
  23. from pandas.core.indexes.numeric import Int64Index
  24. from pandas.core.ops import get_op_result_name
  25. from pandas.tseries.frequencies import to_offset
  26. def _make_wrapped_arith_op(opname):
  27. meth = getattr(TimedeltaArray, opname)
  28. def method(self, other):
  29. result = meth(self._data, maybe_unwrap_index(other))
  30. return wrap_arithmetic_op(self, other, result)
  31. method.__name__ = opname
  32. return method
  33. class TimedeltaDelegateMixin(DatetimelikeDelegateMixin):
  34. # Most attrs are dispatched via datetimelike_{ops,methods}
  35. # Some are "raw" methods, the result is not not re-boxed in an Index
  36. # We also have a few "extra" attrs, which may or may not be raw,
  37. # which we we dont' want to expose in the .dt accessor.
  38. _delegate_class = TimedeltaArray
  39. _delegated_properties = (TimedeltaArray._datetimelike_ops + [
  40. 'components',
  41. ])
  42. _delegated_methods = TimedeltaArray._datetimelike_methods + [
  43. '_box_values',
  44. ]
  45. _raw_properties = {
  46. 'components',
  47. }
  48. _raw_methods = {
  49. 'to_pytimedelta',
  50. }
  51. @delegate_names(TimedeltaArray,
  52. TimedeltaDelegateMixin._delegated_properties,
  53. typ="property")
  54. @delegate_names(TimedeltaArray,
  55. TimedeltaDelegateMixin._delegated_methods,
  56. typ="method", overwrite=False)
  57. class TimedeltaIndex(DatetimeIndexOpsMixin, dtl.TimelikeOps, Int64Index,
  58. TimedeltaDelegateMixin):
  59. """
  60. Immutable ndarray of timedelta64 data, represented internally as int64, and
  61. which can be boxed to timedelta objects
  62. Parameters
  63. ----------
  64. data : array-like (1-dimensional), optional
  65. Optional timedelta-like data to construct index with
  66. unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional
  67. which is an integer/float number
  68. freq : string or pandas offset object, optional
  69. One of pandas date offset strings or corresponding objects. The string
  70. 'infer' can be passed in order to set the frequency of the index as the
  71. inferred frequency upon creation
  72. copy : bool
  73. Make a copy of input ndarray
  74. start : starting value, timedelta-like, optional
  75. If data is None, start is used as the start point in generating regular
  76. timedelta data.
  77. .. deprecated:: 0.24.0
  78. periods : int, optional, > 0
  79. Number of periods to generate, if generating index. Takes precedence
  80. over end argument
  81. .. deprecated:: 0.24.0
  82. end : end time, timedelta-like, optional
  83. If periods is none, generated index will extend to first conforming
  84. time on or just past end argument
  85. .. deprecated:: 0.24. 0
  86. closed : string or None, default None
  87. Make the interval closed with respect to the given frequency to
  88. the 'left', 'right', or both sides (None)
  89. .. deprecated:: 0.24. 0
  90. name : object
  91. Name to be stored in the index
  92. Attributes
  93. ----------
  94. days
  95. seconds
  96. microseconds
  97. nanoseconds
  98. components
  99. inferred_freq
  100. Methods
  101. -------
  102. to_pytimedelta
  103. to_series
  104. round
  105. floor
  106. ceil
  107. to_frame
  108. See Also
  109. ---------
  110. Index : The base pandas Index type.
  111. Timedelta : Represents a duration between two dates or times.
  112. DatetimeIndex : Index of datetime64 data.
  113. PeriodIndex : Index of Period data.
  114. timedelta_range : Create a fixed-frequency TimedeltaIndex.
  115. Notes
  116. -----
  117. To learn more about the frequency strings, please see `this link
  118. <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
  119. Creating a TimedeltaIndex based on `start`, `periods`, and `end` has
  120. been deprecated in favor of :func:`timedelta_range`.
  121. """
  122. _typ = 'timedeltaindex'
  123. _join_precedence = 10
  124. def _join_i8_wrapper(joinf, **kwargs):
  125. return DatetimeIndexOpsMixin._join_i8_wrapper(
  126. joinf, dtype='m8[ns]', **kwargs)
  127. _inner_indexer = _join_i8_wrapper(libjoin.inner_join_indexer_int64)
  128. _outer_indexer = _join_i8_wrapper(libjoin.outer_join_indexer_int64)
  129. _left_indexer = _join_i8_wrapper(libjoin.left_join_indexer_int64)
  130. _left_indexer_unique = _join_i8_wrapper(
  131. libjoin.left_join_indexer_unique_int64, with_indexers=False)
  132. _engine_type = libindex.TimedeltaEngine
  133. _comparables = ['name', 'freq']
  134. _attributes = ['name', 'freq']
  135. _is_numeric_dtype = True
  136. _infer_as_myclass = True
  137. _freq = None
  138. _box_func = TimedeltaArray._box_func
  139. _bool_ops = TimedeltaArray._bool_ops
  140. _object_ops = TimedeltaArray._object_ops
  141. _field_ops = TimedeltaArray._field_ops
  142. _datetimelike_ops = TimedeltaArray._datetimelike_ops
  143. _datetimelike_methods = TimedeltaArray._datetimelike_methods
  144. _other_ops = TimedeltaArray._other_ops
  145. # -------------------------------------------------------------------
  146. # Constructors
  147. def __new__(cls, data=None, unit=None, freq=None, start=None, end=None,
  148. periods=None, closed=None, dtype=_TD_DTYPE, copy=False,
  149. name=None, verify_integrity=None):
  150. if verify_integrity is not None:
  151. warnings.warn("The 'verify_integrity' argument is deprecated, "
  152. "will be removed in a future version.",
  153. FutureWarning, stacklevel=2)
  154. else:
  155. verify_integrity = True
  156. if data is None:
  157. freq, freq_infer = dtl.maybe_infer_freq(freq)
  158. warnings.warn("Creating a TimedeltaIndex by passing range "
  159. "endpoints is deprecated. Use "
  160. "`pandas.timedelta_range` instead.",
  161. FutureWarning, stacklevel=2)
  162. result = TimedeltaArray._generate_range(start, end, periods, freq,
  163. closed=closed)
  164. return cls._simple_new(result._data, freq=freq, name=name)
  165. if is_scalar(data):
  166. raise TypeError('{cls}() must be called with a '
  167. 'collection of some kind, {data} was passed'
  168. .format(cls=cls.__name__, data=repr(data)))
  169. if isinstance(data, TimedeltaArray):
  170. if copy:
  171. data = data.copy()
  172. return cls._simple_new(data, name=name, freq=freq)
  173. if (isinstance(data, TimedeltaIndex) and
  174. freq is None and name is None):
  175. if copy:
  176. return data.copy()
  177. else:
  178. return data._shallow_copy()
  179. # - Cases checked above all return/raise before reaching here - #
  180. tdarr = TimedeltaArray._from_sequence(data, freq=freq, unit=unit,
  181. dtype=dtype, copy=copy)
  182. return cls._simple_new(tdarr._data, freq=tdarr.freq, name=name)
  183. @classmethod
  184. def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
  185. # `dtype` is passed by _shallow_copy in corner cases, should always
  186. # be timedelta64[ns] if present
  187. if not isinstance(values, TimedeltaArray):
  188. values = TimedeltaArray._simple_new(values, dtype=dtype,
  189. freq=freq)
  190. else:
  191. if freq is None:
  192. freq = values.freq
  193. assert isinstance(values, TimedeltaArray), type(values)
  194. assert dtype == _TD_DTYPE, dtype
  195. assert values.dtype == 'm8[ns]', values.dtype
  196. tdarr = TimedeltaArray._simple_new(values._data, freq=freq)
  197. result = object.__new__(cls)
  198. result._data = tdarr
  199. result.name = name
  200. # For groupby perf. See note in indexes/base about _index_data
  201. result._index_data = tdarr._data
  202. result._reset_identity()
  203. return result
  204. # -------------------------------------------------------------------
  205. def __setstate__(self, state):
  206. """Necessary for making this object picklable"""
  207. if isinstance(state, dict):
  208. super(TimedeltaIndex, self).__setstate__(state)
  209. else:
  210. raise Exception("invalid pickle state")
  211. _unpickle_compat = __setstate__
  212. def _maybe_update_attributes(self, attrs):
  213. """ Update Index attributes (e.g. freq) depending on op """
  214. freq = attrs.get('freq', None)
  215. if freq is not None:
  216. # no need to infer if freq is None
  217. attrs['freq'] = 'infer'
  218. return attrs
  219. # -------------------------------------------------------------------
  220. # Rendering Methods
  221. @property
  222. def _formatter_func(self):
  223. from pandas.io.formats.format import _get_format_timedelta64
  224. return _get_format_timedelta64(self, box=True)
  225. def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs):
  226. from pandas.io.formats.format import Timedelta64Formatter
  227. return Timedelta64Formatter(values=self,
  228. nat_rep=na_rep,
  229. justify='all').get_result()
  230. # -------------------------------------------------------------------
  231. # Wrapping TimedeltaArray
  232. __mul__ = _make_wrapped_arith_op("__mul__")
  233. __rmul__ = _make_wrapped_arith_op("__rmul__")
  234. __floordiv__ = _make_wrapped_arith_op("__floordiv__")
  235. __rfloordiv__ = _make_wrapped_arith_op("__rfloordiv__")
  236. __mod__ = _make_wrapped_arith_op("__mod__")
  237. __rmod__ = _make_wrapped_arith_op("__rmod__")
  238. __divmod__ = _make_wrapped_arith_op("__divmod__")
  239. __rdivmod__ = _make_wrapped_arith_op("__rdivmod__")
  240. __truediv__ = _make_wrapped_arith_op("__truediv__")
  241. __rtruediv__ = _make_wrapped_arith_op("__rtruediv__")
  242. if compat.PY2:
  243. __div__ = __truediv__
  244. __rdiv__ = __rtruediv__
  245. # Compat for frequency inference, see GH#23789
  246. _is_monotonic_increasing = Index.is_monotonic_increasing
  247. _is_monotonic_decreasing = Index.is_monotonic_decreasing
  248. _is_unique = Index.is_unique
  249. @property
  250. def _box_func(self):
  251. return lambda x: Timedelta(x, unit='ns')
  252. def __getitem__(self, key):
  253. result = self._data.__getitem__(key)
  254. if is_scalar(result):
  255. return result
  256. return type(self)(result, name=self.name)
  257. # -------------------------------------------------------------------
  258. @Appender(_index_shared_docs['astype'])
  259. def astype(self, dtype, copy=True):
  260. dtype = pandas_dtype(dtype)
  261. if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype):
  262. # Have to repeat the check for 'timedelta64' (not ns) dtype
  263. # so that we can return a numeric index, since pandas will return
  264. # a TimedeltaIndex when dtype='timedelta'
  265. result = self._data.astype(dtype, copy=copy)
  266. if self.hasnans:
  267. return Index(result, name=self.name)
  268. return Index(result.astype('i8'), name=self.name)
  269. return DatetimeIndexOpsMixin.astype(self, dtype, copy=copy)
  270. def union(self, other):
  271. """
  272. Specialized union for TimedeltaIndex objects. If combine
  273. overlapping ranges with the same DateOffset, will be much
  274. faster than Index.union
  275. Parameters
  276. ----------
  277. other : TimedeltaIndex or array-like
  278. Returns
  279. -------
  280. y : Index or TimedeltaIndex
  281. """
  282. self._assert_can_do_setop(other)
  283. if len(other) == 0 or self.equals(other) or len(self) == 0:
  284. return super(TimedeltaIndex, self).union(other)
  285. if not isinstance(other, TimedeltaIndex):
  286. try:
  287. other = TimedeltaIndex(other)
  288. except (TypeError, ValueError):
  289. pass
  290. this, other = self, other
  291. if this._can_fast_union(other):
  292. return this._fast_union(other)
  293. else:
  294. result = Index.union(this, other)
  295. if isinstance(result, TimedeltaIndex):
  296. if result.freq is None:
  297. result.freq = to_offset(result.inferred_freq)
  298. return result
  299. def join(self, other, how='left', level=None, return_indexers=False,
  300. sort=False):
  301. """
  302. See Index.join
  303. """
  304. if _is_convertible_to_index(other):
  305. try:
  306. other = TimedeltaIndex(other)
  307. except (TypeError, ValueError):
  308. pass
  309. return Index.join(self, other, how=how, level=level,
  310. return_indexers=return_indexers,
  311. sort=sort)
  312. def _wrap_joined_index(self, joined, other):
  313. name = get_op_result_name(self, other)
  314. if (isinstance(other, TimedeltaIndex) and self.freq == other.freq and
  315. self._can_fast_union(other)):
  316. joined = self._shallow_copy(joined, name=name)
  317. return joined
  318. else:
  319. return self._simple_new(joined, name)
  320. def _can_fast_union(self, other):
  321. if not isinstance(other, TimedeltaIndex):
  322. return False
  323. freq = self.freq
  324. if freq is None or freq != other.freq:
  325. return False
  326. if not self.is_monotonic or not other.is_monotonic:
  327. return False
  328. if len(self) == 0 or len(other) == 0:
  329. return True
  330. # to make our life easier, "sort" the two ranges
  331. if self[0] <= other[0]:
  332. left, right = self, other
  333. else:
  334. left, right = other, self
  335. right_start = right[0]
  336. left_end = left[-1]
  337. # Only need to "adjoin", not overlap
  338. return (right_start == left_end + freq) or right_start in left
  339. def _fast_union(self, other):
  340. if len(other) == 0:
  341. return self.view(type(self))
  342. if len(self) == 0:
  343. return other.view(type(self))
  344. # to make our life easier, "sort" the two ranges
  345. if self[0] <= other[0]:
  346. left, right = self, other
  347. else:
  348. left, right = other, self
  349. left_end = left[-1]
  350. right_end = right[-1]
  351. # concatenate
  352. if left_end < right_end:
  353. loc = right.searchsorted(left_end, side='right')
  354. right_chunk = right.values[loc:]
  355. dates = _concat._concat_compat((left.values, right_chunk))
  356. return self._shallow_copy(dates)
  357. else:
  358. return left
  359. def intersection(self, other):
  360. """
  361. Specialized intersection for TimedeltaIndex objects. May be much faster
  362. than Index.intersection
  363. Parameters
  364. ----------
  365. other : TimedeltaIndex or array-like
  366. Returns
  367. -------
  368. y : Index or TimedeltaIndex
  369. """
  370. self._assert_can_do_setop(other)
  371. if self.equals(other):
  372. return self._get_reconciled_name_object(other)
  373. if not isinstance(other, TimedeltaIndex):
  374. try:
  375. other = TimedeltaIndex(other)
  376. except (TypeError, ValueError):
  377. pass
  378. result = Index.intersection(self, other)
  379. return result
  380. if len(self) == 0:
  381. return self
  382. if len(other) == 0:
  383. return other
  384. # to make our life easier, "sort" the two ranges
  385. if self[0] <= other[0]:
  386. left, right = self, other
  387. else:
  388. left, right = other, self
  389. end = min(left[-1], right[-1])
  390. start = right[0]
  391. if end < start:
  392. return type(self)(data=[])
  393. else:
  394. lslice = slice(*left.slice_locs(start, end))
  395. left_chunk = left.values[lslice]
  396. return self._shallow_copy(left_chunk)
  397. def _maybe_promote(self, other):
  398. if other.inferred_type == 'timedelta':
  399. other = TimedeltaIndex(other)
  400. return self, other
  401. def get_value(self, series, key):
  402. """
  403. Fast lookup of value from 1-dimensional ndarray. Only use this if you
  404. know what you're doing
  405. """
  406. if _is_convertible_to_td(key):
  407. key = Timedelta(key)
  408. return self.get_value_maybe_box(series, key)
  409. try:
  410. return com.maybe_box(self, Index.get_value(self, series, key),
  411. series, key)
  412. except KeyError:
  413. try:
  414. loc = self._get_string_slice(key)
  415. return series[loc]
  416. except (TypeError, ValueError, KeyError):
  417. pass
  418. try:
  419. return self.get_value_maybe_box(series, key)
  420. except (TypeError, ValueError, KeyError):
  421. raise KeyError(key)
  422. def get_value_maybe_box(self, series, key):
  423. if not isinstance(key, Timedelta):
  424. key = Timedelta(key)
  425. values = self._engine.get_value(com.values_from_object(series), key)
  426. return com.maybe_box(self, values, series, key)
  427. def get_loc(self, key, method=None, tolerance=None):
  428. """
  429. Get integer location for requested label
  430. Returns
  431. -------
  432. loc : int
  433. """
  434. if is_list_like(key) or (isinstance(key, datetime) and key is not NaT):
  435. # GH#20464 datetime check here is to ensure we don't allow
  436. # datetime objects to be incorrectly treated as timedelta
  437. # objects; NaT is a special case because it plays a double role
  438. # as Not-A-Timedelta
  439. raise TypeError
  440. if isna(key):
  441. key = NaT
  442. if tolerance is not None:
  443. # try converting tolerance now, so errors don't get swallowed by
  444. # the try/except clauses below
  445. tolerance = self._convert_tolerance(tolerance, np.asarray(key))
  446. if _is_convertible_to_td(key):
  447. key = Timedelta(key)
  448. return Index.get_loc(self, key, method, tolerance)
  449. try:
  450. return Index.get_loc(self, key, method, tolerance)
  451. except (KeyError, ValueError, TypeError):
  452. try:
  453. return self._get_string_slice(key)
  454. except (TypeError, KeyError, ValueError):
  455. pass
  456. try:
  457. stamp = Timedelta(key)
  458. return Index.get_loc(self, stamp, method, tolerance)
  459. except (KeyError, ValueError):
  460. raise KeyError(key)
  461. def _maybe_cast_slice_bound(self, label, side, kind):
  462. """
  463. If label is a string, cast it to timedelta according to resolution.
  464. Parameters
  465. ----------
  466. label : object
  467. side : {'left', 'right'}
  468. kind : {'ix', 'loc', 'getitem'}
  469. Returns
  470. -------
  471. label : object
  472. """
  473. assert kind in ['ix', 'loc', 'getitem', None]
  474. if isinstance(label, compat.string_types):
  475. parsed = Timedelta(label)
  476. lbound = parsed.round(parsed.resolution)
  477. if side == 'left':
  478. return lbound
  479. else:
  480. return (lbound + to_offset(parsed.resolution) -
  481. Timedelta(1, 'ns'))
  482. elif ((is_integer(label) or is_float(label)) and
  483. not is_timedelta64_dtype(label)):
  484. self._invalid_indexer('slice', label)
  485. return label
  486. def _get_string_slice(self, key):
  487. if is_integer(key) or is_float(key) or key is NaT:
  488. self._invalid_indexer('slice', key)
  489. loc = self._partial_td_slice(key)
  490. return loc
  491. def _partial_td_slice(self, key):
  492. # given a key, try to figure out a location for a partial slice
  493. if not isinstance(key, compat.string_types):
  494. return key
  495. raise NotImplementedError
  496. @Substitution(klass='TimedeltaIndex')
  497. @Appender(_shared_docs['searchsorted'])
  498. def searchsorted(self, value, side='left', sorter=None):
  499. if isinstance(value, (np.ndarray, Index)):
  500. value = np.array(value, dtype=_TD_DTYPE, copy=False)
  501. else:
  502. value = Timedelta(value).asm8.view(_TD_DTYPE)
  503. return self.values.searchsorted(value, side=side, sorter=sorter)
  504. def is_type_compatible(self, typ):
  505. return typ == self.inferred_type or typ == 'timedelta'
  506. @property
  507. def inferred_type(self):
  508. return 'timedelta64'
  509. @property
  510. def is_all_dates(self):
  511. return True
  512. def insert(self, loc, item):
  513. """
  514. Make new Index inserting new item at location
  515. Parameters
  516. ----------
  517. loc : int
  518. item : object
  519. if not either a Python datetime or a numpy integer-like, returned
  520. Index dtype will be object rather than datetime.
  521. Returns
  522. -------
  523. new_index : Index
  524. """
  525. # try to convert if possible
  526. if _is_convertible_to_td(item):
  527. try:
  528. item = Timedelta(item)
  529. except Exception:
  530. pass
  531. elif is_scalar(item) and isna(item):
  532. # GH 18295
  533. item = self._na_value
  534. freq = None
  535. if isinstance(item, Timedelta) or (is_scalar(item) and isna(item)):
  536. # check freq can be preserved on edge cases
  537. if self.freq is not None:
  538. if ((loc == 0 or loc == -len(self)) and
  539. item + self.freq == self[0]):
  540. freq = self.freq
  541. elif (loc == len(self)) and item - self.freq == self[-1]:
  542. freq = self.freq
  543. item = Timedelta(item).asm8.view(_TD_DTYPE)
  544. try:
  545. new_tds = np.concatenate((self[:loc].asi8, [item.view(np.int64)],
  546. self[loc:].asi8))
  547. return self._shallow_copy(new_tds, freq=freq)
  548. except (AttributeError, TypeError):
  549. # fall back to object index
  550. if isinstance(item, compat.string_types):
  551. return self.astype(object).insert(loc, item)
  552. raise TypeError(
  553. "cannot insert TimedeltaIndex with incompatible label")
  554. def delete(self, loc):
  555. """
  556. Make a new TimedeltaIndex with passed location(s) deleted.
  557. Parameters
  558. ----------
  559. loc: int, slice or array of ints
  560. Indicate which sub-arrays to remove.
  561. Returns
  562. -------
  563. new_index : TimedeltaIndex
  564. """
  565. new_tds = np.delete(self.asi8, loc)
  566. freq = 'infer'
  567. if is_integer(loc):
  568. if loc in (0, -len(self), -1, len(self) - 1):
  569. freq = self.freq
  570. else:
  571. if is_list_like(loc):
  572. loc = lib.maybe_indices_to_slice(
  573. ensure_int64(np.array(loc)), len(self))
  574. if isinstance(loc, slice) and loc.step in (1, None):
  575. if (loc.start in (0, None) or loc.stop in (len(self), None)):
  576. freq = self.freq
  577. return TimedeltaIndex(new_tds, name=self.name, freq=freq)
  578. TimedeltaIndex._add_comparison_ops()
  579. TimedeltaIndex._add_numeric_methods_unary()
  580. TimedeltaIndex._add_logical_methods_disabled()
  581. TimedeltaIndex._add_datetimelike_methods()
  582. def _is_convertible_to_index(other):
  583. """
  584. return a boolean whether I can attempt conversion to a TimedeltaIndex
  585. """
  586. if isinstance(other, TimedeltaIndex):
  587. return True
  588. elif (len(other) > 0 and
  589. other.inferred_type not in ('floating', 'mixed-integer', 'integer',
  590. 'mixed-integer-float', 'mixed')):
  591. return True
  592. return False
  593. def timedelta_range(start=None, end=None, periods=None, freq=None,
  594. name=None, closed=None):
  595. """
  596. Return a fixed frequency TimedeltaIndex, with day as the default
  597. frequency
  598. Parameters
  599. ----------
  600. start : string or timedelta-like, default None
  601. Left bound for generating timedeltas
  602. end : string or timedelta-like, default None
  603. Right bound for generating timedeltas
  604. periods : integer, default None
  605. Number of periods to generate
  606. freq : string or DateOffset, default 'D'
  607. Frequency strings can have multiples, e.g. '5H'
  608. name : string, default None
  609. Name of the resulting TimedeltaIndex
  610. closed : string, default None
  611. Make the interval closed with respect to the given frequency to
  612. the 'left', 'right', or both sides (None)
  613. Returns
  614. -------
  615. rng : TimedeltaIndex
  616. Notes
  617. -----
  618. Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,
  619. exactly three must be specified. If ``freq`` is omitted, the resulting
  620. ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between
  621. ``start`` and ``end`` (closed on both sides).
  622. To learn more about the frequency strings, please see `this link
  623. <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
  624. Examples
  625. --------
  626. >>> pd.timedelta_range(start='1 day', periods=4)
  627. TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'],
  628. dtype='timedelta64[ns]', freq='D')
  629. The ``closed`` parameter specifies which endpoint is included. The default
  630. behavior is to include both endpoints.
  631. >>> pd.timedelta_range(start='1 day', periods=4, closed='right')
  632. TimedeltaIndex(['2 days', '3 days', '4 days'],
  633. dtype='timedelta64[ns]', freq='D')
  634. The ``freq`` parameter specifies the frequency of the TimedeltaIndex.
  635. Only fixed frequencies can be passed, non-fixed frequencies such as
  636. 'M' (month end) will raise.
  637. >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H')
  638. TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00',
  639. '1 days 18:00:00', '2 days 00:00:00'],
  640. dtype='timedelta64[ns]', freq='6H')
  641. Specify ``start``, ``end``, and ``periods``; the frequency is generated
  642. automatically (linearly spaced).
  643. >>> pd.timedelta_range(start='1 day', end='5 days', periods=4)
  644. TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00',
  645. '5 days 00:00:00'],
  646. dtype='timedelta64[ns]', freq=None)
  647. """
  648. if freq is None and com._any_none(periods, start, end):
  649. freq = 'D'
  650. freq, freq_infer = dtl.maybe_infer_freq(freq)
  651. tdarr = TimedeltaArray._generate_range(start, end, periods, freq,
  652. closed=closed)
  653. return TimedeltaIndex._simple_new(tdarr._data, freq=tdarr.freq, name=name)