test_interval.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. from itertools import permutations
  2. import re
  3. import numpy as np
  4. import pytest
  5. import pandas as pd
  6. from pandas import (
  7. Index,
  8. Interval,
  9. IntervalIndex,
  10. Timedelta,
  11. Timestamp,
  12. date_range,
  13. interval_range,
  14. isna,
  15. notna,
  16. timedelta_range,
  17. )
  18. import pandas._testing as tm
  19. import pandas.core.common as com
  20. @pytest.fixture(params=[None, "foo"])
  21. def name(request):
  22. return request.param
  23. class TestIntervalIndex:
  24. index = IntervalIndex.from_arrays([0, 1], [1, 2])
  25. def create_index(self, closed="right"):
  26. return IntervalIndex.from_breaks(range(11), closed=closed)
  27. def create_index_with_nan(self, closed="right"):
  28. mask = [True, False] + [True] * 8
  29. return IntervalIndex.from_arrays(
  30. np.where(mask, np.arange(10), np.nan),
  31. np.where(mask, np.arange(1, 11), np.nan),
  32. closed=closed,
  33. )
  34. def test_properties(self, closed):
  35. index = self.create_index(closed=closed)
  36. assert len(index) == 10
  37. assert index.size == 10
  38. assert index.shape == (10,)
  39. tm.assert_index_equal(index.left, Index(np.arange(10, dtype=np.int64)))
  40. tm.assert_index_equal(index.right, Index(np.arange(1, 11, dtype=np.int64)))
  41. tm.assert_index_equal(index.mid, Index(np.arange(0.5, 10.5, dtype=np.float64)))
  42. assert index.closed == closed
  43. ivs = [
  44. Interval(left, right, closed)
  45. for left, right in zip(range(10), range(1, 11))
  46. ]
  47. expected = np.array(ivs, dtype=object)
  48. tm.assert_numpy_array_equal(np.asarray(index), expected)
  49. # with nans
  50. index = self.create_index_with_nan(closed=closed)
  51. assert len(index) == 10
  52. assert index.size == 10
  53. assert index.shape == (10,)
  54. expected_left = Index([0, np.nan, 2, 3, 4, 5, 6, 7, 8, 9])
  55. expected_right = expected_left + 1
  56. expected_mid = expected_left + 0.5
  57. tm.assert_index_equal(index.left, expected_left)
  58. tm.assert_index_equal(index.right, expected_right)
  59. tm.assert_index_equal(index.mid, expected_mid)
  60. assert index.closed == closed
  61. ivs = [
  62. Interval(left, right, closed) if notna(left) else np.nan
  63. for left, right in zip(expected_left, expected_right)
  64. ]
  65. expected = np.array(ivs, dtype=object)
  66. tm.assert_numpy_array_equal(np.asarray(index), expected)
  67. @pytest.mark.parametrize(
  68. "breaks",
  69. [
  70. [1, 1, 2, 5, 15, 53, 217, 1014, 5335, 31240, 201608],
  71. [-np.inf, -100, -10, 0.5, 1, 1.5, 3.8, 101, 202, np.inf],
  72. date_range("2017-01-01", "2017-01-04"),
  73. pytest.param(
  74. date_range("2017-01-01", "2017-01-04", unit="s"),
  75. marks=pytest.mark.xfail(reason="mismatched result unit"),
  76. ),
  77. pd.to_timedelta(["1ns", "2ms", "3s", "4min", "5h", "6D"]),
  78. ],
  79. )
  80. def test_length(self, closed, breaks):
  81. # GH 18789
  82. index = IntervalIndex.from_breaks(breaks, closed=closed)
  83. result = index.length
  84. expected = Index(iv.length for iv in index)
  85. tm.assert_index_equal(result, expected)
  86. # with NA
  87. index = index.insert(1, np.nan)
  88. result = index.length
  89. expected = Index(iv.length if notna(iv) else iv for iv in index)
  90. tm.assert_index_equal(result, expected)
  91. def test_with_nans(self, closed):
  92. index = self.create_index(closed=closed)
  93. assert index.hasnans is False
  94. result = index.isna()
  95. expected = np.zeros(len(index), dtype=bool)
  96. tm.assert_numpy_array_equal(result, expected)
  97. result = index.notna()
  98. expected = np.ones(len(index), dtype=bool)
  99. tm.assert_numpy_array_equal(result, expected)
  100. index = self.create_index_with_nan(closed=closed)
  101. assert index.hasnans is True
  102. result = index.isna()
  103. expected = np.array([False, True] + [False] * (len(index) - 2))
  104. tm.assert_numpy_array_equal(result, expected)
  105. result = index.notna()
  106. expected = np.array([True, False] + [True] * (len(index) - 2))
  107. tm.assert_numpy_array_equal(result, expected)
  108. def test_copy(self, closed):
  109. expected = self.create_index(closed=closed)
  110. result = expected.copy()
  111. assert result.equals(expected)
  112. result = expected.copy(deep=True)
  113. assert result.equals(expected)
  114. assert result.left is not expected.left
  115. def test_ensure_copied_data(self, closed):
  116. # exercise the copy flag in the constructor
  117. # not copying
  118. index = self.create_index(closed=closed)
  119. result = IntervalIndex(index, copy=False)
  120. tm.assert_numpy_array_equal(
  121. index.left.values, result.left.values, check_same="same"
  122. )
  123. tm.assert_numpy_array_equal(
  124. index.right.values, result.right.values, check_same="same"
  125. )
  126. # by-definition make a copy
  127. result = IntervalIndex(np.array(index), copy=False)
  128. tm.assert_numpy_array_equal(
  129. index.left.values, result.left.values, check_same="copy"
  130. )
  131. tm.assert_numpy_array_equal(
  132. index.right.values, result.right.values, check_same="copy"
  133. )
  134. def test_delete(self, closed):
  135. breaks = np.arange(1, 11, dtype=np.int64)
  136. expected = IntervalIndex.from_breaks(breaks, closed=closed)
  137. result = self.create_index(closed=closed).delete(0)
  138. tm.assert_index_equal(result, expected)
  139. @pytest.mark.parametrize(
  140. "data",
  141. [
  142. interval_range(0, periods=10, closed="neither"),
  143. interval_range(1.7, periods=8, freq=2.5, closed="both"),
  144. interval_range(Timestamp("20170101"), periods=12, closed="left"),
  145. interval_range(Timedelta("1 day"), periods=6, closed="right"),
  146. ],
  147. )
  148. def test_insert(self, data):
  149. item = data[0]
  150. idx_item = IntervalIndex([item])
  151. # start
  152. expected = idx_item.append(data)
  153. result = data.insert(0, item)
  154. tm.assert_index_equal(result, expected)
  155. # end
  156. expected = data.append(idx_item)
  157. result = data.insert(len(data), item)
  158. tm.assert_index_equal(result, expected)
  159. # mid
  160. expected = data[:3].append(idx_item).append(data[3:])
  161. result = data.insert(3, item)
  162. tm.assert_index_equal(result, expected)
  163. # invalid type
  164. res = data.insert(1, "foo")
  165. expected = data.astype(object).insert(1, "foo")
  166. tm.assert_index_equal(res, expected)
  167. msg = "can only insert Interval objects and NA into an IntervalArray"
  168. with pytest.raises(TypeError, match=msg):
  169. data._data.insert(1, "foo")
  170. # invalid closed
  171. msg = "'value.closed' is 'left', expected 'right'."
  172. for closed in {"left", "right", "both", "neither"} - {item.closed}:
  173. msg = f"'value.closed' is '{closed}', expected '{item.closed}'."
  174. bad_item = Interval(item.left, item.right, closed=closed)
  175. res = data.insert(1, bad_item)
  176. expected = data.astype(object).insert(1, bad_item)
  177. tm.assert_index_equal(res, expected)
  178. with pytest.raises(ValueError, match=msg):
  179. data._data.insert(1, bad_item)
  180. # GH 18295 (test missing)
  181. na_idx = IntervalIndex([np.nan], closed=data.closed)
  182. for na in [np.nan, None, pd.NA]:
  183. expected = data[:1].append(na_idx).append(data[1:])
  184. result = data.insert(1, na)
  185. tm.assert_index_equal(result, expected)
  186. if data.left.dtype.kind not in ["m", "M"]:
  187. # trying to insert pd.NaT into a numeric-dtyped Index should cast
  188. expected = data.astype(object).insert(1, pd.NaT)
  189. msg = "can only insert Interval objects and NA into an IntervalArray"
  190. with pytest.raises(TypeError, match=msg):
  191. data._data.insert(1, pd.NaT)
  192. result = data.insert(1, pd.NaT)
  193. tm.assert_index_equal(result, expected)
  194. def test_is_unique_interval(self, closed):
  195. """
  196. Interval specific tests for is_unique in addition to base class tests
  197. """
  198. # unique overlapping - distinct endpoints
  199. idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed)
  200. assert idx.is_unique is True
  201. # unique overlapping - shared endpoints
  202. idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
  203. assert idx.is_unique is True
  204. # unique nested
  205. idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed)
  206. assert idx.is_unique is True
  207. # unique NaN
  208. idx = IntervalIndex.from_tuples([(np.nan, np.nan)], closed=closed)
  209. assert idx.is_unique is True
  210. # non-unique NaN
  211. idx = IntervalIndex.from_tuples(
  212. [(np.nan, np.nan), (np.nan, np.nan)], closed=closed
  213. )
  214. assert idx.is_unique is False
  215. def test_monotonic(self, closed):
  216. # increasing non-overlapping
  217. idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], closed=closed)
  218. assert idx.is_monotonic_increasing is True
  219. assert idx._is_strictly_monotonic_increasing is True
  220. assert idx.is_monotonic_decreasing is False
  221. assert idx._is_strictly_monotonic_decreasing is False
  222. # decreasing non-overlapping
  223. idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], closed=closed)
  224. assert idx.is_monotonic_increasing is False
  225. assert idx._is_strictly_monotonic_increasing is False
  226. assert idx.is_monotonic_decreasing is True
  227. assert idx._is_strictly_monotonic_decreasing is True
  228. # unordered non-overlapping
  229. idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], closed=closed)
  230. assert idx.is_monotonic_increasing is False
  231. assert idx._is_strictly_monotonic_increasing is False
  232. assert idx.is_monotonic_decreasing is False
  233. assert idx._is_strictly_monotonic_decreasing is False
  234. # increasing overlapping
  235. idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], closed=closed)
  236. assert idx.is_monotonic_increasing is True
  237. assert idx._is_strictly_monotonic_increasing is True
  238. assert idx.is_monotonic_decreasing is False
  239. assert idx._is_strictly_monotonic_decreasing is False
  240. # decreasing overlapping
  241. idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], closed=closed)
  242. assert idx.is_monotonic_increasing is False
  243. assert idx._is_strictly_monotonic_increasing is False
  244. assert idx.is_monotonic_decreasing is True
  245. assert idx._is_strictly_monotonic_decreasing is True
  246. # unordered overlapping
  247. idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], closed=closed)
  248. assert idx.is_monotonic_increasing is False
  249. assert idx._is_strictly_monotonic_increasing is False
  250. assert idx.is_monotonic_decreasing is False
  251. assert idx._is_strictly_monotonic_decreasing is False
  252. # increasing overlapping shared endpoints
  253. idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
  254. assert idx.is_monotonic_increasing is True
  255. assert idx._is_strictly_monotonic_increasing is True
  256. assert idx.is_monotonic_decreasing is False
  257. assert idx._is_strictly_monotonic_decreasing is False
  258. # decreasing overlapping shared endpoints
  259. idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)
  260. assert idx.is_monotonic_increasing is False
  261. assert idx._is_strictly_monotonic_increasing is False
  262. assert idx.is_monotonic_decreasing is True
  263. assert idx._is_strictly_monotonic_decreasing is True
  264. # stationary
  265. idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed)
  266. assert idx.is_monotonic_increasing is True
  267. assert idx._is_strictly_monotonic_increasing is False
  268. assert idx.is_monotonic_decreasing is True
  269. assert idx._is_strictly_monotonic_decreasing is False
  270. # empty
  271. idx = IntervalIndex([], closed=closed)
  272. assert idx.is_monotonic_increasing is True
  273. assert idx._is_strictly_monotonic_increasing is True
  274. assert idx.is_monotonic_decreasing is True
  275. assert idx._is_strictly_monotonic_decreasing is True
  276. def test_is_monotonic_with_nans(self):
  277. # GH#41831
  278. index = IntervalIndex([np.nan, np.nan])
  279. assert not index.is_monotonic_increasing
  280. assert not index._is_strictly_monotonic_increasing
  281. assert not index.is_monotonic_increasing
  282. assert not index._is_strictly_monotonic_decreasing
  283. assert not index.is_monotonic_decreasing
  284. @pytest.mark.parametrize(
  285. "breaks",
  286. [
  287. date_range("20180101", periods=4),
  288. date_range("20180101", periods=4, tz="US/Eastern"),
  289. timedelta_range("0 days", periods=4),
  290. ],
  291. ids=lambda x: str(x.dtype),
  292. )
  293. def test_maybe_convert_i8(self, breaks):
  294. # GH 20636
  295. index = IntervalIndex.from_breaks(breaks)
  296. # intervalindex
  297. result = index._maybe_convert_i8(index)
  298. expected = IntervalIndex.from_breaks(breaks.asi8)
  299. tm.assert_index_equal(result, expected)
  300. # interval
  301. interval = Interval(breaks[0], breaks[1])
  302. result = index._maybe_convert_i8(interval)
  303. expected = Interval(breaks[0]._value, breaks[1]._value)
  304. assert result == expected
  305. # datetimelike index
  306. result = index._maybe_convert_i8(breaks)
  307. expected = Index(breaks.asi8)
  308. tm.assert_index_equal(result, expected)
  309. # datetimelike scalar
  310. result = index._maybe_convert_i8(breaks[0])
  311. expected = breaks[0]._value
  312. assert result == expected
  313. # list-like of datetimelike scalars
  314. result = index._maybe_convert_i8(list(breaks))
  315. expected = Index(breaks.asi8)
  316. tm.assert_index_equal(result, expected)
  317. @pytest.mark.parametrize(
  318. "breaks",
  319. [date_range("2018-01-01", periods=5), timedelta_range("0 days", periods=5)],
  320. )
  321. def test_maybe_convert_i8_nat(self, breaks):
  322. # GH 20636
  323. index = IntervalIndex.from_breaks(breaks)
  324. to_convert = breaks._constructor([pd.NaT] * 3).as_unit("ns")
  325. expected = Index([np.nan] * 3, dtype=np.float64)
  326. result = index._maybe_convert_i8(to_convert)
  327. tm.assert_index_equal(result, expected)
  328. to_convert = to_convert.insert(0, breaks[0])
  329. expected = expected.insert(0, float(breaks[0]._value))
  330. result = index._maybe_convert_i8(to_convert)
  331. tm.assert_index_equal(result, expected)
  332. @pytest.mark.parametrize(
  333. "make_key",
  334. [lambda breaks: breaks, list],
  335. ids=["lambda", "list"],
  336. )
  337. def test_maybe_convert_i8_numeric(self, make_key, any_real_numpy_dtype):
  338. # GH 20636
  339. breaks = np.arange(5, dtype=any_real_numpy_dtype)
  340. index = IntervalIndex.from_breaks(breaks)
  341. key = make_key(breaks)
  342. result = index._maybe_convert_i8(key)
  343. kind = breaks.dtype.kind
  344. expected_dtype = {"i": np.int64, "u": np.uint64, "f": np.float64}[kind]
  345. expected = Index(key, dtype=expected_dtype)
  346. tm.assert_index_equal(result, expected)
  347. @pytest.mark.parametrize(
  348. "make_key",
  349. [
  350. IntervalIndex.from_breaks,
  351. lambda breaks: Interval(breaks[0], breaks[1]),
  352. lambda breaks: breaks[0],
  353. ],
  354. ids=["IntervalIndex", "Interval", "scalar"],
  355. )
  356. def test_maybe_convert_i8_numeric_identical(self, make_key, any_real_numpy_dtype):
  357. # GH 20636
  358. breaks = np.arange(5, dtype=any_real_numpy_dtype)
  359. index = IntervalIndex.from_breaks(breaks)
  360. key = make_key(breaks)
  361. # test if _maybe_convert_i8 won't change key if an Interval or IntervalIndex
  362. result = index._maybe_convert_i8(key)
  363. assert result is key
  364. @pytest.mark.parametrize(
  365. "breaks1, breaks2",
  366. permutations(
  367. [
  368. date_range("20180101", periods=4),
  369. date_range("20180101", periods=4, tz="US/Eastern"),
  370. timedelta_range("0 days", periods=4),
  371. ],
  372. 2,
  373. ),
  374. ids=lambda x: str(x.dtype),
  375. )
  376. @pytest.mark.parametrize(
  377. "make_key",
  378. [
  379. IntervalIndex.from_breaks,
  380. lambda breaks: Interval(breaks[0], breaks[1]),
  381. lambda breaks: breaks,
  382. lambda breaks: breaks[0],
  383. list,
  384. ],
  385. ids=["IntervalIndex", "Interval", "Index", "scalar", "list"],
  386. )
  387. def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key):
  388. # GH 20636
  389. index = IntervalIndex.from_breaks(breaks1)
  390. key = make_key(breaks2)
  391. msg = (
  392. f"Cannot index an IntervalIndex of subtype {breaks1.dtype} with "
  393. f"values of dtype {breaks2.dtype}"
  394. )
  395. msg = re.escape(msg)
  396. with pytest.raises(ValueError, match=msg):
  397. index._maybe_convert_i8(key)
  398. def test_contains_method(self):
  399. # can select values that are IN the range of a value
  400. i = IntervalIndex.from_arrays([0, 1], [1, 2])
  401. expected = np.array([False, False], dtype="bool")
  402. actual = i.contains(0)
  403. tm.assert_numpy_array_equal(actual, expected)
  404. actual = i.contains(3)
  405. tm.assert_numpy_array_equal(actual, expected)
  406. expected = np.array([True, False], dtype="bool")
  407. actual = i.contains(0.5)
  408. tm.assert_numpy_array_equal(actual, expected)
  409. actual = i.contains(1)
  410. tm.assert_numpy_array_equal(actual, expected)
  411. # __contains__ not implemented for "interval in interval", follow
  412. # that for the contains method for now
  413. with pytest.raises(
  414. NotImplementedError, match="contains not implemented for two"
  415. ):
  416. i.contains(Interval(0, 1))
  417. def test_dropna(self, closed):
  418. expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)
  419. ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed)
  420. result = ii.dropna()
  421. tm.assert_index_equal(result, expected)
  422. ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], closed=closed)
  423. result = ii.dropna()
  424. tm.assert_index_equal(result, expected)
  425. def test_non_contiguous(self, closed):
  426. index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
  427. target = [0.5, 1.5, 2.5]
  428. actual = index.get_indexer(target)
  429. expected = np.array([0, -1, 1], dtype="intp")
  430. tm.assert_numpy_array_equal(actual, expected)
  431. assert 1.5 not in index
  432. def test_isin(self, closed):
  433. index = self.create_index(closed=closed)
  434. expected = np.array([True] + [False] * (len(index) - 1))
  435. result = index.isin(index[:1])
  436. tm.assert_numpy_array_equal(result, expected)
  437. result = index.isin([index[0]])
  438. tm.assert_numpy_array_equal(result, expected)
  439. other = IntervalIndex.from_breaks(np.arange(-2, 10), closed=closed)
  440. expected = np.array([True] * (len(index) - 1) + [False])
  441. result = index.isin(other)
  442. tm.assert_numpy_array_equal(result, expected)
  443. result = index.isin(other.tolist())
  444. tm.assert_numpy_array_equal(result, expected)
  445. for other_closed in ["right", "left", "both", "neither"]:
  446. other = self.create_index(closed=other_closed)
  447. expected = np.repeat(closed == other_closed, len(index))
  448. result = index.isin(other)
  449. tm.assert_numpy_array_equal(result, expected)
  450. result = index.isin(other.tolist())
  451. tm.assert_numpy_array_equal(result, expected)
  452. def test_comparison(self):
  453. actual = Interval(0, 1) < self.index
  454. expected = np.array([False, True])
  455. tm.assert_numpy_array_equal(actual, expected)
  456. actual = Interval(0.5, 1.5) < self.index
  457. expected = np.array([False, True])
  458. tm.assert_numpy_array_equal(actual, expected)
  459. actual = self.index > Interval(0.5, 1.5)
  460. tm.assert_numpy_array_equal(actual, expected)
  461. actual = self.index == self.index
  462. expected = np.array([True, True])
  463. tm.assert_numpy_array_equal(actual, expected)
  464. actual = self.index <= self.index
  465. tm.assert_numpy_array_equal(actual, expected)
  466. actual = self.index >= self.index
  467. tm.assert_numpy_array_equal(actual, expected)
  468. actual = self.index < self.index
  469. expected = np.array([False, False])
  470. tm.assert_numpy_array_equal(actual, expected)
  471. actual = self.index > self.index
  472. tm.assert_numpy_array_equal(actual, expected)
  473. actual = self.index == IntervalIndex.from_breaks([0, 1, 2], "left")
  474. tm.assert_numpy_array_equal(actual, expected)
  475. actual = self.index == self.index.values
  476. tm.assert_numpy_array_equal(actual, np.array([True, True]))
  477. actual = self.index.values == self.index
  478. tm.assert_numpy_array_equal(actual, np.array([True, True]))
  479. actual = self.index <= self.index.values
  480. tm.assert_numpy_array_equal(actual, np.array([True, True]))
  481. actual = self.index != self.index.values
  482. tm.assert_numpy_array_equal(actual, np.array([False, False]))
  483. actual = self.index > self.index.values
  484. tm.assert_numpy_array_equal(actual, np.array([False, False]))
  485. actual = self.index.values > self.index
  486. tm.assert_numpy_array_equal(actual, np.array([False, False]))
  487. # invalid comparisons
  488. actual = self.index == 0
  489. tm.assert_numpy_array_equal(actual, np.array([False, False]))
  490. actual = self.index == self.index.left
  491. tm.assert_numpy_array_equal(actual, np.array([False, False]))
  492. msg = "|".join(
  493. [
  494. "not supported between instances of 'int' and '.*.Interval'",
  495. r"Invalid comparison between dtype=interval\[int64, right\] and ",
  496. ]
  497. )
  498. with pytest.raises(TypeError, match=msg):
  499. self.index > 0
  500. with pytest.raises(TypeError, match=msg):
  501. self.index <= 0
  502. with pytest.raises(TypeError, match=msg):
  503. self.index > np.arange(2)
  504. msg = "Lengths must match to compare"
  505. with pytest.raises(ValueError, match=msg):
  506. self.index > np.arange(3)
  507. def test_missing_values(self, closed):
  508. idx = Index(
  509. [np.nan, Interval(0, 1, closed=closed), Interval(1, 2, closed=closed)]
  510. )
  511. idx2 = IntervalIndex.from_arrays([np.nan, 0, 1], [np.nan, 1, 2], closed=closed)
  512. assert idx.equals(idx2)
  513. msg = (
  514. "missing values must be missing in the same location both left "
  515. "and right sides"
  516. )
  517. with pytest.raises(ValueError, match=msg):
  518. IntervalIndex.from_arrays(
  519. [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed
  520. )
  521. tm.assert_numpy_array_equal(isna(idx), np.array([True, False, False]))
  522. def test_sort_values(self, closed):
  523. index = self.create_index(closed=closed)
  524. result = index.sort_values()
  525. tm.assert_index_equal(result, index)
  526. result = index.sort_values(ascending=False)
  527. tm.assert_index_equal(result, index[::-1])
  528. # with nan
  529. index = IntervalIndex([Interval(1, 2), np.nan, Interval(0, 1)])
  530. result = index.sort_values()
  531. expected = IntervalIndex([Interval(0, 1), Interval(1, 2), np.nan])
  532. tm.assert_index_equal(result, expected)
  533. result = index.sort_values(ascending=False, na_position="first")
  534. expected = IntervalIndex([np.nan, Interval(1, 2), Interval(0, 1)])
  535. tm.assert_index_equal(result, expected)
  536. @pytest.mark.parametrize("tz", [None, "US/Eastern"])
  537. def test_datetime(self, tz):
  538. start = Timestamp("2000-01-01", tz=tz)
  539. dates = date_range(start=start, periods=10)
  540. index = IntervalIndex.from_breaks(dates)
  541. # test mid
  542. start = Timestamp("2000-01-01T12:00", tz=tz)
  543. expected = date_range(start=start, periods=9)
  544. tm.assert_index_equal(index.mid, expected)
  545. # __contains__ doesn't check individual points
  546. assert Timestamp("2000-01-01", tz=tz) not in index
  547. assert Timestamp("2000-01-01T12", tz=tz) not in index
  548. assert Timestamp("2000-01-02", tz=tz) not in index
  549. iv_true = Interval(
  550. Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz)
  551. )
  552. iv_false = Interval(
  553. Timestamp("1999-12-31", tz=tz), Timestamp("2000-01-01", tz=tz)
  554. )
  555. assert iv_true in index
  556. assert iv_false not in index
  557. # .contains does check individual points
  558. assert not index.contains(Timestamp("2000-01-01", tz=tz)).any()
  559. assert index.contains(Timestamp("2000-01-01T12", tz=tz)).any()
  560. assert index.contains(Timestamp("2000-01-02", tz=tz)).any()
  561. # test get_indexer
  562. start = Timestamp("1999-12-31T12:00", tz=tz)
  563. target = date_range(start=start, periods=7, freq="12h")
  564. actual = index.get_indexer(target)
  565. expected = np.array([-1, -1, 0, 0, 1, 1, 2], dtype="intp")
  566. tm.assert_numpy_array_equal(actual, expected)
  567. start = Timestamp("2000-01-08T18:00", tz=tz)
  568. target = date_range(start=start, periods=7, freq="6h")
  569. actual = index.get_indexer(target)
  570. expected = np.array([7, 7, 8, 8, 8, 8, -1], dtype="intp")
  571. tm.assert_numpy_array_equal(actual, expected)
  572. def test_append(self, closed):
  573. index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed)
  574. index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed)
  575. result = index1.append(index2)
  576. expected = IntervalIndex.from_arrays([0, 1, 1, 2], [1, 2, 2, 3], closed=closed)
  577. tm.assert_index_equal(result, expected)
  578. result = index1.append([index1, index2])
  579. expected = IntervalIndex.from_arrays(
  580. [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed
  581. )
  582. tm.assert_index_equal(result, expected)
  583. for other_closed in {"left", "right", "both", "neither"} - {closed}:
  584. index_other_closed = IntervalIndex.from_arrays(
  585. [0, 1], [1, 2], closed=other_closed
  586. )
  587. result = index1.append(index_other_closed)
  588. expected = index1.astype(object).append(index_other_closed.astype(object))
  589. tm.assert_index_equal(result, expected)
  590. def test_is_non_overlapping_monotonic(self, closed):
  591. # Should be True in all cases
  592. tpls = [(0, 1), (2, 3), (4, 5), (6, 7)]
  593. idx = IntervalIndex.from_tuples(tpls, closed=closed)
  594. assert idx.is_non_overlapping_monotonic is True
  595. idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
  596. assert idx.is_non_overlapping_monotonic is True
  597. # Should be False in all cases (overlapping)
  598. tpls = [(0, 2), (1, 3), (4, 5), (6, 7)]
  599. idx = IntervalIndex.from_tuples(tpls, closed=closed)
  600. assert idx.is_non_overlapping_monotonic is False
  601. idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
  602. assert idx.is_non_overlapping_monotonic is False
  603. # Should be False in all cases (non-monotonic)
  604. tpls = [(0, 1), (2, 3), (6, 7), (4, 5)]
  605. idx = IntervalIndex.from_tuples(tpls, closed=closed)
  606. assert idx.is_non_overlapping_monotonic is False
  607. idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
  608. assert idx.is_non_overlapping_monotonic is False
  609. # Should be False for closed='both', otherwise True (GH16560)
  610. if closed == "both":
  611. idx = IntervalIndex.from_breaks(range(4), closed=closed)
  612. assert idx.is_non_overlapping_monotonic is False
  613. else:
  614. idx = IntervalIndex.from_breaks(range(4), closed=closed)
  615. assert idx.is_non_overlapping_monotonic is True
  616. @pytest.mark.parametrize(
  617. "start, shift, na_value",
  618. [
  619. (0, 1, np.nan),
  620. (Timestamp("2018-01-01"), Timedelta("1 day"), pd.NaT),
  621. (Timedelta("0 days"), Timedelta("1 day"), pd.NaT),
  622. ],
  623. )
  624. def test_is_overlapping(self, start, shift, na_value, closed):
  625. # GH 23309
  626. # see test_interval_tree.py for extensive tests; interface tests here
  627. # non-overlapping
  628. tuples = [(start + n * shift, start + (n + 1) * shift) for n in (0, 2, 4)]
  629. index = IntervalIndex.from_tuples(tuples, closed=closed)
  630. assert index.is_overlapping is False
  631. # non-overlapping with NA
  632. tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
  633. index = IntervalIndex.from_tuples(tuples, closed=closed)
  634. assert index.is_overlapping is False
  635. # overlapping
  636. tuples = [(start + n * shift, start + (n + 2) * shift) for n in range(3)]
  637. index = IntervalIndex.from_tuples(tuples, closed=closed)
  638. assert index.is_overlapping is True
  639. # overlapping with NA
  640. tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
  641. index = IntervalIndex.from_tuples(tuples, closed=closed)
  642. assert index.is_overlapping is True
  643. # common endpoints
  644. tuples = [(start + n * shift, start + (n + 1) * shift) for n in range(3)]
  645. index = IntervalIndex.from_tuples(tuples, closed=closed)
  646. result = index.is_overlapping
  647. expected = closed == "both"
  648. assert result is expected
  649. # common endpoints with NA
  650. tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
  651. index = IntervalIndex.from_tuples(tuples, closed=closed)
  652. result = index.is_overlapping
  653. assert result is expected
  654. # intervals with duplicate left values
  655. a = [10, 15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85]
  656. b = [15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]
  657. index = IntervalIndex.from_arrays(a, b, closed="right")
  658. result = index.is_overlapping
  659. assert result is False
  660. @pytest.mark.parametrize(
  661. "tuples",
  662. [
  663. list(zip(range(10), range(1, 11))),
  664. list(
  665. zip(
  666. date_range("20170101", periods=10),
  667. date_range("20170101", periods=10),
  668. )
  669. ),
  670. list(
  671. zip(
  672. timedelta_range("0 days", periods=10),
  673. timedelta_range("1 day", periods=10),
  674. )
  675. ),
  676. ],
  677. )
  678. def test_to_tuples(self, tuples):
  679. # GH 18756
  680. idx = IntervalIndex.from_tuples(tuples)
  681. result = idx.to_tuples()
  682. expected = Index(com.asarray_tuplesafe(tuples))
  683. tm.assert_index_equal(result, expected)
  684. @pytest.mark.parametrize(
  685. "tuples",
  686. [
  687. list(zip(range(10), range(1, 11))) + [np.nan],
  688. list(
  689. zip(
  690. date_range("20170101", periods=10),
  691. date_range("20170101", periods=10),
  692. )
  693. )
  694. + [np.nan],
  695. list(
  696. zip(
  697. timedelta_range("0 days", periods=10),
  698. timedelta_range("1 day", periods=10),
  699. )
  700. )
  701. + [np.nan],
  702. ],
  703. )
  704. @pytest.mark.parametrize("na_tuple", [True, False])
  705. def test_to_tuples_na(self, tuples, na_tuple):
  706. # GH 18756
  707. idx = IntervalIndex.from_tuples(tuples)
  708. result = idx.to_tuples(na_tuple=na_tuple)
  709. # check the non-NA portion
  710. expected_notna = Index(com.asarray_tuplesafe(tuples[:-1]))
  711. result_notna = result[:-1]
  712. tm.assert_index_equal(result_notna, expected_notna)
  713. # check the NA portion
  714. result_na = result[-1]
  715. if na_tuple:
  716. assert isinstance(result_na, tuple)
  717. assert len(result_na) == 2
  718. assert all(isna(x) for x in result_na)
  719. else:
  720. assert isna(result_na)
  721. def test_nbytes(self):
  722. # GH 19209
  723. left = np.arange(0, 4, dtype="i8")
  724. right = np.arange(1, 5, dtype="i8")
  725. result = IntervalIndex.from_arrays(left, right).nbytes
  726. expected = 64 # 4 * 8 * 2
  727. assert result == expected
  728. @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
  729. def test_set_closed(self, name, closed, new_closed):
  730. # GH 21670
  731. index = interval_range(0, 5, closed=closed, name=name)
  732. result = index.set_closed(new_closed)
  733. expected = interval_range(0, 5, closed=new_closed, name=name)
  734. tm.assert_index_equal(result, expected)
  735. @pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False])
  736. def test_set_closed_errors(self, bad_closed):
  737. # GH 21670
  738. index = interval_range(0, 5)
  739. msg = f"invalid option for 'closed': {bad_closed}"
  740. with pytest.raises(ValueError, match=msg):
  741. index.set_closed(bad_closed)
  742. def test_is_all_dates(self):
  743. # GH 23576
  744. year_2017 = Interval(
  745. Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")
  746. )
  747. year_2017_index = IntervalIndex([year_2017])
  748. assert not year_2017_index._is_all_dates
  749. def test_dir():
  750. # GH#27571 dir(interval_index) should not raise
  751. index = IntervalIndex.from_arrays([0, 1], [1, 2])
  752. result = dir(index)
  753. assert "str" not in result
  754. def test_searchsorted_different_argument_classes(listlike_box):
  755. # https://github.com/pandas-dev/pandas/issues/32762
  756. values = IntervalIndex([Interval(0, 1), Interval(1, 2)])
  757. result = values.searchsorted(listlike_box(values))
  758. expected = np.array([0, 1], dtype=result.dtype)
  759. tm.assert_numpy_array_equal(result, expected)
  760. result = values._data.searchsorted(listlike_box(values))
  761. tm.assert_numpy_array_equal(result, expected)
  762. @pytest.mark.parametrize(
  763. "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]
  764. )
  765. def test_searchsorted_invalid_argument(arg):
  766. values = IntervalIndex([Interval(0, 1), Interval(1, 2)])
  767. msg = "'<' not supported between instances of 'pandas._libs.interval.Interval' and "
  768. with pytest.raises(TypeError, match=msg):
  769. values.searchsorted(arg)