test_any_index.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """
  2. Tests that can be parametrized over _any_ Index object.
  3. """
  4. import re
  5. import numpy as np
  6. import pytest
  7. from pandas.errors import InvalidIndexError
  8. import pandas._testing as tm
  9. def test_boolean_context_compat(index):
  10. # GH#7897
  11. with pytest.raises(ValueError, match="The truth value of a"):
  12. if index:
  13. pass
  14. with pytest.raises(ValueError, match="The truth value of a"):
  15. bool(index)
  16. def test_sort(index):
  17. msg = "cannot sort an Index object in-place, use sort_values instead"
  18. with pytest.raises(TypeError, match=msg):
  19. index.sort()
  20. def test_hash_error(index):
  21. with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"):
  22. hash(index)
  23. def test_mutability(index):
  24. if not len(index):
  25. return
  26. msg = "Index does not support mutable operations"
  27. with pytest.raises(TypeError, match=msg):
  28. index[0] = index[0]
  29. def test_map_identity_mapping(index, request):
  30. # GH#12766
  31. result = index.map(lambda x: x)
  32. if index.dtype == object and result.dtype == bool:
  33. assert (index == result).all()
  34. # TODO: could work that into the 'exact="equiv"'?
  35. return # FIXME: doesn't belong in this file anymore!
  36. tm.assert_index_equal(result, index, exact="equiv")
  37. def test_wrong_number_names(index):
  38. names = index.nlevels * ["apple", "banana", "carrot"]
  39. with pytest.raises(ValueError, match="^Length"):
  40. index.names = names
  41. def test_view_preserves_name(index):
  42. assert index.view().name == index.name
  43. def test_ravel(index):
  44. # GH#19956 ravel returning ndarray is deprecated, in 2.0 returns a view on self
  45. res = index.ravel()
  46. tm.assert_index_equal(res, index)
  47. class TestConversion:
  48. def test_to_series(self, index):
  49. # assert that we are creating a copy of the index
  50. ser = index.to_series()
  51. assert ser.values is not index.values
  52. assert ser.index is not index
  53. assert ser.name == index.name
  54. def test_to_series_with_arguments(self, index):
  55. # GH#18699
  56. # index kwarg
  57. ser = index.to_series(index=index)
  58. assert ser.values is not index.values
  59. assert ser.index is index
  60. assert ser.name == index.name
  61. # name kwarg
  62. ser = index.to_series(name="__test")
  63. assert ser.values is not index.values
  64. assert ser.index is not index
  65. assert ser.name != index.name
  66. def test_tolist_matches_list(self, index):
  67. assert index.tolist() == list(index)
  68. class TestRoundTrips:
  69. def test_pickle_roundtrip(self, index):
  70. result = tm.round_trip_pickle(index)
  71. tm.assert_index_equal(result, index, exact=True)
  72. if result.nlevels > 1:
  73. # GH#8367 round-trip with timezone
  74. assert index.equal_levels(result)
  75. def test_pickle_preserves_name(self, index):
  76. original_name, index.name = index.name, "foo"
  77. unpickled = tm.round_trip_pickle(index)
  78. assert index.equals(unpickled)
  79. index.name = original_name
  80. class TestIndexing:
  81. def test_get_loc_listlike_raises_invalid_index_error(self, index):
  82. # and never TypeError
  83. key = np.array([0, 1], dtype=np.intp)
  84. with pytest.raises(InvalidIndexError, match=r"\[0 1\]"):
  85. index.get_loc(key)
  86. with pytest.raises(InvalidIndexError, match=r"\[False True\]"):
  87. index.get_loc(key.astype(bool))
  88. def test_getitem_ellipsis(self, index):
  89. # GH#21282
  90. result = index[...]
  91. assert result.equals(index)
  92. assert result is not index
  93. def test_slice_keeps_name(self, index):
  94. assert index.name == index[1:].name
  95. @pytest.mark.parametrize("item", [101, "no_int", 2.5])
  96. def test_getitem_error(self, index, item):
  97. msg = "|".join(
  98. [
  99. r"index 101 is out of bounds for axis 0 with size [\d]+",
  100. re.escape(
  101. "only integers, slices (`:`), ellipsis (`...`), "
  102. "numpy.newaxis (`None`) and integer or boolean arrays "
  103. "are valid indices"
  104. ),
  105. "index out of bounds", # string[pyarrow]
  106. ]
  107. )
  108. with pytest.raises(IndexError, match=msg):
  109. index[item]
  110. class TestRendering:
  111. def test_str(self, index):
  112. # test the string repr
  113. index.name = "foo"
  114. assert "'foo'" in str(index)
  115. assert type(index).__name__ in str(index)
  116. class TestReductions:
  117. def test_argmax_axis_invalid(self, index):
  118. # GH#23081
  119. msg = r"`axis` must be fewer than the number of dimensions \(1\)"
  120. with pytest.raises(ValueError, match=msg):
  121. index.argmax(axis=1)
  122. with pytest.raises(ValueError, match=msg):
  123. index.argmin(axis=2)
  124. with pytest.raises(ValueError, match=msg):
  125. index.min(axis=-2)
  126. with pytest.raises(ValueError, match=msg):
  127. index.max(axis=-3)