test_timedelta64.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. # Arithmetic tests for DataFrame/Series/Index/Array classes that should
  2. # behave identically.
  3. from datetime import (
  4. datetime,
  5. timedelta,
  6. )
  7. import numpy as np
  8. import pytest
  9. from pandas.errors import (
  10. OutOfBoundsDatetime,
  11. PerformanceWarning,
  12. )
  13. import pandas as pd
  14. from pandas import (
  15. DataFrame,
  16. DatetimeIndex,
  17. Index,
  18. NaT,
  19. Series,
  20. Timedelta,
  21. TimedeltaIndex,
  22. Timestamp,
  23. offsets,
  24. timedelta_range,
  25. )
  26. import pandas._testing as tm
  27. from pandas.core.arrays import PandasArray
  28. from pandas.tests.arithmetic.common import (
  29. assert_invalid_addsub_type,
  30. assert_invalid_comparison,
  31. get_upcast_box,
  32. )
  33. def assert_dtype(obj, expected_dtype):
  34. """
  35. Helper to check the dtype for a Series, Index, or single-column DataFrame.
  36. """
  37. dtype = tm.get_dtype(obj)
  38. assert dtype == expected_dtype
  39. def get_expected_name(box, names):
  40. if box is DataFrame:
  41. # Since we are operating with a DataFrame and a non-DataFrame,
  42. # the non-DataFrame is cast to Series and its name ignored.
  43. exname = names[0]
  44. elif box in [tm.to_array, pd.array]:
  45. exname = names[1]
  46. else:
  47. exname = names[2]
  48. return exname
  49. # ------------------------------------------------------------------
  50. # Timedelta64[ns] dtype Comparisons
  51. class TestTimedelta64ArrayLikeComparisons:
  52. # Comparison tests for timedelta64[ns] vectors fully parametrized over
  53. # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all comparison
  54. # tests will eventually end up here.
  55. def test_compare_timedelta64_zerodim(self, box_with_array):
  56. # GH#26689 should unbox when comparing with zerodim array
  57. box = box_with_array
  58. xbox = box_with_array if box_with_array not in [Index, pd.array] else np.ndarray
  59. tdi = timedelta_range("2H", periods=4)
  60. other = np.array(tdi.to_numpy()[0])
  61. tdi = tm.box_expected(tdi, box)
  62. res = tdi <= other
  63. expected = np.array([True, False, False, False])
  64. expected = tm.box_expected(expected, xbox)
  65. tm.assert_equal(res, expected)
  66. @pytest.mark.parametrize(
  67. "td_scalar",
  68. [
  69. timedelta(days=1),
  70. Timedelta(days=1),
  71. Timedelta(days=1).to_timedelta64(),
  72. offsets.Hour(24),
  73. ],
  74. )
  75. def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar):
  76. # regression test for GH#5963
  77. box = box_with_array
  78. xbox = box if box not in [Index, pd.array] else np.ndarray
  79. ser = Series([timedelta(days=1), timedelta(days=2)])
  80. ser = tm.box_expected(ser, box)
  81. actual = ser > td_scalar
  82. expected = Series([False, True])
  83. expected = tm.box_expected(expected, xbox)
  84. tm.assert_equal(actual, expected)
  85. @pytest.mark.parametrize(
  86. "invalid",
  87. [
  88. 345600000000000,
  89. "a",
  90. Timestamp("2021-01-01"),
  91. Timestamp("2021-01-01").now("UTC"),
  92. Timestamp("2021-01-01").now().to_datetime64(),
  93. Timestamp("2021-01-01").now().to_pydatetime(),
  94. Timestamp("2021-01-01").date(),
  95. np.array(4), # zero-dim mismatched dtype
  96. ],
  97. )
  98. def test_td64_comparisons_invalid(self, box_with_array, invalid):
  99. # GH#13624 for str
  100. box = box_with_array
  101. rng = timedelta_range("1 days", periods=10)
  102. obj = tm.box_expected(rng, box)
  103. assert_invalid_comparison(obj, invalid, box)
  104. @pytest.mark.parametrize(
  105. "other",
  106. [
  107. list(range(10)),
  108. np.arange(10),
  109. np.arange(10).astype(np.float32),
  110. np.arange(10).astype(object),
  111. pd.date_range("1970-01-01", periods=10, tz="UTC").array,
  112. np.array(pd.date_range("1970-01-01", periods=10)),
  113. list(pd.date_range("1970-01-01", periods=10)),
  114. pd.date_range("1970-01-01", periods=10).astype(object),
  115. pd.period_range("1971-01-01", freq="D", periods=10).array,
  116. pd.period_range("1971-01-01", freq="D", periods=10).astype(object),
  117. ],
  118. )
  119. def test_td64arr_cmp_arraylike_invalid(self, other, box_with_array):
  120. # We don't parametrize this over box_with_array because listlike
  121. # other plays poorly with assert_invalid_comparison reversed checks
  122. rng = timedelta_range("1 days", periods=10)._data
  123. rng = tm.box_expected(rng, box_with_array)
  124. assert_invalid_comparison(rng, other, box_with_array)
  125. def test_td64arr_cmp_mixed_invalid(self):
  126. rng = timedelta_range("1 days", periods=5)._data
  127. other = np.array([0, 1, 2, rng[3], Timestamp("2021-01-01")])
  128. result = rng == other
  129. expected = np.array([False, False, False, True, False])
  130. tm.assert_numpy_array_equal(result, expected)
  131. result = rng != other
  132. tm.assert_numpy_array_equal(result, ~expected)
  133. msg = "Invalid comparison between|Cannot compare type|not supported between"
  134. with pytest.raises(TypeError, match=msg):
  135. rng < other
  136. with pytest.raises(TypeError, match=msg):
  137. rng > other
  138. with pytest.raises(TypeError, match=msg):
  139. rng <= other
  140. with pytest.raises(TypeError, match=msg):
  141. rng >= other
  142. class TestTimedelta64ArrayComparisons:
  143. # TODO: All of these need to be parametrized over box
  144. @pytest.mark.parametrize("dtype", [None, object])
  145. def test_comp_nat(self, dtype):
  146. left = TimedeltaIndex([Timedelta("1 days"), NaT, Timedelta("3 days")])
  147. right = TimedeltaIndex([NaT, NaT, Timedelta("3 days")])
  148. lhs, rhs = left, right
  149. if dtype is object:
  150. lhs, rhs = left.astype(object), right.astype(object)
  151. result = rhs == lhs
  152. expected = np.array([False, False, True])
  153. tm.assert_numpy_array_equal(result, expected)
  154. result = rhs != lhs
  155. expected = np.array([True, True, False])
  156. tm.assert_numpy_array_equal(result, expected)
  157. expected = np.array([False, False, False])
  158. tm.assert_numpy_array_equal(lhs == NaT, expected)
  159. tm.assert_numpy_array_equal(NaT == rhs, expected)
  160. expected = np.array([True, True, True])
  161. tm.assert_numpy_array_equal(lhs != NaT, expected)
  162. tm.assert_numpy_array_equal(NaT != lhs, expected)
  163. expected = np.array([False, False, False])
  164. tm.assert_numpy_array_equal(lhs < NaT, expected)
  165. tm.assert_numpy_array_equal(NaT > lhs, expected)
  166. @pytest.mark.parametrize(
  167. "idx2",
  168. [
  169. TimedeltaIndex(
  170. ["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"]
  171. ),
  172. np.array(
  173. [
  174. np.timedelta64(2, "D"),
  175. np.timedelta64(2, "D"),
  176. np.timedelta64("nat"),
  177. np.timedelta64("nat"),
  178. np.timedelta64(1, "D") + np.timedelta64(2, "s"),
  179. np.timedelta64(5, "D") + np.timedelta64(3, "s"),
  180. ]
  181. ),
  182. ],
  183. )
  184. def test_comparisons_nat(self, idx2):
  185. idx1 = TimedeltaIndex(
  186. [
  187. "1 day",
  188. NaT,
  189. "1 day 00:00:01",
  190. NaT,
  191. "1 day 00:00:01",
  192. "5 day 00:00:03",
  193. ]
  194. )
  195. # Check pd.NaT is handles as the same as np.nan
  196. result = idx1 < idx2
  197. expected = np.array([True, False, False, False, True, False])
  198. tm.assert_numpy_array_equal(result, expected)
  199. result = idx2 > idx1
  200. expected = np.array([True, False, False, False, True, False])
  201. tm.assert_numpy_array_equal(result, expected)
  202. result = idx1 <= idx2
  203. expected = np.array([True, False, False, False, True, True])
  204. tm.assert_numpy_array_equal(result, expected)
  205. result = idx2 >= idx1
  206. expected = np.array([True, False, False, False, True, True])
  207. tm.assert_numpy_array_equal(result, expected)
  208. result = idx1 == idx2
  209. expected = np.array([False, False, False, False, False, True])
  210. tm.assert_numpy_array_equal(result, expected)
  211. result = idx1 != idx2
  212. expected = np.array([True, True, True, True, True, False])
  213. tm.assert_numpy_array_equal(result, expected)
  214. # TODO: better name
  215. def test_comparisons_coverage(self):
  216. rng = timedelta_range("1 days", periods=10)
  217. result = rng < rng[3]
  218. expected = np.array([True, True, True] + [False] * 7)
  219. tm.assert_numpy_array_equal(result, expected)
  220. result = rng == list(rng)
  221. exp = rng == rng
  222. tm.assert_numpy_array_equal(result, exp)
  223. # ------------------------------------------------------------------
  224. # Timedelta64[ns] dtype Arithmetic Operations
  225. class TestTimedelta64ArithmeticUnsorted:
  226. # Tests moved from type-specific test files but not
  227. # yet sorted/parametrized/de-duplicated
  228. def test_ufunc_coercions(self):
  229. # normal ops are also tested in tseries/test_timedeltas.py
  230. idx = TimedeltaIndex(["2H", "4H", "6H", "8H", "10H"], freq="2H", name="x")
  231. for result in [idx * 2, np.multiply(idx, 2)]:
  232. assert isinstance(result, TimedeltaIndex)
  233. exp = TimedeltaIndex(["4H", "8H", "12H", "16H", "20H"], freq="4H", name="x")
  234. tm.assert_index_equal(result, exp)
  235. assert result.freq == "4H"
  236. for result in [idx / 2, np.divide(idx, 2)]:
  237. assert isinstance(result, TimedeltaIndex)
  238. exp = TimedeltaIndex(["1H", "2H", "3H", "4H", "5H"], freq="H", name="x")
  239. tm.assert_index_equal(result, exp)
  240. assert result.freq == "H"
  241. for result in [-idx, np.negative(idx)]:
  242. assert isinstance(result, TimedeltaIndex)
  243. exp = TimedeltaIndex(
  244. ["-2H", "-4H", "-6H", "-8H", "-10H"], freq="-2H", name="x"
  245. )
  246. tm.assert_index_equal(result, exp)
  247. assert result.freq == "-2H"
  248. idx = TimedeltaIndex(["-2H", "-1H", "0H", "1H", "2H"], freq="H", name="x")
  249. for result in [abs(idx), np.absolute(idx)]:
  250. assert isinstance(result, TimedeltaIndex)
  251. exp = TimedeltaIndex(["2H", "1H", "0H", "1H", "2H"], freq=None, name="x")
  252. tm.assert_index_equal(result, exp)
  253. assert result.freq is None
  254. def test_subtraction_ops(self):
  255. # with datetimes/timedelta and tdi/dti
  256. tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
  257. dti = pd.date_range("20130101", periods=3, name="bar")
  258. td = Timedelta("1 days")
  259. dt = Timestamp("20130101")
  260. msg = "cannot subtract a datelike from a TimedeltaArray"
  261. with pytest.raises(TypeError, match=msg):
  262. tdi - dt
  263. with pytest.raises(TypeError, match=msg):
  264. tdi - dti
  265. msg = r"unsupported operand type\(s\) for -"
  266. with pytest.raises(TypeError, match=msg):
  267. td - dt
  268. msg = "(bad|unsupported) operand type for unary"
  269. with pytest.raises(TypeError, match=msg):
  270. td - dti
  271. result = dt - dti
  272. expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"], name="bar")
  273. tm.assert_index_equal(result, expected)
  274. result = dti - dt
  275. expected = TimedeltaIndex(["0 days", "1 days", "2 days"], name="bar")
  276. tm.assert_index_equal(result, expected)
  277. result = tdi - td
  278. expected = TimedeltaIndex(["0 days", NaT, "1 days"], name="foo")
  279. tm.assert_index_equal(result, expected, check_names=False)
  280. result = td - tdi
  281. expected = TimedeltaIndex(["0 days", NaT, "-1 days"], name="foo")
  282. tm.assert_index_equal(result, expected, check_names=False)
  283. result = dti - td
  284. expected = DatetimeIndex(
  285. ["20121231", "20130101", "20130102"], freq="D", name="bar"
  286. )
  287. tm.assert_index_equal(result, expected, check_names=False)
  288. result = dt - tdi
  289. expected = DatetimeIndex(["20121231", NaT, "20121230"], name="foo")
  290. tm.assert_index_equal(result, expected)
  291. def test_subtraction_ops_with_tz(self, box_with_array):
  292. # check that dt/dti subtraction ops with tz are validated
  293. dti = pd.date_range("20130101", periods=3)
  294. dti = tm.box_expected(dti, box_with_array)
  295. ts = Timestamp("20130101")
  296. dt = ts.to_pydatetime()
  297. dti_tz = pd.date_range("20130101", periods=3).tz_localize("US/Eastern")
  298. dti_tz = tm.box_expected(dti_tz, box_with_array)
  299. ts_tz = Timestamp("20130101").tz_localize("US/Eastern")
  300. ts_tz2 = Timestamp("20130101").tz_localize("CET")
  301. dt_tz = ts_tz.to_pydatetime()
  302. td = Timedelta("1 days")
  303. def _check(result, expected):
  304. assert result == expected
  305. assert isinstance(result, Timedelta)
  306. # scalars
  307. result = ts - ts
  308. expected = Timedelta("0 days")
  309. _check(result, expected)
  310. result = dt_tz - ts_tz
  311. expected = Timedelta("0 days")
  312. _check(result, expected)
  313. result = ts_tz - dt_tz
  314. expected = Timedelta("0 days")
  315. _check(result, expected)
  316. # tz mismatches
  317. msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
  318. with pytest.raises(TypeError, match=msg):
  319. dt_tz - ts
  320. msg = "can't subtract offset-naive and offset-aware datetimes"
  321. with pytest.raises(TypeError, match=msg):
  322. dt_tz - dt
  323. msg = "can't subtract offset-naive and offset-aware datetimes"
  324. with pytest.raises(TypeError, match=msg):
  325. dt - dt_tz
  326. msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
  327. with pytest.raises(TypeError, match=msg):
  328. ts - dt_tz
  329. with pytest.raises(TypeError, match=msg):
  330. ts_tz2 - ts
  331. with pytest.raises(TypeError, match=msg):
  332. ts_tz2 - dt
  333. msg = "Cannot subtract tz-naive and tz-aware"
  334. # with dti
  335. with pytest.raises(TypeError, match=msg):
  336. dti - ts_tz
  337. with pytest.raises(TypeError, match=msg):
  338. dti_tz - ts
  339. result = dti_tz - dt_tz
  340. expected = TimedeltaIndex(["0 days", "1 days", "2 days"])
  341. expected = tm.box_expected(expected, box_with_array)
  342. tm.assert_equal(result, expected)
  343. result = dt_tz - dti_tz
  344. expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"])
  345. expected = tm.box_expected(expected, box_with_array)
  346. tm.assert_equal(result, expected)
  347. result = dti_tz - ts_tz
  348. expected = TimedeltaIndex(["0 days", "1 days", "2 days"])
  349. expected = tm.box_expected(expected, box_with_array)
  350. tm.assert_equal(result, expected)
  351. result = ts_tz - dti_tz
  352. expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"])
  353. expected = tm.box_expected(expected, box_with_array)
  354. tm.assert_equal(result, expected)
  355. result = td - td
  356. expected = Timedelta("0 days")
  357. _check(result, expected)
  358. result = dti_tz - td
  359. expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern")
  360. expected = tm.box_expected(expected, box_with_array)
  361. tm.assert_equal(result, expected)
  362. def test_dti_tdi_numeric_ops(self):
  363. # These are normally union/diff set-like ops
  364. tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
  365. dti = pd.date_range("20130101", periods=3, name="bar")
  366. result = tdi - tdi
  367. expected = TimedeltaIndex(["0 days", NaT, "0 days"], name="foo")
  368. tm.assert_index_equal(result, expected)
  369. result = tdi + tdi
  370. expected = TimedeltaIndex(["2 days", NaT, "4 days"], name="foo")
  371. tm.assert_index_equal(result, expected)
  372. result = dti - tdi # name will be reset
  373. expected = DatetimeIndex(["20121231", NaT, "20130101"])
  374. tm.assert_index_equal(result, expected)
  375. def test_addition_ops(self):
  376. # with datetimes/timedelta and tdi/dti
  377. tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
  378. dti = pd.date_range("20130101", periods=3, name="bar")
  379. td = Timedelta("1 days")
  380. dt = Timestamp("20130101")
  381. result = tdi + dt
  382. expected = DatetimeIndex(["20130102", NaT, "20130103"], name="foo")
  383. tm.assert_index_equal(result, expected)
  384. result = dt + tdi
  385. expected = DatetimeIndex(["20130102", NaT, "20130103"], name="foo")
  386. tm.assert_index_equal(result, expected)
  387. result = td + tdi
  388. expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo")
  389. tm.assert_index_equal(result, expected)
  390. result = tdi + td
  391. expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo")
  392. tm.assert_index_equal(result, expected)
  393. # unequal length
  394. msg = "cannot add indices of unequal length"
  395. with pytest.raises(ValueError, match=msg):
  396. tdi + dti[0:1]
  397. with pytest.raises(ValueError, match=msg):
  398. tdi[0:1] + dti
  399. # random indexes
  400. msg = "Addition/subtraction of integers and integer-arrays"
  401. with pytest.raises(TypeError, match=msg):
  402. tdi + Index([1, 2, 3], dtype=np.int64)
  403. # this is a union!
  404. # pytest.raises(TypeError, lambda : Index([1,2,3]) + tdi)
  405. result = tdi + dti # name will be reset
  406. expected = DatetimeIndex(["20130102", NaT, "20130105"])
  407. tm.assert_index_equal(result, expected)
  408. result = dti + tdi # name will be reset
  409. expected = DatetimeIndex(["20130102", NaT, "20130105"])
  410. tm.assert_index_equal(result, expected)
  411. result = dt + td
  412. expected = Timestamp("20130102")
  413. assert result == expected
  414. result = td + dt
  415. expected = Timestamp("20130102")
  416. assert result == expected
  417. # TODO: Needs more informative name, probably split up into
  418. # more targeted tests
  419. @pytest.mark.parametrize("freq", ["D", "B"])
  420. def test_timedelta(self, freq):
  421. index = pd.date_range("1/1/2000", periods=50, freq=freq)
  422. shifted = index + timedelta(1)
  423. back = shifted + timedelta(-1)
  424. back = back._with_freq("infer")
  425. tm.assert_index_equal(index, back)
  426. if freq == "D":
  427. expected = pd.tseries.offsets.Day(1)
  428. assert index.freq == expected
  429. assert shifted.freq == expected
  430. assert back.freq == expected
  431. else: # freq == 'B'
  432. assert index.freq == pd.tseries.offsets.BusinessDay(1)
  433. assert shifted.freq is None
  434. assert back.freq == pd.tseries.offsets.BusinessDay(1)
  435. result = index - timedelta(1)
  436. expected = index + timedelta(-1)
  437. tm.assert_index_equal(result, expected)
  438. def test_timedelta_tick_arithmetic(self):
  439. # GH#4134, buggy with timedeltas
  440. rng = pd.date_range("2013", "2014")
  441. s = Series(rng)
  442. result1 = rng - offsets.Hour(1)
  443. result2 = DatetimeIndex(s - np.timedelta64(100000000))
  444. result3 = rng - np.timedelta64(100000000)
  445. result4 = DatetimeIndex(s - offsets.Hour(1))
  446. assert result1.freq == rng.freq
  447. result1 = result1._with_freq(None)
  448. tm.assert_index_equal(result1, result4)
  449. assert result3.freq == rng.freq
  450. result3 = result3._with_freq(None)
  451. tm.assert_index_equal(result2, result3)
  452. def test_tda_add_sub_index(self):
  453. # Check that TimedeltaArray defers to Index on arithmetic ops
  454. tdi = TimedeltaIndex(["1 days", NaT, "2 days"])
  455. tda = tdi.array
  456. dti = pd.date_range("1999-12-31", periods=3, freq="D")
  457. result = tda + dti
  458. expected = tdi + dti
  459. tm.assert_index_equal(result, expected)
  460. result = tda + tdi
  461. expected = tdi + tdi
  462. tm.assert_index_equal(result, expected)
  463. result = tda - tdi
  464. expected = tdi - tdi
  465. tm.assert_index_equal(result, expected)
  466. def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture):
  467. # Result should be cast back to DatetimeArray
  468. box = box_with_array
  469. dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
  470. dti = dti._with_freq(None)
  471. tdi = dti - dti
  472. obj = tm.box_expected(tdi, box)
  473. other = tm.box_expected(dti, box)
  474. with tm.assert_produces_warning(PerformanceWarning):
  475. result = obj + other.astype(object)
  476. tm.assert_equal(result, other.astype(object))
  477. # -------------------------------------------------------------
  478. # Binary operations TimedeltaIndex and timedelta-like
  479. def test_tdi_iadd_timedeltalike(self, two_hours, box_with_array):
  480. # only test adding/sub offsets as + is now numeric
  481. rng = timedelta_range("1 days", "10 days")
  482. expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
  483. rng = tm.box_expected(rng, box_with_array)
  484. expected = tm.box_expected(expected, box_with_array)
  485. orig_rng = rng
  486. rng += two_hours
  487. tm.assert_equal(rng, expected)
  488. if box_with_array is not Index:
  489. # Check that operation is actually inplace
  490. tm.assert_equal(orig_rng, expected)
  491. def test_tdi_isub_timedeltalike(self, two_hours, box_with_array):
  492. # only test adding/sub offsets as - is now numeric
  493. rng = timedelta_range("1 days", "10 days")
  494. expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
  495. rng = tm.box_expected(rng, box_with_array)
  496. expected = tm.box_expected(expected, box_with_array)
  497. orig_rng = rng
  498. rng -= two_hours
  499. tm.assert_equal(rng, expected)
  500. if box_with_array is not Index:
  501. # Check that operation is actually inplace
  502. tm.assert_equal(orig_rng, expected)
  503. # -------------------------------------------------------------
  504. def test_tdi_ops_attributes(self):
  505. rng = timedelta_range("2 days", periods=5, freq="2D", name="x")
  506. result = rng + 1 * rng.freq
  507. exp = timedelta_range("4 days", periods=5, freq="2D", name="x")
  508. tm.assert_index_equal(result, exp)
  509. assert result.freq == "2D"
  510. result = rng - 2 * rng.freq
  511. exp = timedelta_range("-2 days", periods=5, freq="2D", name="x")
  512. tm.assert_index_equal(result, exp)
  513. assert result.freq == "2D"
  514. result = rng * 2
  515. exp = timedelta_range("4 days", periods=5, freq="4D", name="x")
  516. tm.assert_index_equal(result, exp)
  517. assert result.freq == "4D"
  518. result = rng / 2
  519. exp = timedelta_range("1 days", periods=5, freq="D", name="x")
  520. tm.assert_index_equal(result, exp)
  521. assert result.freq == "D"
  522. result = -rng
  523. exp = timedelta_range("-2 days", periods=5, freq="-2D", name="x")
  524. tm.assert_index_equal(result, exp)
  525. assert result.freq == "-2D"
  526. rng = timedelta_range("-2 days", periods=5, freq="D", name="x")
  527. result = abs(rng)
  528. exp = TimedeltaIndex(
  529. ["2 days", "1 days", "0 days", "1 days", "2 days"], name="x"
  530. )
  531. tm.assert_index_equal(result, exp)
  532. assert result.freq is None
  533. class TestAddSubNaTMasking:
  534. # TODO: parametrize over boxes
  535. @pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"])
  536. def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts):
  537. # GH#17991 checking for overflow-masking with NaT
  538. tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"])
  539. tdobj = tm.box_expected(tdinat, box_with_array)
  540. ts = Timestamp(str_ts)
  541. ts_variants = [
  542. ts,
  543. ts.to_pydatetime(),
  544. ts.to_datetime64().astype("datetime64[ns]"),
  545. ts.to_datetime64().astype("datetime64[D]"),
  546. ]
  547. for variant in ts_variants:
  548. res = tdobj + variant
  549. if box_with_array is DataFrame:
  550. assert res.iloc[1, 1] is NaT
  551. else:
  552. assert res[1] is NaT
  553. def test_tdi_add_overflow(self):
  554. # See GH#14068
  555. # preliminary test scalar analogue of vectorized tests below
  556. # TODO: Make raised error message more informative and test
  557. with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
  558. pd.to_timedelta(106580, "D") + Timestamp("2000")
  559. with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
  560. Timestamp("2000") + pd.to_timedelta(106580, "D")
  561. _NaT = NaT._value + 1
  562. msg = "Overflow in int64 addition"
  563. with pytest.raises(OverflowError, match=msg):
  564. pd.to_timedelta([106580], "D") + Timestamp("2000")
  565. with pytest.raises(OverflowError, match=msg):
  566. Timestamp("2000") + pd.to_timedelta([106580], "D")
  567. with pytest.raises(OverflowError, match=msg):
  568. pd.to_timedelta([_NaT]) - Timedelta("1 days")
  569. with pytest.raises(OverflowError, match=msg):
  570. pd.to_timedelta(["5 days", _NaT]) - Timedelta("1 days")
  571. with pytest.raises(OverflowError, match=msg):
  572. (
  573. pd.to_timedelta([_NaT, "5 days", "1 hours"])
  574. - pd.to_timedelta(["7 seconds", _NaT, "4 hours"])
  575. )
  576. # These should not overflow!
  577. exp = TimedeltaIndex([NaT])
  578. result = pd.to_timedelta([NaT]) - Timedelta("1 days")
  579. tm.assert_index_equal(result, exp)
  580. exp = TimedeltaIndex(["4 days", NaT])
  581. result = pd.to_timedelta(["5 days", NaT]) - Timedelta("1 days")
  582. tm.assert_index_equal(result, exp)
  583. exp = TimedeltaIndex([NaT, NaT, "5 hours"])
  584. result = pd.to_timedelta([NaT, "5 days", "1 hours"]) + pd.to_timedelta(
  585. ["7 seconds", NaT, "4 hours"]
  586. )
  587. tm.assert_index_equal(result, exp)
  588. class TestTimedeltaArraylikeAddSubOps:
  589. # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__
  590. def test_sub_nat_retain_unit(self):
  591. ser = pd.to_timedelta(Series(["00:00:01"])).astype("m8[s]")
  592. result = ser - NaT
  593. expected = Series([NaT], dtype="m8[s]")
  594. tm.assert_series_equal(result, expected)
  595. # TODO: moved from tests.indexes.timedeltas.test_arithmetic; needs
  596. # parametrization+de-duplication
  597. def test_timedelta_ops_with_missing_values(self):
  598. # setup
  599. s1 = pd.to_timedelta(Series(["00:00:01"]))
  600. s2 = pd.to_timedelta(Series(["00:00:02"]))
  601. msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]"
  602. with pytest.raises(TypeError, match=msg):
  603. # Passing datetime64-dtype data to TimedeltaIndex is no longer
  604. # supported GH#29794
  605. pd.to_timedelta(Series([NaT])) # TODO: belongs elsewhere?
  606. sn = pd.to_timedelta(Series([NaT], dtype="m8[ns]"))
  607. df1 = DataFrame(["00:00:01"]).apply(pd.to_timedelta)
  608. df2 = DataFrame(["00:00:02"]).apply(pd.to_timedelta)
  609. with pytest.raises(TypeError, match=msg):
  610. # Passing datetime64-dtype data to TimedeltaIndex is no longer
  611. # supported GH#29794
  612. DataFrame([NaT]).apply(pd.to_timedelta) # TODO: belongs elsewhere?
  613. dfn = DataFrame([NaT._value]).apply(pd.to_timedelta)
  614. scalar1 = pd.to_timedelta("00:00:01")
  615. scalar2 = pd.to_timedelta("00:00:02")
  616. timedelta_NaT = pd.to_timedelta("NaT")
  617. actual = scalar1 + scalar1
  618. assert actual == scalar2
  619. actual = scalar2 - scalar1
  620. assert actual == scalar1
  621. actual = s1 + s1
  622. tm.assert_series_equal(actual, s2)
  623. actual = s2 - s1
  624. tm.assert_series_equal(actual, s1)
  625. actual = s1 + scalar1
  626. tm.assert_series_equal(actual, s2)
  627. actual = scalar1 + s1
  628. tm.assert_series_equal(actual, s2)
  629. actual = s2 - scalar1
  630. tm.assert_series_equal(actual, s1)
  631. actual = -scalar1 + s2
  632. tm.assert_series_equal(actual, s1)
  633. actual = s1 + timedelta_NaT
  634. tm.assert_series_equal(actual, sn)
  635. actual = timedelta_NaT + s1
  636. tm.assert_series_equal(actual, sn)
  637. actual = s1 - timedelta_NaT
  638. tm.assert_series_equal(actual, sn)
  639. actual = -timedelta_NaT + s1
  640. tm.assert_series_equal(actual, sn)
  641. msg = "unsupported operand type"
  642. with pytest.raises(TypeError, match=msg):
  643. s1 + np.nan
  644. with pytest.raises(TypeError, match=msg):
  645. np.nan + s1
  646. with pytest.raises(TypeError, match=msg):
  647. s1 - np.nan
  648. with pytest.raises(TypeError, match=msg):
  649. -np.nan + s1
  650. actual = s1 + NaT
  651. tm.assert_series_equal(actual, sn)
  652. actual = s2 - NaT
  653. tm.assert_series_equal(actual, sn)
  654. actual = s1 + df1
  655. tm.assert_frame_equal(actual, df2)
  656. actual = s2 - df1
  657. tm.assert_frame_equal(actual, df1)
  658. actual = df1 + s1
  659. tm.assert_frame_equal(actual, df2)
  660. actual = df2 - s1
  661. tm.assert_frame_equal(actual, df1)
  662. actual = df1 + df1
  663. tm.assert_frame_equal(actual, df2)
  664. actual = df2 - df1
  665. tm.assert_frame_equal(actual, df1)
  666. actual = df1 + scalar1
  667. tm.assert_frame_equal(actual, df2)
  668. actual = df2 - scalar1
  669. tm.assert_frame_equal(actual, df1)
  670. actual = df1 + timedelta_NaT
  671. tm.assert_frame_equal(actual, dfn)
  672. actual = df1 - timedelta_NaT
  673. tm.assert_frame_equal(actual, dfn)
  674. msg = "cannot subtract a datelike from|unsupported operand type"
  675. with pytest.raises(TypeError, match=msg):
  676. df1 + np.nan
  677. with pytest.raises(TypeError, match=msg):
  678. df1 - np.nan
  679. actual = df1 + NaT # NaT is datetime, not timedelta
  680. tm.assert_frame_equal(actual, dfn)
  681. actual = df1 - NaT
  682. tm.assert_frame_equal(actual, dfn)
  683. # TODO: moved from tests.series.test_operators, needs splitting, cleanup,
  684. # de-duplication, box-parametrization...
  685. def test_operators_timedelta64(self):
  686. # series ops
  687. v1 = pd.date_range("2012-1-1", periods=3, freq="D")
  688. v2 = pd.date_range("2012-1-2", periods=3, freq="D")
  689. rs = Series(v2) - Series(v1)
  690. xp = Series(1e9 * 3600 * 24, rs.index).astype("int64").astype("timedelta64[ns]")
  691. tm.assert_series_equal(rs, xp)
  692. assert rs.dtype == "timedelta64[ns]"
  693. df = DataFrame({"A": v1})
  694. td = Series([timedelta(days=i) for i in range(3)])
  695. assert td.dtype == "timedelta64[ns]"
  696. # series on the rhs
  697. result = df["A"] - df["A"].shift()
  698. assert result.dtype == "timedelta64[ns]"
  699. result = df["A"] + td
  700. assert result.dtype == "M8[ns]"
  701. # scalar Timestamp on rhs
  702. maxa = df["A"].max()
  703. assert isinstance(maxa, Timestamp)
  704. resultb = df["A"] - df["A"].max()
  705. assert resultb.dtype == "timedelta64[ns]"
  706. # timestamp on lhs
  707. result = resultb + df["A"]
  708. values = [Timestamp("20111230"), Timestamp("20120101"), Timestamp("20120103")]
  709. expected = Series(values, name="A")
  710. tm.assert_series_equal(result, expected)
  711. # datetimes on rhs
  712. result = df["A"] - datetime(2001, 1, 1)
  713. expected = Series([timedelta(days=4017 + i) for i in range(3)], name="A")
  714. tm.assert_series_equal(result, expected)
  715. assert result.dtype == "m8[ns]"
  716. d = datetime(2001, 1, 1, 3, 4)
  717. resulta = df["A"] - d
  718. assert resulta.dtype == "m8[ns]"
  719. # roundtrip
  720. resultb = resulta + d
  721. tm.assert_series_equal(df["A"], resultb)
  722. # timedeltas on rhs
  723. td = timedelta(days=1)
  724. resulta = df["A"] + td
  725. resultb = resulta - td
  726. tm.assert_series_equal(resultb, df["A"])
  727. assert resultb.dtype == "M8[ns]"
  728. # roundtrip
  729. td = timedelta(minutes=5, seconds=3)
  730. resulta = df["A"] + td
  731. resultb = resulta - td
  732. tm.assert_series_equal(df["A"], resultb)
  733. assert resultb.dtype == "M8[ns]"
  734. # inplace
  735. value = rs[2] + np.timedelta64(timedelta(minutes=5, seconds=1))
  736. rs[2] += np.timedelta64(timedelta(minutes=5, seconds=1))
  737. assert rs[2] == value
  738. def test_timedelta64_ops_nat(self):
  739. # GH 11349
  740. timedelta_series = Series([NaT, Timedelta("1s")])
  741. nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]")
  742. single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
  743. # subtraction
  744. tm.assert_series_equal(timedelta_series - NaT, nat_series_dtype_timedelta)
  745. tm.assert_series_equal(-NaT + timedelta_series, nat_series_dtype_timedelta)
  746. tm.assert_series_equal(
  747. timedelta_series - single_nat_dtype_timedelta, nat_series_dtype_timedelta
  748. )
  749. tm.assert_series_equal(
  750. -single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta
  751. )
  752. # addition
  753. tm.assert_series_equal(
  754. nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta
  755. )
  756. tm.assert_series_equal(
  757. NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta
  758. )
  759. tm.assert_series_equal(
  760. nat_series_dtype_timedelta + single_nat_dtype_timedelta,
  761. nat_series_dtype_timedelta,
  762. )
  763. tm.assert_series_equal(
  764. single_nat_dtype_timedelta + nat_series_dtype_timedelta,
  765. nat_series_dtype_timedelta,
  766. )
  767. tm.assert_series_equal(timedelta_series + NaT, nat_series_dtype_timedelta)
  768. tm.assert_series_equal(NaT + timedelta_series, nat_series_dtype_timedelta)
  769. tm.assert_series_equal(
  770. timedelta_series + single_nat_dtype_timedelta, nat_series_dtype_timedelta
  771. )
  772. tm.assert_series_equal(
  773. single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta
  774. )
  775. tm.assert_series_equal(
  776. nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta
  777. )
  778. tm.assert_series_equal(
  779. NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta
  780. )
  781. tm.assert_series_equal(
  782. nat_series_dtype_timedelta + single_nat_dtype_timedelta,
  783. nat_series_dtype_timedelta,
  784. )
  785. tm.assert_series_equal(
  786. single_nat_dtype_timedelta + nat_series_dtype_timedelta,
  787. nat_series_dtype_timedelta,
  788. )
  789. # multiplication
  790. tm.assert_series_equal(
  791. nat_series_dtype_timedelta * 1.0, nat_series_dtype_timedelta
  792. )
  793. tm.assert_series_equal(
  794. 1.0 * nat_series_dtype_timedelta, nat_series_dtype_timedelta
  795. )
  796. tm.assert_series_equal(timedelta_series * 1, timedelta_series)
  797. tm.assert_series_equal(1 * timedelta_series, timedelta_series)
  798. tm.assert_series_equal(timedelta_series * 1.5, Series([NaT, Timedelta("1.5s")]))
  799. tm.assert_series_equal(1.5 * timedelta_series, Series([NaT, Timedelta("1.5s")]))
  800. tm.assert_series_equal(timedelta_series * np.nan, nat_series_dtype_timedelta)
  801. tm.assert_series_equal(np.nan * timedelta_series, nat_series_dtype_timedelta)
  802. # division
  803. tm.assert_series_equal(timedelta_series / 2, Series([NaT, Timedelta("0.5s")]))
  804. tm.assert_series_equal(timedelta_series / 2.0, Series([NaT, Timedelta("0.5s")]))
  805. tm.assert_series_equal(timedelta_series / np.nan, nat_series_dtype_timedelta)
  806. # -------------------------------------------------------------
  807. # Binary operations td64 arraylike and datetime-like
  808. @pytest.mark.parametrize("cls", [Timestamp, datetime, np.datetime64])
  809. def test_td64arr_add_sub_datetimelike_scalar(
  810. self, cls, box_with_array, tz_naive_fixture
  811. ):
  812. # GH#11925, GH#29558, GH#23215
  813. tz = tz_naive_fixture
  814. dt_scalar = Timestamp("2012-01-01", tz=tz)
  815. if cls is datetime:
  816. ts = dt_scalar.to_pydatetime()
  817. elif cls is np.datetime64:
  818. if tz_naive_fixture is not None:
  819. return
  820. ts = dt_scalar.to_datetime64()
  821. else:
  822. ts = dt_scalar
  823. tdi = timedelta_range("1 day", periods=3)
  824. expected = pd.date_range("2012-01-02", periods=3, tz=tz)
  825. tdarr = tm.box_expected(tdi, box_with_array)
  826. expected = tm.box_expected(expected, box_with_array)
  827. tm.assert_equal(ts + tdarr, expected)
  828. tm.assert_equal(tdarr + ts, expected)
  829. expected2 = pd.date_range("2011-12-31", periods=3, freq="-1D", tz=tz)
  830. expected2 = tm.box_expected(expected2, box_with_array)
  831. tm.assert_equal(ts - tdarr, expected2)
  832. tm.assert_equal(ts + (-tdarr), expected2)
  833. msg = "cannot subtract a datelike"
  834. with pytest.raises(TypeError, match=msg):
  835. tdarr - ts
  836. def test_td64arr_add_datetime64_nat(self, box_with_array):
  837. # GH#23215
  838. other = np.datetime64("NaT")
  839. tdi = timedelta_range("1 day", periods=3)
  840. expected = DatetimeIndex(["NaT", "NaT", "NaT"])
  841. tdser = tm.box_expected(tdi, box_with_array)
  842. expected = tm.box_expected(expected, box_with_array)
  843. tm.assert_equal(tdser + other, expected)
  844. tm.assert_equal(other + tdser, expected)
  845. def test_td64arr_sub_dt64_array(self, box_with_array):
  846. dti = pd.date_range("2016-01-01", periods=3)
  847. tdi = TimedeltaIndex(["-1 Day"] * 3)
  848. dtarr = dti.values
  849. expected = DatetimeIndex(dtarr) - tdi
  850. tdi = tm.box_expected(tdi, box_with_array)
  851. expected = tm.box_expected(expected, box_with_array)
  852. msg = "cannot subtract a datelike from"
  853. with pytest.raises(TypeError, match=msg):
  854. tdi - dtarr
  855. # TimedeltaIndex.__rsub__
  856. result = dtarr - tdi
  857. tm.assert_equal(result, expected)
  858. def test_td64arr_add_dt64_array(self, box_with_array):
  859. dti = pd.date_range("2016-01-01", periods=3)
  860. tdi = TimedeltaIndex(["-1 Day"] * 3)
  861. dtarr = dti.values
  862. expected = DatetimeIndex(dtarr) + tdi
  863. tdi = tm.box_expected(tdi, box_with_array)
  864. expected = tm.box_expected(expected, box_with_array)
  865. result = tdi + dtarr
  866. tm.assert_equal(result, expected)
  867. result = dtarr + tdi
  868. tm.assert_equal(result, expected)
  869. # ------------------------------------------------------------------
  870. # Invalid __add__/__sub__ operations
  871. @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "H"])
  872. @pytest.mark.parametrize("tdi_freq", [None, "H"])
  873. def test_td64arr_sub_periodlike(
  874. self, box_with_array, box_with_array2, tdi_freq, pi_freq
  875. ):
  876. # GH#20049 subtracting PeriodIndex should raise TypeError
  877. tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
  878. dti = Timestamp("2018-03-07 17:16:40") + tdi
  879. pi = dti.to_period(pi_freq)
  880. per = pi[0]
  881. tdi = tm.box_expected(tdi, box_with_array)
  882. pi = tm.box_expected(pi, box_with_array2)
  883. msg = "cannot subtract|unsupported operand type"
  884. with pytest.raises(TypeError, match=msg):
  885. tdi - pi
  886. # GH#13078 subtraction of Period scalar not supported
  887. with pytest.raises(TypeError, match=msg):
  888. tdi - per
  889. @pytest.mark.parametrize(
  890. "other",
  891. [
  892. # GH#12624 for str case
  893. "a",
  894. # GH#19123
  895. 1,
  896. 1.5,
  897. np.array(2),
  898. ],
  899. )
  900. def test_td64arr_addsub_numeric_scalar_invalid(self, box_with_array, other):
  901. # vector-like others are tested in test_td64arr_add_sub_numeric_arr_invalid
  902. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  903. tdarr = tm.box_expected(tdser, box_with_array)
  904. assert_invalid_addsub_type(tdarr, other)
  905. @pytest.mark.parametrize(
  906. "vec",
  907. [
  908. np.array([1, 2, 3]),
  909. Index([1, 2, 3]),
  910. Series([1, 2, 3]),
  911. DataFrame([[1, 2, 3]]),
  912. ],
  913. ids=lambda x: type(x).__name__,
  914. )
  915. def test_td64arr_addsub_numeric_arr_invalid(
  916. self, box_with_array, vec, any_real_numpy_dtype
  917. ):
  918. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  919. tdarr = tm.box_expected(tdser, box_with_array)
  920. vector = vec.astype(any_real_numpy_dtype)
  921. assert_invalid_addsub_type(tdarr, vector)
  922. def test_td64arr_add_sub_int(self, box_with_array, one):
  923. # Variants of `one` for #19012, deprecated GH#22535
  924. rng = timedelta_range("1 days 09:00:00", freq="H", periods=10)
  925. tdarr = tm.box_expected(rng, box_with_array)
  926. msg = "Addition/subtraction of integers"
  927. assert_invalid_addsub_type(tdarr, one, msg)
  928. # TODO: get inplace ops into assert_invalid_addsub_type
  929. with pytest.raises(TypeError, match=msg):
  930. tdarr += one
  931. with pytest.raises(TypeError, match=msg):
  932. tdarr -= one
  933. def test_td64arr_add_sub_integer_array(self, box_with_array):
  934. # GH#19959, deprecated GH#22535
  935. # GH#22696 for DataFrame case, check that we don't dispatch to numpy
  936. # implementation, which treats int64 as m8[ns]
  937. box = box_with_array
  938. xbox = np.ndarray if box is pd.array else box
  939. rng = timedelta_range("1 days 09:00:00", freq="H", periods=3)
  940. tdarr = tm.box_expected(rng, box)
  941. other = tm.box_expected([4, 3, 2], xbox)
  942. msg = "Addition/subtraction of integers and integer-arrays"
  943. assert_invalid_addsub_type(tdarr, other, msg)
  944. def test_td64arr_addsub_integer_array_no_freq(self, box_with_array):
  945. # GH#19959
  946. box = box_with_array
  947. xbox = np.ndarray if box is pd.array else box
  948. tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"])
  949. tdarr = tm.box_expected(tdi, box)
  950. other = tm.box_expected([14, -1, 16], xbox)
  951. msg = "Addition/subtraction of integers"
  952. assert_invalid_addsub_type(tdarr, other, msg)
  953. # ------------------------------------------------------------------
  954. # Operations with timedelta-like others
  955. def test_td64arr_add_sub_td64_array(self, box_with_array):
  956. box = box_with_array
  957. dti = pd.date_range("2016-01-01", periods=3)
  958. tdi = dti - dti.shift(1)
  959. tdarr = tdi.values
  960. expected = 2 * tdi
  961. tdi = tm.box_expected(tdi, box)
  962. expected = tm.box_expected(expected, box)
  963. result = tdi + tdarr
  964. tm.assert_equal(result, expected)
  965. result = tdarr + tdi
  966. tm.assert_equal(result, expected)
  967. expected_sub = 0 * tdi
  968. result = tdi - tdarr
  969. tm.assert_equal(result, expected_sub)
  970. result = tdarr - tdi
  971. tm.assert_equal(result, expected_sub)
  972. def test_td64arr_add_sub_tdi(self, box_with_array, names):
  973. # GH#17250 make sure result dtype is correct
  974. # GH#19043 make sure names are propagated correctly
  975. box = box_with_array
  976. exname = get_expected_name(box, names)
  977. tdi = TimedeltaIndex(["0 days", "1 day"], name=names[1])
  978. tdi = np.array(tdi) if box in [tm.to_array, pd.array] else tdi
  979. ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[0])
  980. expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], name=exname)
  981. ser = tm.box_expected(ser, box)
  982. expected = tm.box_expected(expected, box)
  983. result = tdi + ser
  984. tm.assert_equal(result, expected)
  985. assert_dtype(result, "timedelta64[ns]")
  986. result = ser + tdi
  987. tm.assert_equal(result, expected)
  988. assert_dtype(result, "timedelta64[ns]")
  989. expected = Series(
  990. [Timedelta(hours=-3), Timedelta(days=1, hours=-4)], name=exname
  991. )
  992. expected = tm.box_expected(expected, box)
  993. result = tdi - ser
  994. tm.assert_equal(result, expected)
  995. assert_dtype(result, "timedelta64[ns]")
  996. result = ser - tdi
  997. tm.assert_equal(result, -expected)
  998. assert_dtype(result, "timedelta64[ns]")
  999. @pytest.mark.parametrize("tdnat", [np.timedelta64("NaT"), NaT])
  1000. def test_td64arr_add_sub_td64_nat(self, box_with_array, tdnat):
  1001. # GH#18808, GH#23320 special handling for timedelta64("NaT")
  1002. box = box_with_array
  1003. tdi = TimedeltaIndex([NaT, Timedelta("1s")])
  1004. expected = TimedeltaIndex(["NaT"] * 2)
  1005. obj = tm.box_expected(tdi, box)
  1006. expected = tm.box_expected(expected, box)
  1007. result = obj + tdnat
  1008. tm.assert_equal(result, expected)
  1009. result = tdnat + obj
  1010. tm.assert_equal(result, expected)
  1011. result = obj - tdnat
  1012. tm.assert_equal(result, expected)
  1013. result = tdnat - obj
  1014. tm.assert_equal(result, expected)
  1015. def test_td64arr_add_timedeltalike(self, two_hours, box_with_array):
  1016. # only test adding/sub offsets as + is now numeric
  1017. # GH#10699 for Tick cases
  1018. box = box_with_array
  1019. rng = timedelta_range("1 days", "10 days")
  1020. expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
  1021. rng = tm.box_expected(rng, box)
  1022. expected = tm.box_expected(expected, box)
  1023. result = rng + two_hours
  1024. tm.assert_equal(result, expected)
  1025. result = two_hours + rng
  1026. tm.assert_equal(result, expected)
  1027. def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array):
  1028. # only test adding/sub offsets as - is now numeric
  1029. # GH#10699 for Tick cases
  1030. box = box_with_array
  1031. rng = timedelta_range("1 days", "10 days")
  1032. expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
  1033. rng = tm.box_expected(rng, box)
  1034. expected = tm.box_expected(expected, box)
  1035. result = rng - two_hours
  1036. tm.assert_equal(result, expected)
  1037. result = two_hours - rng
  1038. tm.assert_equal(result, -expected)
  1039. # ------------------------------------------------------------------
  1040. # __add__/__sub__ with DateOffsets and arrays of DateOffsets
  1041. def test_td64arr_add_sub_offset_index(self, names, box_with_array):
  1042. # GH#18849, GH#19744
  1043. box = box_with_array
  1044. exname = get_expected_name(box, names)
  1045. tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
  1046. other = Index([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
  1047. other = np.array(other) if box in [tm.to_array, pd.array] else other
  1048. expected = TimedeltaIndex(
  1049. [tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=exname
  1050. )
  1051. expected_sub = TimedeltaIndex(
  1052. [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname
  1053. )
  1054. tdi = tm.box_expected(tdi, box)
  1055. expected = tm.box_expected(expected, box).astype(object, copy=False)
  1056. expected_sub = tm.box_expected(expected_sub, box).astype(object, copy=False)
  1057. with tm.assert_produces_warning(PerformanceWarning):
  1058. res = tdi + other
  1059. tm.assert_equal(res, expected)
  1060. with tm.assert_produces_warning(PerformanceWarning):
  1061. res2 = other + tdi
  1062. tm.assert_equal(res2, expected)
  1063. with tm.assert_produces_warning(PerformanceWarning):
  1064. res_sub = tdi - other
  1065. tm.assert_equal(res_sub, expected_sub)
  1066. def test_td64arr_add_sub_offset_array(self, box_with_array):
  1067. # GH#18849, GH#18824
  1068. box = box_with_array
  1069. tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"])
  1070. other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)])
  1071. expected = TimedeltaIndex(
  1072. [tdi[n] + other[n] for n in range(len(tdi))], freq="infer"
  1073. )
  1074. expected_sub = TimedeltaIndex(
  1075. [tdi[n] - other[n] for n in range(len(tdi))], freq="infer"
  1076. )
  1077. tdi = tm.box_expected(tdi, box)
  1078. expected = tm.box_expected(expected, box).astype(object)
  1079. with tm.assert_produces_warning(PerformanceWarning):
  1080. res = tdi + other
  1081. tm.assert_equal(res, expected)
  1082. with tm.assert_produces_warning(PerformanceWarning):
  1083. res2 = other + tdi
  1084. tm.assert_equal(res2, expected)
  1085. expected_sub = tm.box_expected(expected_sub, box_with_array).astype(object)
  1086. with tm.assert_produces_warning(PerformanceWarning):
  1087. res_sub = tdi - other
  1088. tm.assert_equal(res_sub, expected_sub)
  1089. def test_td64arr_with_offset_series(self, names, box_with_array):
  1090. # GH#18849
  1091. box = box_with_array
  1092. box2 = Series if box in [Index, tm.to_array, pd.array] else box
  1093. exname = get_expected_name(box, names)
  1094. tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
  1095. other = Series([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
  1096. expected_add = Series(
  1097. [tdi[n] + other[n] for n in range(len(tdi))], name=exname, dtype=object
  1098. )
  1099. obj = tm.box_expected(tdi, box)
  1100. expected_add = tm.box_expected(expected_add, box2).astype(object)
  1101. with tm.assert_produces_warning(PerformanceWarning):
  1102. res = obj + other
  1103. tm.assert_equal(res, expected_add)
  1104. with tm.assert_produces_warning(PerformanceWarning):
  1105. res2 = other + obj
  1106. tm.assert_equal(res2, expected_add)
  1107. expected_sub = Series(
  1108. [tdi[n] - other[n] for n in range(len(tdi))], name=exname, dtype=object
  1109. )
  1110. expected_sub = tm.box_expected(expected_sub, box2).astype(object)
  1111. with tm.assert_produces_warning(PerformanceWarning):
  1112. res3 = obj - other
  1113. tm.assert_equal(res3, expected_sub)
  1114. @pytest.mark.parametrize("obox", [np.array, Index, Series])
  1115. def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array):
  1116. # GH#18824
  1117. tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"])
  1118. tdi = tm.box_expected(tdi, box_with_array)
  1119. anchored = obox([offsets.MonthEnd(), offsets.Day(n=2)])
  1120. # addition/subtraction ops with anchored offsets should issue
  1121. # a PerformanceWarning and _then_ raise a TypeError.
  1122. msg = "has incorrect type|cannot add the type MonthEnd"
  1123. with pytest.raises(TypeError, match=msg):
  1124. with tm.assert_produces_warning(PerformanceWarning):
  1125. tdi + anchored
  1126. with pytest.raises(TypeError, match=msg):
  1127. with tm.assert_produces_warning(PerformanceWarning):
  1128. anchored + tdi
  1129. with pytest.raises(TypeError, match=msg):
  1130. with tm.assert_produces_warning(PerformanceWarning):
  1131. tdi - anchored
  1132. with pytest.raises(TypeError, match=msg):
  1133. with tm.assert_produces_warning(PerformanceWarning):
  1134. anchored - tdi
  1135. # ------------------------------------------------------------------
  1136. # Unsorted
  1137. def test_td64arr_add_sub_object_array(self, box_with_array):
  1138. box = box_with_array
  1139. xbox = np.ndarray if box is pd.array else box
  1140. tdi = timedelta_range("1 day", periods=3, freq="D")
  1141. tdarr = tm.box_expected(tdi, box)
  1142. other = np.array([Timedelta(days=1), offsets.Day(2), Timestamp("2000-01-04")])
  1143. with tm.assert_produces_warning(PerformanceWarning):
  1144. result = tdarr + other
  1145. expected = Index(
  1146. [Timedelta(days=2), Timedelta(days=4), Timestamp("2000-01-07")]
  1147. )
  1148. expected = tm.box_expected(expected, xbox).astype(object)
  1149. tm.assert_equal(result, expected)
  1150. msg = "unsupported operand type|cannot subtract a datelike"
  1151. with pytest.raises(TypeError, match=msg):
  1152. with tm.assert_produces_warning(PerformanceWarning):
  1153. tdarr - other
  1154. with tm.assert_produces_warning(PerformanceWarning):
  1155. result = other - tdarr
  1156. expected = Index([Timedelta(0), Timedelta(0), Timestamp("2000-01-01")])
  1157. expected = tm.box_expected(expected, xbox).astype(object)
  1158. tm.assert_equal(result, expected)
  1159. class TestTimedeltaArraylikeMulDivOps:
  1160. # Tests for timedelta64[ns]
  1161. # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
  1162. # ------------------------------------------------------------------
  1163. # Multiplication
  1164. # organized with scalar others first, then array-like
  1165. def test_td64arr_mul_int(self, box_with_array):
  1166. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1167. idx = tm.box_expected(idx, box_with_array)
  1168. result = idx * 1
  1169. tm.assert_equal(result, idx)
  1170. result = 1 * idx
  1171. tm.assert_equal(result, idx)
  1172. def test_td64arr_mul_tdlike_scalar_raises(self, two_hours, box_with_array):
  1173. rng = timedelta_range("1 days", "10 days", name="foo")
  1174. rng = tm.box_expected(rng, box_with_array)
  1175. msg = "argument must be an integer|cannot use operands with types dtype"
  1176. with pytest.raises(TypeError, match=msg):
  1177. rng * two_hours
  1178. def test_tdi_mul_int_array_zerodim(self, box_with_array):
  1179. rng5 = np.arange(5, dtype="int64")
  1180. idx = TimedeltaIndex(rng5)
  1181. expected = TimedeltaIndex(rng5 * 5)
  1182. idx = tm.box_expected(idx, box_with_array)
  1183. expected = tm.box_expected(expected, box_with_array)
  1184. result = idx * np.array(5, dtype="int64")
  1185. tm.assert_equal(result, expected)
  1186. def test_tdi_mul_int_array(self, box_with_array):
  1187. rng5 = np.arange(5, dtype="int64")
  1188. idx = TimedeltaIndex(rng5)
  1189. expected = TimedeltaIndex(rng5**2)
  1190. idx = tm.box_expected(idx, box_with_array)
  1191. expected = tm.box_expected(expected, box_with_array)
  1192. result = idx * rng5
  1193. tm.assert_equal(result, expected)
  1194. def test_tdi_mul_int_series(self, box_with_array):
  1195. box = box_with_array
  1196. xbox = Series if box in [Index, tm.to_array, pd.array] else box
  1197. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1198. expected = TimedeltaIndex(np.arange(5, dtype="int64") ** 2)
  1199. idx = tm.box_expected(idx, box)
  1200. expected = tm.box_expected(expected, xbox)
  1201. result = idx * Series(np.arange(5, dtype="int64"))
  1202. tm.assert_equal(result, expected)
  1203. def test_tdi_mul_float_series(self, box_with_array):
  1204. box = box_with_array
  1205. xbox = Series if box in [Index, tm.to_array, pd.array] else box
  1206. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1207. idx = tm.box_expected(idx, box)
  1208. rng5f = np.arange(5, dtype="float64")
  1209. expected = TimedeltaIndex(rng5f * (rng5f + 1.0))
  1210. expected = tm.box_expected(expected, xbox)
  1211. result = idx * Series(rng5f + 1.0)
  1212. tm.assert_equal(result, expected)
  1213. # TODO: Put Series/DataFrame in others?
  1214. @pytest.mark.parametrize(
  1215. "other",
  1216. [
  1217. np.arange(1, 11),
  1218. Index(np.arange(1, 11), np.int64),
  1219. Index(range(1, 11), np.uint64),
  1220. Index(range(1, 11), np.float64),
  1221. pd.RangeIndex(1, 11),
  1222. ],
  1223. ids=lambda x: type(x).__name__,
  1224. )
  1225. def test_tdi_rmul_arraylike(self, other, box_with_array):
  1226. box = box_with_array
  1227. tdi = TimedeltaIndex(["1 Day"] * 10)
  1228. expected = timedelta_range("1 days", "10 days")._with_freq(None)
  1229. tdi = tm.box_expected(tdi, box)
  1230. xbox = get_upcast_box(tdi, other)
  1231. expected = tm.box_expected(expected, xbox)
  1232. result = other * tdi
  1233. tm.assert_equal(result, expected)
  1234. commute = tdi * other
  1235. tm.assert_equal(commute, expected)
  1236. # ------------------------------------------------------------------
  1237. # __div__, __rdiv__
  1238. def test_td64arr_div_nat_invalid(self, box_with_array):
  1239. # don't allow division by NaT (maybe could in the future)
  1240. rng = timedelta_range("1 days", "10 days", name="foo")
  1241. rng = tm.box_expected(rng, box_with_array)
  1242. with pytest.raises(TypeError, match="unsupported operand type"):
  1243. rng / NaT
  1244. with pytest.raises(TypeError, match="Cannot divide NaTType by"):
  1245. NaT / rng
  1246. dt64nat = np.datetime64("NaT", "ns")
  1247. msg = "|".join(
  1248. [
  1249. # 'divide' on npdev as of 2021-12-18
  1250. "ufunc '(true_divide|divide)' cannot use operands",
  1251. "cannot perform __r?truediv__",
  1252. "Cannot divide datetime64 by TimedeltaArray",
  1253. ]
  1254. )
  1255. with pytest.raises(TypeError, match=msg):
  1256. rng / dt64nat
  1257. with pytest.raises(TypeError, match=msg):
  1258. dt64nat / rng
  1259. def test_td64arr_div_td64nat(self, box_with_array):
  1260. # GH#23829
  1261. box = box_with_array
  1262. xbox = np.ndarray if box is pd.array else box
  1263. rng = timedelta_range("1 days", "10 days")
  1264. rng = tm.box_expected(rng, box)
  1265. other = np.timedelta64("NaT")
  1266. expected = np.array([np.nan] * 10)
  1267. expected = tm.box_expected(expected, xbox)
  1268. result = rng / other
  1269. tm.assert_equal(result, expected)
  1270. result = other / rng
  1271. tm.assert_equal(result, expected)
  1272. def test_td64arr_div_int(self, box_with_array):
  1273. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1274. idx = tm.box_expected(idx, box_with_array)
  1275. result = idx / 1
  1276. tm.assert_equal(result, idx)
  1277. with pytest.raises(TypeError, match="Cannot divide"):
  1278. # GH#23829
  1279. 1 / idx
  1280. def test_td64arr_div_tdlike_scalar(self, two_hours, box_with_array):
  1281. # GH#20088, GH#22163 ensure DataFrame returns correct dtype
  1282. box = box_with_array
  1283. xbox = np.ndarray if box is pd.array else box
  1284. rng = timedelta_range("1 days", "10 days", name="foo")
  1285. expected = Index((np.arange(10) + 1) * 12, dtype=np.float64, name="foo")
  1286. rng = tm.box_expected(rng, box)
  1287. expected = tm.box_expected(expected, xbox)
  1288. result = rng / two_hours
  1289. tm.assert_equal(result, expected)
  1290. result = two_hours / rng
  1291. expected = 1 / expected
  1292. tm.assert_equal(result, expected)
  1293. @pytest.mark.parametrize("m", [1, 3, 10])
  1294. @pytest.mark.parametrize("unit", ["D", "h", "m", "s", "ms", "us", "ns"])
  1295. def test_td64arr_div_td64_scalar(self, m, unit, box_with_array):
  1296. box = box_with_array
  1297. xbox = np.ndarray if box is pd.array else box
  1298. ser = Series([Timedelta(days=59)] * 3)
  1299. ser[2] = np.nan
  1300. flat = ser
  1301. ser = tm.box_expected(ser, box)
  1302. # op
  1303. expected = Series([x / np.timedelta64(m, unit) for x in flat])
  1304. expected = tm.box_expected(expected, xbox)
  1305. result = ser / np.timedelta64(m, unit)
  1306. tm.assert_equal(result, expected)
  1307. # reverse op
  1308. expected = Series([Timedelta(np.timedelta64(m, unit)) / x for x in flat])
  1309. expected = tm.box_expected(expected, xbox)
  1310. result = np.timedelta64(m, unit) / ser
  1311. tm.assert_equal(result, expected)
  1312. def test_td64arr_div_tdlike_scalar_with_nat(self, two_hours, box_with_array):
  1313. box = box_with_array
  1314. xbox = np.ndarray if box is pd.array else box
  1315. rng = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo")
  1316. expected = Index([12, np.nan, 24], dtype=np.float64, name="foo")
  1317. rng = tm.box_expected(rng, box)
  1318. expected = tm.box_expected(expected, xbox)
  1319. result = rng / two_hours
  1320. tm.assert_equal(result, expected)
  1321. result = two_hours / rng
  1322. expected = 1 / expected
  1323. tm.assert_equal(result, expected)
  1324. def test_td64arr_div_td64_ndarray(self, box_with_array):
  1325. # GH#22631
  1326. box = box_with_array
  1327. xbox = np.ndarray if box is pd.array else box
  1328. rng = TimedeltaIndex(["1 days", NaT, "2 days"])
  1329. expected = Index([12, np.nan, 24], dtype=np.float64)
  1330. rng = tm.box_expected(rng, box)
  1331. expected = tm.box_expected(expected, xbox)
  1332. other = np.array([2, 4, 2], dtype="m8[h]")
  1333. result = rng / other
  1334. tm.assert_equal(result, expected)
  1335. result = rng / tm.box_expected(other, box)
  1336. tm.assert_equal(result, expected)
  1337. result = rng / other.astype(object)
  1338. tm.assert_equal(result, expected.astype(object))
  1339. result = rng / list(other)
  1340. tm.assert_equal(result, expected)
  1341. # reversed op
  1342. expected = 1 / expected
  1343. result = other / rng
  1344. tm.assert_equal(result, expected)
  1345. result = tm.box_expected(other, box) / rng
  1346. tm.assert_equal(result, expected)
  1347. result = other.astype(object) / rng
  1348. tm.assert_equal(result, expected)
  1349. result = list(other) / rng
  1350. tm.assert_equal(result, expected)
  1351. def test_tdarr_div_length_mismatch(self, box_with_array):
  1352. rng = TimedeltaIndex(["1 days", NaT, "2 days"])
  1353. mismatched = [1, 2, 3, 4]
  1354. rng = tm.box_expected(rng, box_with_array)
  1355. msg = "Cannot divide vectors|Unable to coerce to Series"
  1356. for obj in [mismatched, mismatched[:2]]:
  1357. # one shorter, one longer
  1358. for other in [obj, np.array(obj), Index(obj)]:
  1359. with pytest.raises(ValueError, match=msg):
  1360. rng / other
  1361. with pytest.raises(ValueError, match=msg):
  1362. other / rng
  1363. def test_td64_div_object_mixed_result(self, box_with_array):
  1364. # Case where we having a NaT in the result inseat of timedelta64("NaT")
  1365. # is misleading
  1366. orig = timedelta_range("1 Day", periods=3).insert(1, NaT)
  1367. tdi = tm.box_expected(orig, box_with_array, transpose=False)
  1368. other = np.array([orig[0], 1.5, 2.0, orig[2]], dtype=object)
  1369. other = tm.box_expected(other, box_with_array, transpose=False)
  1370. res = tdi / other
  1371. expected = Index([1.0, np.timedelta64("NaT", "ns"), orig[0], 1.5], dtype=object)
  1372. expected = tm.box_expected(expected, box_with_array, transpose=False)
  1373. if isinstance(expected, PandasArray):
  1374. expected = expected.to_numpy()
  1375. tm.assert_equal(res, expected)
  1376. if box_with_array is DataFrame:
  1377. # We have a np.timedelta64(NaT), not pd.NaT
  1378. assert isinstance(res.iloc[1, 0], np.timedelta64)
  1379. res = tdi // other
  1380. expected = Index([1, np.timedelta64("NaT", "ns"), orig[0], 1], dtype=object)
  1381. expected = tm.box_expected(expected, box_with_array, transpose=False)
  1382. if isinstance(expected, PandasArray):
  1383. expected = expected.to_numpy()
  1384. tm.assert_equal(res, expected)
  1385. if box_with_array is DataFrame:
  1386. # We have a np.timedelta64(NaT), not pd.NaT
  1387. assert isinstance(res.iloc[1, 0], np.timedelta64)
  1388. # ------------------------------------------------------------------
  1389. # __floordiv__, __rfloordiv__
  1390. def test_td64arr_floordiv_td64arr_with_nat(
  1391. self, box_with_array, using_array_manager
  1392. ):
  1393. # GH#35529
  1394. box = box_with_array
  1395. xbox = np.ndarray if box is pd.array else box
  1396. left = Series([1000, 222330, 30], dtype="timedelta64[ns]")
  1397. right = Series([1000, 222330, None], dtype="timedelta64[ns]")
  1398. left = tm.box_expected(left, box)
  1399. right = tm.box_expected(right, box)
  1400. expected = np.array([1.0, 1.0, np.nan], dtype=np.float64)
  1401. expected = tm.box_expected(expected, xbox)
  1402. if box is DataFrame and using_array_manager:
  1403. # INFO(ArrayManager) floordiv returns integer, and ArrayManager
  1404. # performs ops column-wise and thus preserves int64 dtype for
  1405. # columns without missing values
  1406. expected[[0, 1]] = expected[[0, 1]].astype("int64")
  1407. with tm.maybe_produces_warning(
  1408. RuntimeWarning, box is pd.array, check_stacklevel=False
  1409. ):
  1410. result = left // right
  1411. tm.assert_equal(result, expected)
  1412. # case that goes through __rfloordiv__ with arraylike
  1413. with tm.maybe_produces_warning(
  1414. RuntimeWarning, box is pd.array, check_stacklevel=False
  1415. ):
  1416. result = np.asarray(left) // right
  1417. tm.assert_equal(result, expected)
  1418. @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning")
  1419. def test_td64arr_floordiv_tdscalar(self, box_with_array, scalar_td):
  1420. # GH#18831, GH#19125
  1421. box = box_with_array
  1422. xbox = np.ndarray if box is pd.array else box
  1423. td = Timedelta("5m3s") # i.e. (scalar_td - 1sec) / 2
  1424. td1 = Series([td, td, NaT], dtype="m8[ns]")
  1425. td1 = tm.box_expected(td1, box, transpose=False)
  1426. expected = Series([0, 0, np.nan])
  1427. expected = tm.box_expected(expected, xbox, transpose=False)
  1428. result = td1 // scalar_td
  1429. tm.assert_equal(result, expected)
  1430. # Reversed op
  1431. expected = Series([2, 2, np.nan])
  1432. expected = tm.box_expected(expected, xbox, transpose=False)
  1433. result = scalar_td // td1
  1434. tm.assert_equal(result, expected)
  1435. # same thing buts let's be explicit about calling __rfloordiv__
  1436. result = td1.__rfloordiv__(scalar_td)
  1437. tm.assert_equal(result, expected)
  1438. def test_td64arr_floordiv_int(self, box_with_array):
  1439. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1440. idx = tm.box_expected(idx, box_with_array)
  1441. result = idx // 1
  1442. tm.assert_equal(result, idx)
  1443. pattern = "floor_divide cannot use operands|Cannot divide int by Timedelta*"
  1444. with pytest.raises(TypeError, match=pattern):
  1445. 1 // idx
  1446. # ------------------------------------------------------------------
  1447. # mod, divmod
  1448. # TODO: operations with timedelta-like arrays, numeric arrays,
  1449. # reversed ops
  1450. def test_td64arr_mod_tdscalar(self, box_with_array, three_days):
  1451. tdi = timedelta_range("1 Day", "9 days")
  1452. tdarr = tm.box_expected(tdi, box_with_array)
  1453. expected = TimedeltaIndex(["1 Day", "2 Days", "0 Days"] * 3)
  1454. expected = tm.box_expected(expected, box_with_array)
  1455. result = tdarr % three_days
  1456. tm.assert_equal(result, expected)
  1457. warn = None
  1458. if box_with_array is DataFrame and isinstance(three_days, pd.DateOffset):
  1459. warn = PerformanceWarning
  1460. # TODO: making expected be object here a result of DataFrame.__divmod__
  1461. # being defined in a naive way that does not dispatch to the underlying
  1462. # array's __divmod__
  1463. expected = expected.astype(object)
  1464. with tm.assert_produces_warning(warn):
  1465. result = divmod(tdarr, three_days)
  1466. tm.assert_equal(result[1], expected)
  1467. tm.assert_equal(result[0], tdarr // three_days)
  1468. def test_td64arr_mod_int(self, box_with_array):
  1469. tdi = timedelta_range("1 ns", "10 ns", periods=10)
  1470. tdarr = tm.box_expected(tdi, box_with_array)
  1471. expected = TimedeltaIndex(["1 ns", "0 ns"] * 5)
  1472. expected = tm.box_expected(expected, box_with_array)
  1473. result = tdarr % 2
  1474. tm.assert_equal(result, expected)
  1475. msg = "Cannot divide int by"
  1476. with pytest.raises(TypeError, match=msg):
  1477. 2 % tdarr
  1478. result = divmod(tdarr, 2)
  1479. tm.assert_equal(result[1], expected)
  1480. tm.assert_equal(result[0], tdarr // 2)
  1481. def test_td64arr_rmod_tdscalar(self, box_with_array, three_days):
  1482. tdi = timedelta_range("1 Day", "9 days")
  1483. tdarr = tm.box_expected(tdi, box_with_array)
  1484. expected = ["0 Days", "1 Day", "0 Days"] + ["3 Days"] * 6
  1485. expected = TimedeltaIndex(expected)
  1486. expected = tm.box_expected(expected, box_with_array)
  1487. result = three_days % tdarr
  1488. tm.assert_equal(result, expected)
  1489. result = divmod(three_days, tdarr)
  1490. tm.assert_equal(result[1], expected)
  1491. tm.assert_equal(result[0], three_days // tdarr)
  1492. # ------------------------------------------------------------------
  1493. # Operations with invalid others
  1494. def test_td64arr_mul_tdscalar_invalid(self, box_with_array, scalar_td):
  1495. td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
  1496. td1.iloc[2] = np.nan
  1497. td1 = tm.box_expected(td1, box_with_array)
  1498. # check that we are getting a TypeError
  1499. # with 'operate' (from core/ops.py) for the ops that are not
  1500. # defined
  1501. pattern = "operate|unsupported|cannot|not supported"
  1502. with pytest.raises(TypeError, match=pattern):
  1503. td1 * scalar_td
  1504. with pytest.raises(TypeError, match=pattern):
  1505. scalar_td * td1
  1506. def test_td64arr_mul_too_short_raises(self, box_with_array):
  1507. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1508. idx = tm.box_expected(idx, box_with_array)
  1509. msg = "|".join(
  1510. [
  1511. "cannot use operands with types dtype",
  1512. "Cannot multiply with unequal lengths",
  1513. "Unable to coerce to Series",
  1514. ]
  1515. )
  1516. with pytest.raises(TypeError, match=msg):
  1517. # length check before dtype check
  1518. idx * idx[:3]
  1519. with pytest.raises(ValueError, match=msg):
  1520. idx * np.array([1, 2])
  1521. def test_td64arr_mul_td64arr_raises(self, box_with_array):
  1522. idx = TimedeltaIndex(np.arange(5, dtype="int64"))
  1523. idx = tm.box_expected(idx, box_with_array)
  1524. msg = "cannot use operands with types dtype"
  1525. with pytest.raises(TypeError, match=msg):
  1526. idx * idx
  1527. # ------------------------------------------------------------------
  1528. # Operations with numeric others
  1529. def test_td64arr_mul_numeric_scalar(self, box_with_array, one):
  1530. # GH#4521
  1531. # divide/multiply by integers
  1532. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  1533. expected = Series(["-59 Days", "-59 Days", "NaT"], dtype="timedelta64[ns]")
  1534. tdser = tm.box_expected(tdser, box_with_array)
  1535. expected = tm.box_expected(expected, box_with_array)
  1536. result = tdser * (-one)
  1537. tm.assert_equal(result, expected)
  1538. result = (-one) * tdser
  1539. tm.assert_equal(result, expected)
  1540. expected = Series(["118 Days", "118 Days", "NaT"], dtype="timedelta64[ns]")
  1541. expected = tm.box_expected(expected, box_with_array)
  1542. result = tdser * (2 * one)
  1543. tm.assert_equal(result, expected)
  1544. result = (2 * one) * tdser
  1545. tm.assert_equal(result, expected)
  1546. @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)])
  1547. def test_td64arr_div_numeric_scalar(self, box_with_array, two):
  1548. # GH#4521
  1549. # divide/multiply by integers
  1550. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  1551. expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
  1552. tdser = tm.box_expected(tdser, box_with_array)
  1553. expected = tm.box_expected(expected, box_with_array)
  1554. result = tdser / two
  1555. tm.assert_equal(result, expected)
  1556. with pytest.raises(TypeError, match="Cannot divide"):
  1557. two / tdser
  1558. @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)])
  1559. def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two):
  1560. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  1561. expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
  1562. tdser = tm.box_expected(tdser, box_with_array)
  1563. expected = tm.box_expected(expected, box_with_array)
  1564. result = tdser // two
  1565. tm.assert_equal(result, expected)
  1566. with pytest.raises(TypeError, match="Cannot divide"):
  1567. two // tdser
  1568. @pytest.mark.parametrize(
  1569. "vector",
  1570. [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
  1571. ids=lambda x: type(x).__name__,
  1572. )
  1573. def test_td64arr_rmul_numeric_array(
  1574. self,
  1575. box_with_array,
  1576. vector,
  1577. any_real_numpy_dtype,
  1578. ):
  1579. # GH#4521
  1580. # divide/multiply by integers
  1581. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  1582. vector = vector.astype(any_real_numpy_dtype)
  1583. expected = Series(["1180 Days", "1770 Days", "NaT"], dtype="timedelta64[ns]")
  1584. tdser = tm.box_expected(tdser, box_with_array)
  1585. xbox = get_upcast_box(tdser, vector)
  1586. expected = tm.box_expected(expected, xbox)
  1587. result = tdser * vector
  1588. tm.assert_equal(result, expected)
  1589. result = vector * tdser
  1590. tm.assert_equal(result, expected)
  1591. @pytest.mark.parametrize(
  1592. "vector",
  1593. [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
  1594. ids=lambda x: type(x).__name__,
  1595. )
  1596. def test_td64arr_div_numeric_array(
  1597. self, box_with_array, vector, any_real_numpy_dtype
  1598. ):
  1599. # GH#4521
  1600. # divide/multiply by integers
  1601. tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
  1602. vector = vector.astype(any_real_numpy_dtype)
  1603. expected = Series(["2.95D", "1D 23H 12m", "NaT"], dtype="timedelta64[ns]")
  1604. tdser = tm.box_expected(tdser, box_with_array)
  1605. xbox = get_upcast_box(tdser, vector)
  1606. expected = tm.box_expected(expected, xbox)
  1607. result = tdser / vector
  1608. tm.assert_equal(result, expected)
  1609. pattern = "|".join(
  1610. [
  1611. "true_divide'? cannot use operands",
  1612. "cannot perform __div__",
  1613. "cannot perform __truediv__",
  1614. "unsupported operand",
  1615. "Cannot divide",
  1616. "ufunc 'divide' cannot use operands with types",
  1617. ]
  1618. )
  1619. with pytest.raises(TypeError, match=pattern):
  1620. vector / tdser
  1621. result = tdser / vector.astype(object)
  1622. if box_with_array is DataFrame:
  1623. expected = [tdser.iloc[0, n] / vector[n] for n in range(len(vector))]
  1624. expected = tm.box_expected(expected, xbox).astype(object)
  1625. else:
  1626. expected = [tdser[n] / vector[n] for n in range(len(tdser))]
  1627. expected = [
  1628. x if x is not NaT else np.timedelta64("NaT", "ns") for x in expected
  1629. ]
  1630. if xbox is tm.to_array:
  1631. expected = tm.to_array(expected).astype(object)
  1632. else:
  1633. expected = xbox(expected, dtype=object)
  1634. tm.assert_equal(result, expected)
  1635. with pytest.raises(TypeError, match=pattern):
  1636. vector.astype(object) / tdser
  1637. def test_td64arr_mul_int_series(self, box_with_array, names):
  1638. # GH#19042 test for correct name attachment
  1639. box = box_with_array
  1640. exname = get_expected_name(box, names)
  1641. tdi = TimedeltaIndex(
  1642. ["0days", "1day", "2days", "3days", "4days"], name=names[0]
  1643. )
  1644. # TODO: Should we be parametrizing over types for `ser` too?
  1645. ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1])
  1646. expected = Series(
  1647. ["0days", "1day", "4days", "9days", "16days"],
  1648. dtype="timedelta64[ns]",
  1649. name=exname,
  1650. )
  1651. tdi = tm.box_expected(tdi, box)
  1652. xbox = get_upcast_box(tdi, ser)
  1653. expected = tm.box_expected(expected, xbox)
  1654. result = ser * tdi
  1655. tm.assert_equal(result, expected)
  1656. result = tdi * ser
  1657. tm.assert_equal(result, expected)
  1658. # TODO: Should we be parametrizing over types for `ser` too?
  1659. def test_float_series_rdiv_td64arr(self, box_with_array, names):
  1660. # GH#19042 test for correct name attachment
  1661. box = box_with_array
  1662. tdi = TimedeltaIndex(
  1663. ["0days", "1day", "2days", "3days", "4days"], name=names[0]
  1664. )
  1665. ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1])
  1666. xname = names[2] if box not in [tm.to_array, pd.array] else names[1]
  1667. expected = Series(
  1668. [tdi[n] / ser[n] for n in range(len(ser))],
  1669. dtype="timedelta64[ns]",
  1670. name=xname,
  1671. )
  1672. tdi = tm.box_expected(tdi, box)
  1673. xbox = get_upcast_box(tdi, ser)
  1674. expected = tm.box_expected(expected, xbox)
  1675. result = ser.__rtruediv__(tdi)
  1676. if box is DataFrame:
  1677. assert result is NotImplemented
  1678. else:
  1679. tm.assert_equal(result, expected)
  1680. def test_td64arr_all_nat_div_object_dtype_numeric(self, box_with_array):
  1681. # GH#39750 make sure we infer the result as td64
  1682. tdi = TimedeltaIndex([NaT, NaT])
  1683. left = tm.box_expected(tdi, box_with_array)
  1684. right = np.array([2, 2.0], dtype=object)
  1685. expected = Index([np.timedelta64("NaT", "ns")] * 2, dtype=object)
  1686. if box_with_array is not Index:
  1687. expected = tm.box_expected(expected, box_with_array).astype(object)
  1688. result = left / right
  1689. tm.assert_equal(result, expected)
  1690. result = left // right
  1691. tm.assert_equal(result, expected)
  1692. class TestTimedelta64ArrayLikeArithmetic:
  1693. # Arithmetic tests for timedelta64[ns] vectors fully parametrized over
  1694. # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all arithmetic
  1695. # tests will eventually end up here.
  1696. def test_td64arr_pow_invalid(self, scalar_td, box_with_array):
  1697. td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
  1698. td1.iloc[2] = np.nan
  1699. td1 = tm.box_expected(td1, box_with_array)
  1700. # check that we are getting a TypeError
  1701. # with 'operate' (from core/ops.py) for the ops that are not
  1702. # defined
  1703. pattern = "operate|unsupported|cannot|not supported"
  1704. with pytest.raises(TypeError, match=pattern):
  1705. scalar_td**td1
  1706. with pytest.raises(TypeError, match=pattern):
  1707. td1**scalar_td
  1708. def test_add_timestamp_to_timedelta():
  1709. # GH: 35897
  1710. timestamp = Timestamp("2021-01-01")
  1711. result = timestamp + timedelta_range("0s", "1s", periods=31)
  1712. expected = DatetimeIndex(
  1713. [
  1714. timestamp
  1715. + (
  1716. pd.to_timedelta("0.033333333s") * i
  1717. + pd.to_timedelta("0.000000001s") * divmod(i, 3)[0]
  1718. )
  1719. for i in range(31)
  1720. ]
  1721. )
  1722. tm.assert_index_equal(result, expected)