test_common.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. """
  2. Collection of tests asserting things that should be true for
  3. any index subclass except for MultiIndex. Makes use of the `index_flat`
  4. fixture defined in pandas/conftest.py.
  5. """
  6. from copy import (
  7. copy,
  8. deepcopy,
  9. )
  10. import re
  11. import numpy as np
  12. import pytest
  13. from pandas.compat import IS64
  14. from pandas.core.dtypes.common import (
  15. is_integer_dtype,
  16. is_numeric_dtype,
  17. )
  18. import pandas as pd
  19. from pandas import (
  20. CategoricalIndex,
  21. MultiIndex,
  22. PeriodIndex,
  23. RangeIndex,
  24. )
  25. import pandas._testing as tm
  26. class TestCommon:
  27. @pytest.mark.parametrize("name", [None, "new_name"])
  28. def test_to_frame(self, name, index_flat):
  29. # see GH#15230, GH#22580
  30. idx = index_flat
  31. if name:
  32. idx_name = name
  33. else:
  34. idx_name = idx.name or 0
  35. df = idx.to_frame(name=idx_name)
  36. assert df.index is idx
  37. assert len(df.columns) == 1
  38. assert df.columns[0] == idx_name
  39. assert df[idx_name].values is not idx.values
  40. df = idx.to_frame(index=False, name=idx_name)
  41. assert df.index is not idx
  42. def test_droplevel(self, index_flat):
  43. # GH 21115
  44. # MultiIndex is tested separately in test_multi.py
  45. index = index_flat
  46. assert index.droplevel([]).equals(index)
  47. for level in [index.name, [index.name]]:
  48. if isinstance(index.name, tuple) and level is index.name:
  49. # GH 21121 : droplevel with tuple name
  50. continue
  51. msg = (
  52. "Cannot remove 1 levels from an index with 1 levels: at least one "
  53. "level must be left."
  54. )
  55. with pytest.raises(ValueError, match=msg):
  56. index.droplevel(level)
  57. for level in "wrong", ["wrong"]:
  58. with pytest.raises(
  59. KeyError,
  60. match=r"'Requested level \(wrong\) does not match index name \(None\)'",
  61. ):
  62. index.droplevel(level)
  63. def test_constructor_non_hashable_name(self, index_flat):
  64. # GH 20527
  65. index = index_flat
  66. message = "Index.name must be a hashable type"
  67. renamed = [["1"]]
  68. # With .rename()
  69. with pytest.raises(TypeError, match=message):
  70. index.rename(name=renamed)
  71. # With .set_names()
  72. with pytest.raises(TypeError, match=message):
  73. index.set_names(names=renamed)
  74. def test_constructor_unwraps_index(self, index_flat):
  75. a = index_flat
  76. # Passing dtype is necessary for Index([True, False], dtype=object)
  77. # case.
  78. b = type(a)(a, dtype=a.dtype)
  79. tm.assert_equal(a._data, b._data)
  80. def test_to_flat_index(self, index_flat):
  81. # 22866
  82. index = index_flat
  83. result = index.to_flat_index()
  84. tm.assert_index_equal(result, index)
  85. def test_set_name_methods(self, index_flat):
  86. # MultiIndex tested separately
  87. index = index_flat
  88. new_name = "This is the new name for this index"
  89. original_name = index.name
  90. new_ind = index.set_names([new_name])
  91. assert new_ind.name == new_name
  92. assert index.name == original_name
  93. res = index.rename(new_name, inplace=True)
  94. # should return None
  95. assert res is None
  96. assert index.name == new_name
  97. assert index.names == [new_name]
  98. # FIXME: dont leave commented-out
  99. # with pytest.raises(TypeError, match="list-like"):
  100. # # should still fail even if it would be the right length
  101. # ind.set_names("a")
  102. with pytest.raises(ValueError, match="Level must be None"):
  103. index.set_names("a", level=0)
  104. # rename in place just leaves tuples and other containers alone
  105. name = ("A", "B")
  106. index.rename(name, inplace=True)
  107. assert index.name == name
  108. assert index.names == [name]
  109. def test_copy_and_deepcopy(self, index_flat):
  110. index = index_flat
  111. for func in (copy, deepcopy):
  112. idx_copy = func(index)
  113. assert idx_copy is not index
  114. assert idx_copy.equals(index)
  115. new_copy = index.copy(deep=True, name="banana")
  116. assert new_copy.name == "banana"
  117. def test_copy_name(self, index_flat):
  118. # GH#12309: Check that the "name" argument
  119. # passed at initialization is honored.
  120. index = index_flat
  121. first = type(index)(index, copy=True, name="mario")
  122. second = type(first)(first, copy=False)
  123. # Even though "copy=False", we want a new object.
  124. assert first is not second
  125. tm.assert_index_equal(first, second)
  126. # Not using tm.assert_index_equal() since names differ.
  127. assert index.equals(first)
  128. assert first.name == "mario"
  129. assert second.name == "mario"
  130. # TODO: belongs in series arithmetic tests?
  131. s1 = pd.Series(2, index=first)
  132. s2 = pd.Series(3, index=second[:-1])
  133. # See GH#13365
  134. s3 = s1 * s2
  135. assert s3.index.name == "mario"
  136. def test_copy_name2(self, index_flat):
  137. # GH#35592
  138. index = index_flat
  139. assert index.copy(name="mario").name == "mario"
  140. with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
  141. index.copy(name=["mario", "luigi"])
  142. msg = f"{type(index).__name__}.name must be a hashable type"
  143. with pytest.raises(TypeError, match=msg):
  144. index.copy(name=[["mario"]])
  145. def test_unique_level(self, index_flat):
  146. # don't test a MultiIndex here (as its tested separated)
  147. index = index_flat
  148. # GH 17896
  149. expected = index.drop_duplicates()
  150. for level in [0, index.name, None]:
  151. result = index.unique(level=level)
  152. tm.assert_index_equal(result, expected)
  153. msg = "Too many levels: Index has only 1 level, not 4"
  154. with pytest.raises(IndexError, match=msg):
  155. index.unique(level=3)
  156. msg = (
  157. rf"Requested level \(wrong\) does not match index name "
  158. rf"\({re.escape(index.name.__repr__())}\)"
  159. )
  160. with pytest.raises(KeyError, match=msg):
  161. index.unique(level="wrong")
  162. def test_unique(self, index_flat):
  163. # MultiIndex tested separately
  164. index = index_flat
  165. if not len(index):
  166. pytest.skip("Skip check for empty Index and MultiIndex")
  167. idx = index[[0] * 5]
  168. idx_unique = index[[0]]
  169. # We test against `idx_unique`, so first we make sure it's unique
  170. # and doesn't contain nans.
  171. assert idx_unique.is_unique is True
  172. try:
  173. assert idx_unique.hasnans is False
  174. except NotImplementedError:
  175. pass
  176. result = idx.unique()
  177. tm.assert_index_equal(result, idx_unique)
  178. # nans:
  179. if not index._can_hold_na:
  180. pytest.skip("Skip na-check if index cannot hold na")
  181. vals = index._values[[0] * 5]
  182. vals[0] = np.nan
  183. vals_unique = vals[:2]
  184. idx_nan = index._shallow_copy(vals)
  185. idx_unique_nan = index._shallow_copy(vals_unique)
  186. assert idx_unique_nan.is_unique is True
  187. assert idx_nan.dtype == index.dtype
  188. assert idx_unique_nan.dtype == index.dtype
  189. expected = idx_unique_nan
  190. for pos, i in enumerate([idx_nan, idx_unique_nan]):
  191. result = i.unique()
  192. tm.assert_index_equal(result, expected)
  193. def test_searchsorted_monotonic(self, index_flat, request):
  194. # GH17271
  195. index = index_flat
  196. # not implemented for tuple searches in MultiIndex
  197. # or Intervals searches in IntervalIndex
  198. if isinstance(index, pd.IntervalIndex):
  199. mark = pytest.mark.xfail(
  200. reason="IntervalIndex.searchsorted does not support Interval arg",
  201. raises=NotImplementedError,
  202. )
  203. request.node.add_marker(mark)
  204. # nothing to test if the index is empty
  205. if index.empty:
  206. pytest.skip("Skip check for empty Index")
  207. value = index[0]
  208. # determine the expected results (handle dupes for 'right')
  209. expected_left, expected_right = 0, (index == value).argmin()
  210. if expected_right == 0:
  211. # all values are the same, expected_right should be length
  212. expected_right = len(index)
  213. # test _searchsorted_monotonic in all cases
  214. # test searchsorted only for increasing
  215. if index.is_monotonic_increasing:
  216. ssm_left = index._searchsorted_monotonic(value, side="left")
  217. assert expected_left == ssm_left
  218. ssm_right = index._searchsorted_monotonic(value, side="right")
  219. assert expected_right == ssm_right
  220. ss_left = index.searchsorted(value, side="left")
  221. assert expected_left == ss_left
  222. ss_right = index.searchsorted(value, side="right")
  223. assert expected_right == ss_right
  224. elif index.is_monotonic_decreasing:
  225. ssm_left = index._searchsorted_monotonic(value, side="left")
  226. assert expected_left == ssm_left
  227. ssm_right = index._searchsorted_monotonic(value, side="right")
  228. assert expected_right == ssm_right
  229. else:
  230. # non-monotonic should raise.
  231. msg = "index must be monotonic increasing or decreasing"
  232. with pytest.raises(ValueError, match=msg):
  233. index._searchsorted_monotonic(value, side="left")
  234. def test_drop_duplicates(self, index_flat, keep):
  235. # MultiIndex is tested separately
  236. index = index_flat
  237. if isinstance(index, RangeIndex):
  238. pytest.skip(
  239. "RangeIndex is tested in test_drop_duplicates_no_duplicates "
  240. "as it cannot hold duplicates"
  241. )
  242. if len(index) == 0:
  243. pytest.skip(
  244. "empty index is tested in test_drop_duplicates_no_duplicates "
  245. "as it cannot hold duplicates"
  246. )
  247. # make unique index
  248. holder = type(index)
  249. unique_values = list(set(index))
  250. dtype = index.dtype if is_numeric_dtype(index) else None
  251. unique_idx = holder(unique_values, dtype=dtype)
  252. # make duplicated index
  253. n = len(unique_idx)
  254. duplicated_selection = np.random.choice(n, int(n * 1.5))
  255. idx = holder(unique_idx.values[duplicated_selection])
  256. # Series.duplicated is tested separately
  257. expected_duplicated = (
  258. pd.Series(duplicated_selection).duplicated(keep=keep).values
  259. )
  260. tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected_duplicated)
  261. # Series.drop_duplicates is tested separately
  262. expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
  263. tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
  264. def test_drop_duplicates_no_duplicates(self, index_flat):
  265. # MultiIndex is tested separately
  266. index = index_flat
  267. # make unique index
  268. if isinstance(index, RangeIndex):
  269. # RangeIndex cannot have duplicates
  270. unique_idx = index
  271. else:
  272. holder = type(index)
  273. unique_values = list(set(index))
  274. dtype = index.dtype if is_numeric_dtype(index) else None
  275. unique_idx = holder(unique_values, dtype=dtype)
  276. # check on unique index
  277. expected_duplicated = np.array([False] * len(unique_idx), dtype="bool")
  278. tm.assert_numpy_array_equal(unique_idx.duplicated(), expected_duplicated)
  279. result_dropped = unique_idx.drop_duplicates()
  280. tm.assert_index_equal(result_dropped, unique_idx)
  281. # validate shallow copy
  282. assert result_dropped is not unique_idx
  283. def test_drop_duplicates_inplace(self, index):
  284. msg = r"drop_duplicates\(\) got an unexpected keyword argument"
  285. with pytest.raises(TypeError, match=msg):
  286. index.drop_duplicates(inplace=True)
  287. def test_has_duplicates(self, index_flat):
  288. # MultiIndex tested separately in:
  289. # tests/indexes/multi/test_unique_and_duplicates.
  290. index = index_flat
  291. holder = type(index)
  292. if not len(index) or isinstance(index, RangeIndex):
  293. # MultiIndex tested separately in:
  294. # tests/indexes/multi/test_unique_and_duplicates.
  295. # RangeIndex is unique by definition.
  296. pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex")
  297. idx = holder([index[0]] * 5)
  298. assert idx.is_unique is False
  299. assert idx.has_duplicates is True
  300. @pytest.mark.parametrize(
  301. "dtype",
  302. ["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"],
  303. )
  304. def test_astype_preserves_name(self, index, dtype):
  305. # https://github.com/pandas-dev/pandas/issues/32013
  306. if isinstance(index, MultiIndex):
  307. index.names = ["idx" + str(i) for i in range(index.nlevels)]
  308. else:
  309. index.name = "idx"
  310. warn = None
  311. if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
  312. # imaginary components discarded
  313. warn = np.ComplexWarning
  314. is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category"
  315. try:
  316. # Some of these conversions cannot succeed so we use a try / except
  317. with tm.assert_produces_warning(
  318. warn,
  319. raise_on_extra_warnings=is_pyarrow_str,
  320. check_stacklevel=False,
  321. ):
  322. result = index.astype(dtype)
  323. except (ValueError, TypeError, NotImplementedError, SystemError):
  324. return
  325. if isinstance(index, MultiIndex):
  326. assert result.names == index.names
  327. else:
  328. assert result.name == index.name
  329. def test_hasnans_isnans(self, index_flat):
  330. # GH#11343, added tests for hasnans / isnans
  331. index = index_flat
  332. # cases in indices doesn't include NaN
  333. idx = index.copy(deep=True)
  334. expected = np.array([False] * len(idx), dtype=bool)
  335. tm.assert_numpy_array_equal(idx._isnan, expected)
  336. assert idx.hasnans is False
  337. idx = index.copy(deep=True)
  338. values = idx._values
  339. if len(index) == 0:
  340. return
  341. elif is_integer_dtype(index.dtype):
  342. return
  343. elif index.dtype == bool:
  344. # values[1] = np.nan below casts to True!
  345. return
  346. values[1] = np.nan
  347. idx = type(index)(values)
  348. expected = np.array([False] * len(idx), dtype=bool)
  349. expected[1] = True
  350. tm.assert_numpy_array_equal(idx._isnan, expected)
  351. assert idx.hasnans is True
  352. @pytest.mark.parametrize("na_position", [None, "middle"])
  353. def test_sort_values_invalid_na_position(index_with_missing, na_position):
  354. with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
  355. index_with_missing.sort_values(na_position=na_position)
  356. @pytest.mark.parametrize("na_position", ["first", "last"])
  357. def test_sort_values_with_missing(index_with_missing, na_position, request):
  358. # GH 35584. Test that sort_values works with missing values,
  359. # sort non-missing and place missing according to na_position
  360. if isinstance(index_with_missing, CategoricalIndex):
  361. request.node.add_marker(
  362. pytest.mark.xfail(
  363. reason="missing value sorting order not well-defined", strict=False
  364. )
  365. )
  366. missing_count = np.sum(index_with_missing.isna())
  367. not_na_vals = index_with_missing[index_with_missing.notna()].values
  368. sorted_values = np.sort(not_na_vals)
  369. if na_position == "first":
  370. sorted_values = np.concatenate([[None] * missing_count, sorted_values])
  371. else:
  372. sorted_values = np.concatenate([sorted_values, [None] * missing_count])
  373. # Explicitly pass dtype needed for Index backed by EA e.g. IntegerArray
  374. expected = type(index_with_missing)(sorted_values, dtype=index_with_missing.dtype)
  375. result = index_with_missing.sort_values(na_position=na_position)
  376. tm.assert_index_equal(result, expected)
  377. def test_ndarray_compat_properties(index):
  378. if isinstance(index, PeriodIndex) and not IS64:
  379. pytest.skip("Overflow")
  380. idx = index
  381. assert idx.T.equals(idx)
  382. assert idx.transpose().equals(idx)
  383. values = idx.values
  384. assert idx.shape == values.shape
  385. assert idx.ndim == values.ndim
  386. assert idx.size == values.size
  387. if not isinstance(index, (RangeIndex, MultiIndex)):
  388. # These two are not backed by an ndarray
  389. assert idx.nbytes == values.nbytes
  390. # test for validity
  391. idx.nbytes
  392. idx.values.nbytes