test_range.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. import numpy as np
  2. import pytest
  3. from pandas.core.dtypes.common import ensure_platform_int
  4. import pandas as pd
  5. from pandas import Float64Index, Index, Int64Index, RangeIndex
  6. import pandas._testing as tm
  7. from ..test_numeric import Numeric
  8. # aliases to make some tests easier to read
  9. RI = RangeIndex
  10. I64 = Int64Index
  11. F64 = Float64Index
  12. OI = Index
  13. class TestRangeIndex(Numeric):
  14. _holder = RangeIndex
  15. _compat_props = ["shape", "ndim", "size"]
  16. @pytest.fixture(
  17. params=[
  18. RangeIndex(start=0, stop=20, step=2, name="foo"),
  19. RangeIndex(start=18, stop=-1, step=-2, name="bar"),
  20. ],
  21. ids=["index_inc", "index_dec"],
  22. )
  23. def indices(self, request):
  24. return request.param
  25. def create_index(self):
  26. return RangeIndex(start=0, stop=20, step=2)
  27. def test_can_hold_identifiers(self):
  28. idx = self.create_index()
  29. key = idx[0]
  30. assert idx._can_hold_identifiers_and_holds_name(key) is False
  31. def test_too_many_names(self):
  32. index = self.create_index()
  33. with pytest.raises(ValueError, match="^Length"):
  34. index.names = ["roger", "harold"]
  35. @pytest.mark.parametrize(
  36. "index, start, stop, step",
  37. [
  38. (RangeIndex(5), 0, 5, 1),
  39. (RangeIndex(0, 5), 0, 5, 1),
  40. (RangeIndex(5, step=2), 0, 5, 2),
  41. (RangeIndex(1, 5, 2), 1, 5, 2),
  42. ],
  43. )
  44. def test_start_stop_step_attrs(self, index, start, stop, step):
  45. # GH 25710
  46. assert index.start == start
  47. assert index.stop == stop
  48. assert index.step == step
  49. @pytest.mark.parametrize("attr_name", ["_start", "_stop", "_step"])
  50. def test_deprecated_start_stop_step_attrs(self, attr_name):
  51. # GH 26581
  52. idx = self.create_index()
  53. with tm.assert_produces_warning(FutureWarning):
  54. getattr(idx, attr_name)
  55. def test_copy(self):
  56. i = RangeIndex(5, name="Foo")
  57. i_copy = i.copy()
  58. assert i_copy is not i
  59. assert i_copy.identical(i)
  60. assert i_copy._range == range(0, 5, 1)
  61. assert i_copy.name == "Foo"
  62. def test_repr(self):
  63. i = RangeIndex(5, name="Foo")
  64. result = repr(i)
  65. expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')"
  66. assert result == expected
  67. result = eval(result)
  68. tm.assert_index_equal(result, i, exact=True)
  69. i = RangeIndex(5, 0, -1)
  70. result = repr(i)
  71. expected = "RangeIndex(start=5, stop=0, step=-1)"
  72. assert result == expected
  73. result = eval(result)
  74. tm.assert_index_equal(result, i, exact=True)
  75. def test_insert(self):
  76. idx = RangeIndex(5, name="Foo")
  77. result = idx[1:4]
  78. # test 0th element
  79. tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]))
  80. # GH 18295 (test missing)
  81. expected = Float64Index([0, np.nan, 1, 2, 3, 4])
  82. for na in (np.nan, pd.NaT, None):
  83. result = RangeIndex(5).insert(1, na)
  84. tm.assert_index_equal(result, expected)
  85. def test_delete(self):
  86. idx = RangeIndex(5, name="Foo")
  87. expected = idx[1:].astype(int)
  88. result = idx.delete(0)
  89. tm.assert_index_equal(result, expected)
  90. assert result.name == expected.name
  91. expected = idx[:-1].astype(int)
  92. result = idx.delete(-1)
  93. tm.assert_index_equal(result, expected)
  94. assert result.name == expected.name
  95. with pytest.raises((IndexError, ValueError)):
  96. # either depending on numpy version
  97. result = idx.delete(len(idx))
  98. def test_view(self):
  99. i = RangeIndex(0, name="Foo")
  100. i_view = i.view()
  101. assert i_view.name == "Foo"
  102. i_view = i.view("i8")
  103. tm.assert_numpy_array_equal(i.values, i_view)
  104. i_view = i.view(RangeIndex)
  105. tm.assert_index_equal(i, i_view)
  106. def test_dtype(self):
  107. index = self.create_index()
  108. assert index.dtype == np.int64
  109. def test_cached_data(self):
  110. # GH 26565, GH26617
  111. # Calling RangeIndex._data caches an int64 array of the same length at
  112. # self._cached_data. This test checks whether _cached_data has been set
  113. idx = RangeIndex(0, 100, 10)
  114. assert idx._cached_data is None
  115. repr(idx)
  116. assert idx._cached_data is None
  117. str(idx)
  118. assert idx._cached_data is None
  119. idx.get_loc(20)
  120. assert idx._cached_data is None
  121. 90 in idx
  122. assert idx._cached_data is None
  123. 91 in idx
  124. assert idx._cached_data is None
  125. idx.all()
  126. assert idx._cached_data is None
  127. idx.any()
  128. assert idx._cached_data is None
  129. df = pd.DataFrame({"a": range(10)}, index=idx)
  130. df.loc[50]
  131. assert idx._cached_data is None
  132. with pytest.raises(KeyError, match="51"):
  133. df.loc[51]
  134. assert idx._cached_data is None
  135. df.loc[10:50]
  136. assert idx._cached_data is None
  137. df.iloc[5:10]
  138. assert idx._cached_data is None
  139. # actually calling idx._data
  140. assert isinstance(idx._data, np.ndarray)
  141. assert isinstance(idx._cached_data, np.ndarray)
  142. def test_is_monotonic(self):
  143. index = RangeIndex(0, 20, 2)
  144. assert index.is_monotonic is True
  145. assert index.is_monotonic_increasing is True
  146. assert index.is_monotonic_decreasing is False
  147. assert index._is_strictly_monotonic_increasing is True
  148. assert index._is_strictly_monotonic_decreasing is False
  149. index = RangeIndex(4, 0, -1)
  150. assert index.is_monotonic is False
  151. assert index._is_strictly_monotonic_increasing is False
  152. assert index.is_monotonic_decreasing is True
  153. assert index._is_strictly_monotonic_decreasing is True
  154. index = RangeIndex(1, 2)
  155. assert index.is_monotonic is True
  156. assert index.is_monotonic_increasing is True
  157. assert index.is_monotonic_decreasing is True
  158. assert index._is_strictly_monotonic_increasing is True
  159. assert index._is_strictly_monotonic_decreasing is True
  160. index = RangeIndex(2, 1)
  161. assert index.is_monotonic is True
  162. assert index.is_monotonic_increasing is True
  163. assert index.is_monotonic_decreasing is True
  164. assert index._is_strictly_monotonic_increasing is True
  165. assert index._is_strictly_monotonic_decreasing is True
  166. index = RangeIndex(1, 1)
  167. assert index.is_monotonic is True
  168. assert index.is_monotonic_increasing is True
  169. assert index.is_monotonic_decreasing is True
  170. assert index._is_strictly_monotonic_increasing is True
  171. assert index._is_strictly_monotonic_decreasing is True
  172. def test_equals_range(self):
  173. equiv_pairs = [
  174. (RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)),
  175. (RangeIndex(0), RangeIndex(1, -1, 3)),
  176. (RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)),
  177. (RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)),
  178. ]
  179. for left, right in equiv_pairs:
  180. assert left.equals(right)
  181. assert right.equals(left)
  182. def test_logical_compat(self):
  183. idx = self.create_index()
  184. assert idx.all() == idx.values.all()
  185. assert idx.any() == idx.values.any()
  186. def test_identical(self):
  187. index = self.create_index()
  188. i = Index(index.copy())
  189. assert i.identical(index)
  190. # we don't allow object dtype for RangeIndex
  191. if isinstance(index, RangeIndex):
  192. return
  193. same_values_different_type = Index(i, dtype=object)
  194. assert not i.identical(same_values_different_type)
  195. i = index.copy(dtype=object)
  196. i = i.rename("foo")
  197. same_values = Index(i, dtype=object)
  198. assert same_values.identical(index.copy(dtype=object))
  199. assert not i.identical(index)
  200. assert Index(same_values, name="foo", dtype=object).identical(i)
  201. assert not index.copy(dtype=object).identical(index.copy(dtype="int64"))
  202. def test_get_indexer(self):
  203. index = self.create_index()
  204. target = RangeIndex(10)
  205. indexer = index.get_indexer(target)
  206. expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)
  207. tm.assert_numpy_array_equal(indexer, expected)
  208. def test_get_indexer_pad(self):
  209. index = self.create_index()
  210. target = RangeIndex(10)
  211. indexer = index.get_indexer(target, method="pad")
  212. expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)
  213. tm.assert_numpy_array_equal(indexer, expected)
  214. def test_get_indexer_backfill(self):
  215. index = self.create_index()
  216. target = RangeIndex(10)
  217. indexer = index.get_indexer(target, method="backfill")
  218. expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
  219. tm.assert_numpy_array_equal(indexer, expected)
  220. def test_get_indexer_limit(self):
  221. # GH 28631
  222. idx = RangeIndex(4)
  223. target = RangeIndex(6)
  224. result = idx.get_indexer(target, method="pad", limit=1)
  225. expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp)
  226. tm.assert_numpy_array_equal(result, expected)
  227. @pytest.mark.parametrize("stop", [0, -1, -2])
  228. def test_get_indexer_decreasing(self, stop):
  229. # GH 28678
  230. index = RangeIndex(7, stop, -3)
  231. result = index.get_indexer(range(9))
  232. expected = np.array([-1, 2, -1, -1, 1, -1, -1, 0, -1], dtype=np.intp)
  233. tm.assert_numpy_array_equal(result, expected)
  234. def test_join_outer(self):
  235. # join with Int64Index
  236. index = self.create_index()
  237. other = Int64Index(np.arange(25, 14, -1))
  238. res, lidx, ridx = index.join(other, how="outer", return_indexers=True)
  239. noidx_res = index.join(other, how="outer")
  240. tm.assert_index_equal(res, noidx_res)
  241. eres = Int64Index(
  242. [0, 2, 4, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
  243. )
  244. elidx = np.array(
  245. [0, 1, 2, 3, 4, 5, 6, 7, -1, 8, -1, 9, -1, -1, -1, -1, -1, -1, -1],
  246. dtype=np.intp,
  247. )
  248. eridx = np.array(
  249. [-1, -1, -1, -1, -1, -1, -1, -1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
  250. dtype=np.intp,
  251. )
  252. assert isinstance(res, Int64Index)
  253. assert not isinstance(res, RangeIndex)
  254. tm.assert_index_equal(res, eres)
  255. tm.assert_numpy_array_equal(lidx, elidx)
  256. tm.assert_numpy_array_equal(ridx, eridx)
  257. # join with RangeIndex
  258. other = RangeIndex(25, 14, -1)
  259. res, lidx, ridx = index.join(other, how="outer", return_indexers=True)
  260. noidx_res = index.join(other, how="outer")
  261. tm.assert_index_equal(res, noidx_res)
  262. assert isinstance(res, Int64Index)
  263. assert not isinstance(res, RangeIndex)
  264. tm.assert_index_equal(res, eres)
  265. tm.assert_numpy_array_equal(lidx, elidx)
  266. tm.assert_numpy_array_equal(ridx, eridx)
  267. def test_join_inner(self):
  268. # Join with non-RangeIndex
  269. index = self.create_index()
  270. other = Int64Index(np.arange(25, 14, -1))
  271. res, lidx, ridx = index.join(other, how="inner", return_indexers=True)
  272. # no guarantee of sortedness, so sort for comparison purposes
  273. ind = res.argsort()
  274. res = res.take(ind)
  275. lidx = lidx.take(ind)
  276. ridx = ridx.take(ind)
  277. eres = Int64Index([16, 18])
  278. elidx = np.array([8, 9], dtype=np.intp)
  279. eridx = np.array([9, 7], dtype=np.intp)
  280. assert isinstance(res, Int64Index)
  281. tm.assert_index_equal(res, eres)
  282. tm.assert_numpy_array_equal(lidx, elidx)
  283. tm.assert_numpy_array_equal(ridx, eridx)
  284. # Join two RangeIndex
  285. other = RangeIndex(25, 14, -1)
  286. res, lidx, ridx = index.join(other, how="inner", return_indexers=True)
  287. assert isinstance(res, RangeIndex)
  288. tm.assert_index_equal(res, eres)
  289. tm.assert_numpy_array_equal(lidx, elidx)
  290. tm.assert_numpy_array_equal(ridx, eridx)
  291. def test_join_left(self):
  292. # Join with Int64Index
  293. index = self.create_index()
  294. other = Int64Index(np.arange(25, 14, -1))
  295. res, lidx, ridx = index.join(other, how="left", return_indexers=True)
  296. eres = index
  297. eridx = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 9, 7], dtype=np.intp)
  298. assert isinstance(res, RangeIndex)
  299. tm.assert_index_equal(res, eres)
  300. assert lidx is None
  301. tm.assert_numpy_array_equal(ridx, eridx)
  302. # Join withRangeIndex
  303. other = Int64Index(np.arange(25, 14, -1))
  304. res, lidx, ridx = index.join(other, how="left", return_indexers=True)
  305. assert isinstance(res, RangeIndex)
  306. tm.assert_index_equal(res, eres)
  307. assert lidx is None
  308. tm.assert_numpy_array_equal(ridx, eridx)
  309. def test_join_right(self):
  310. # Join with Int64Index
  311. index = self.create_index()
  312. other = Int64Index(np.arange(25, 14, -1))
  313. res, lidx, ridx = index.join(other, how="right", return_indexers=True)
  314. eres = other
  315. elidx = np.array([-1, -1, -1, -1, -1, -1, -1, 9, -1, 8, -1], dtype=np.intp)
  316. assert isinstance(other, Int64Index)
  317. tm.assert_index_equal(res, eres)
  318. tm.assert_numpy_array_equal(lidx, elidx)
  319. assert ridx is None
  320. # Join withRangeIndex
  321. other = RangeIndex(25, 14, -1)
  322. res, lidx, ridx = index.join(other, how="right", return_indexers=True)
  323. eres = other
  324. assert isinstance(other, RangeIndex)
  325. tm.assert_index_equal(res, eres)
  326. tm.assert_numpy_array_equal(lidx, elidx)
  327. assert ridx is None
  328. def test_join_non_int_index(self):
  329. index = self.create_index()
  330. other = Index([3, 6, 7, 8, 10], dtype=object)
  331. outer = index.join(other, how="outer")
  332. outer2 = other.join(index, how="outer")
  333. expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18])
  334. tm.assert_index_equal(outer, outer2)
  335. tm.assert_index_equal(outer, expected)
  336. inner = index.join(other, how="inner")
  337. inner2 = other.join(index, how="inner")
  338. expected = Index([6, 8, 10])
  339. tm.assert_index_equal(inner, inner2)
  340. tm.assert_index_equal(inner, expected)
  341. left = index.join(other, how="left")
  342. tm.assert_index_equal(left, index.astype(object))
  343. left2 = other.join(index, how="left")
  344. tm.assert_index_equal(left2, other)
  345. right = index.join(other, how="right")
  346. tm.assert_index_equal(right, other)
  347. right2 = other.join(index, how="right")
  348. tm.assert_index_equal(right2, index.astype(object))
  349. def test_join_non_unique(self):
  350. index = self.create_index()
  351. other = Index([4, 4, 3, 3])
  352. res, lidx, ridx = index.join(other, return_indexers=True)
  353. eres = Int64Index([0, 2, 4, 4, 6, 8, 10, 12, 14, 16, 18])
  354. elidx = np.array([0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.intp)
  355. eridx = np.array([-1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1], dtype=np.intp)
  356. tm.assert_index_equal(res, eres)
  357. tm.assert_numpy_array_equal(lidx, elidx)
  358. tm.assert_numpy_array_equal(ridx, eridx)
  359. def test_join_self(self, join_type):
  360. index = self.create_index()
  361. joined = index.join(index, how=join_type)
  362. assert index is joined
  363. def test_nbytes(self):
  364. # memory savings vs int index
  365. i = RangeIndex(0, 1000)
  366. assert i.nbytes < i._int64index.nbytes / 10
  367. # constant memory usage
  368. i2 = RangeIndex(0, 10)
  369. assert i.nbytes == i2.nbytes
  370. def test_cant_or_shouldnt_cast(self):
  371. # can't
  372. with pytest.raises(TypeError):
  373. RangeIndex("foo", "bar", "baz")
  374. # shouldn't
  375. with pytest.raises(TypeError):
  376. RangeIndex("0", "1", "2")
  377. def test_view_index(self):
  378. index = self.create_index()
  379. index.view(Index)
  380. def test_prevent_casting(self):
  381. index = self.create_index()
  382. result = index.astype("O")
  383. assert result.dtype == np.object_
  384. def test_take_preserve_name(self):
  385. index = RangeIndex(1, 5, name="foo")
  386. taken = index.take([3, 0, 1])
  387. assert index.name == taken.name
  388. def test_take_fill_value(self):
  389. # GH 12631
  390. idx = pd.RangeIndex(1, 4, name="xxx")
  391. result = idx.take(np.array([1, 0, -1]))
  392. expected = pd.Int64Index([2, 1, 3], name="xxx")
  393. tm.assert_index_equal(result, expected)
  394. # fill_value
  395. msg = "Unable to fill values because RangeIndex cannot contain NA"
  396. with pytest.raises(ValueError, match=msg):
  397. idx.take(np.array([1, 0, -1]), fill_value=True)
  398. # allow_fill=False
  399. result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
  400. expected = pd.Int64Index([2, 1, 3], name="xxx")
  401. tm.assert_index_equal(result, expected)
  402. msg = "Unable to fill values because RangeIndex cannot contain NA"
  403. with pytest.raises(ValueError, match=msg):
  404. idx.take(np.array([1, 0, -2]), fill_value=True)
  405. with pytest.raises(ValueError, match=msg):
  406. idx.take(np.array([1, 0, -5]), fill_value=True)
  407. with pytest.raises(IndexError):
  408. idx.take(np.array([1, -5]))
  409. def test_print_unicode_columns(self):
  410. df = pd.DataFrame({"\u05d0": [1, 2, 3], "\u05d1": [4, 5, 6], "c": [7, 8, 9]})
  411. repr(df.columns) # should not raise UnicodeDecodeError
  412. def test_repr_roundtrip(self):
  413. index = self.create_index()
  414. tm.assert_index_equal(eval(repr(index)), index)
  415. def test_slice_keep_name(self):
  416. idx = RangeIndex(1, 2, name="asdf")
  417. assert idx.name == idx[1:].name
  418. def test_explicit_conversions(self):
  419. # GH 8608
  420. # add/sub are overridden explicitly for Float/Int Index
  421. idx = RangeIndex(5)
  422. # float conversions
  423. arr = np.arange(5, dtype="int64") * 3.2
  424. expected = Float64Index(arr)
  425. fidx = idx * 3.2
  426. tm.assert_index_equal(fidx, expected)
  427. fidx = 3.2 * idx
  428. tm.assert_index_equal(fidx, expected)
  429. # interops with numpy arrays
  430. expected = Float64Index(arr)
  431. a = np.zeros(5, dtype="float64")
  432. result = fidx - a
  433. tm.assert_index_equal(result, expected)
  434. expected = Float64Index(-arr)
  435. a = np.zeros(5, dtype="float64")
  436. result = a - fidx
  437. tm.assert_index_equal(result, expected)
  438. def test_has_duplicates(self, indices):
  439. assert indices.is_unique
  440. assert not indices.has_duplicates
  441. def test_extended_gcd(self):
  442. index = self.create_index()
  443. result = index._extended_gcd(6, 10)
  444. assert result[0] == result[1] * 6 + result[2] * 10
  445. assert 2 == result[0]
  446. result = index._extended_gcd(10, 6)
  447. assert 2 == result[1] * 10 + result[2] * 6
  448. assert 2 == result[0]
  449. def test_min_fitting_element(self):
  450. result = RangeIndex(0, 20, 2)._min_fitting_element(1)
  451. assert 2 == result
  452. result = RangeIndex(1, 6)._min_fitting_element(1)
  453. assert 1 == result
  454. result = RangeIndex(18, -2, -2)._min_fitting_element(1)
  455. assert 2 == result
  456. result = RangeIndex(5, 0, -1)._min_fitting_element(1)
  457. assert 1 == result
  458. big_num = 500000000000000000000000
  459. result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num)
  460. assert big_num == result
  461. def test_max_fitting_element(self):
  462. result = RangeIndex(0, 20, 2)._max_fitting_element(17)
  463. assert 16 == result
  464. result = RangeIndex(1, 6)._max_fitting_element(4)
  465. assert 4 == result
  466. result = RangeIndex(18, -2, -2)._max_fitting_element(17)
  467. assert 16 == result
  468. result = RangeIndex(5, 0, -1)._max_fitting_element(4)
  469. assert 4 == result
  470. big_num = 500000000000000000000000
  471. result = RangeIndex(5, big_num * 2, 1)._max_fitting_element(big_num)
  472. assert big_num == result
  473. def test_pickle_compat_construction(self):
  474. # RangeIndex() is a valid constructor
  475. pass
  476. def test_slice_specialised(self):
  477. index = self.create_index()
  478. index.name = "foo"
  479. # scalar indexing
  480. res = index[1]
  481. expected = 2
  482. assert res == expected
  483. res = index[-1]
  484. expected = 18
  485. assert res == expected
  486. # slicing
  487. # slice value completion
  488. index_slice = index[:]
  489. expected = index
  490. tm.assert_index_equal(index_slice, expected)
  491. # positive slice values
  492. index_slice = index[7:10:2]
  493. expected = Index(np.array([14, 18]), name="foo")
  494. tm.assert_index_equal(index_slice, expected)
  495. # negative slice values
  496. index_slice = index[-1:-5:-2]
  497. expected = Index(np.array([18, 14]), name="foo")
  498. tm.assert_index_equal(index_slice, expected)
  499. # stop overshoot
  500. index_slice = index[2:100:4]
  501. expected = Index(np.array([4, 12]), name="foo")
  502. tm.assert_index_equal(index_slice, expected)
  503. # reverse
  504. index_slice = index[::-1]
  505. expected = Index(index.values[::-1], name="foo")
  506. tm.assert_index_equal(index_slice, expected)
  507. index_slice = index[-8::-1]
  508. expected = Index(np.array([4, 2, 0]), name="foo")
  509. tm.assert_index_equal(index_slice, expected)
  510. index_slice = index[-40::-1]
  511. expected = Index(np.array([], dtype=np.int64), name="foo")
  512. tm.assert_index_equal(index_slice, expected)
  513. index_slice = index[40::-1]
  514. expected = Index(index.values[40::-1], name="foo")
  515. tm.assert_index_equal(index_slice, expected)
  516. index_slice = index[10::-1]
  517. expected = Index(index.values[::-1], name="foo")
  518. tm.assert_index_equal(index_slice, expected)
  519. @pytest.mark.parametrize("step", set(range(-5, 6)) - {0})
  520. def test_len_specialised(self, step):
  521. # make sure that our len is the same as np.arange calc
  522. start, stop = (0, 5) if step > 0 else (5, 0)
  523. arr = np.arange(start, stop, step)
  524. index = RangeIndex(start, stop, step)
  525. assert len(index) == len(arr)
  526. index = RangeIndex(stop, start, step)
  527. assert len(index) == 0
  528. @pytest.fixture(
  529. params=[
  530. ([RI(1, 12, 5)], RI(1, 12, 5)),
  531. ([RI(0, 6, 4)], RI(0, 6, 4)),
  532. ([RI(1, 3), RI(3, 7)], RI(1, 7)),
  533. ([RI(1, 5, 2), RI(5, 6)], RI(1, 6, 2)),
  534. ([RI(1, 3, 2), RI(4, 7, 3)], RI(1, 7, 3)),
  535. ([RI(-4, 3, 2), RI(4, 7, 2)], RI(-4, 7, 2)),
  536. ([RI(-4, -8), RI(-8, -12)], RI(0, 0)),
  537. ([RI(-4, -8), RI(3, -4)], RI(0, 0)),
  538. ([RI(-4, -8), RI(3, 5)], RI(3, 5)),
  539. ([RI(-4, -2), RI(3, 5)], I64([-4, -3, 3, 4])),
  540. ([RI(-2), RI(3, 5)], RI(3, 5)),
  541. ([RI(2), RI(2)], I64([0, 1, 0, 1])),
  542. ([RI(2), RI(2, 5), RI(5, 8, 4)], RI(0, 6)),
  543. ([RI(2), RI(3, 5), RI(5, 8, 4)], I64([0, 1, 3, 4, 5])),
  544. ([RI(-2, 2), RI(2, 5), RI(5, 8, 4)], RI(-2, 6)),
  545. ([RI(3), I64([-1, 3, 15])], I64([0, 1, 2, -1, 3, 15])),
  546. ([RI(3), F64([-1, 3.1, 15.0])], F64([0, 1, 2, -1, 3.1, 15.0])),
  547. ([RI(3), OI(["a", None, 14])], OI([0, 1, 2, "a", None, 14])),
  548. ([RI(3, 1), OI(["a", None, 14])], OI(["a", None, 14])),
  549. ]
  550. )
  551. def appends(self, request):
  552. """Inputs and expected outputs for RangeIndex.append test"""
  553. return request.param
  554. def test_append(self, appends):
  555. # GH16212
  556. indices, expected = appends
  557. result = indices[0].append(indices[1:])
  558. tm.assert_index_equal(result, expected, exact=True)
  559. if len(indices) == 2:
  560. # Append single item rather than list
  561. result2 = indices[0].append(indices[1])
  562. tm.assert_index_equal(result2, expected, exact=True)
  563. def test_engineless_lookup(self):
  564. # GH 16685
  565. # Standard lookup on RangeIndex should not require the engine to be
  566. # created
  567. idx = RangeIndex(2, 10, 3)
  568. assert idx.get_loc(5) == 1
  569. tm.assert_numpy_array_equal(
  570. idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2]))
  571. )
  572. with pytest.raises(KeyError, match="3"):
  573. idx.get_loc(3)
  574. assert "_engine" not in idx._cache
  575. # The engine is still required for lookup of a different dtype scalar:
  576. with pytest.raises(KeyError, match="'a'"):
  577. assert idx.get_loc("a") == -1
  578. assert "_engine" in idx._cache