test_reshape.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. Tests for ndarray-like method on the base Index class
  3. """
  4. import numpy as np
  5. import pytest
  6. from pandas import Index
  7. import pandas._testing as tm
  8. class TestReshape:
  9. def test_repeat(self):
  10. repeats = 2
  11. index = Index([1, 2, 3])
  12. expected = Index([1, 1, 2, 2, 3, 3])
  13. result = index.repeat(repeats)
  14. tm.assert_index_equal(result, expected)
  15. def test_insert(self):
  16. # GH 7256
  17. # validate neg/pos inserts
  18. result = Index(["b", "c", "d"])
  19. # test 0th element
  20. tm.assert_index_equal(Index(["a", "b", "c", "d"]), result.insert(0, "a"))
  21. # test Nth element that follows Python list behavior
  22. tm.assert_index_equal(Index(["b", "c", "e", "d"]), result.insert(-1, "e"))
  23. # test loc +/- neq (0, -1)
  24. tm.assert_index_equal(result.insert(1, "z"), result.insert(-2, "z"))
  25. # test empty
  26. null_index = Index([])
  27. tm.assert_index_equal(Index(["a"]), null_index.insert(0, "a"))
  28. def test_insert_missing(self, nulls_fixture):
  29. # GH#22295
  30. # test there is no mangling of NA values
  31. expected = Index(["a", nulls_fixture, "b", "c"])
  32. result = Index(list("abc")).insert(1, nulls_fixture)
  33. tm.assert_index_equal(result, expected)
  34. @pytest.mark.parametrize(
  35. "val", [(1, 2), np.datetime64("2019-12-31"), np.timedelta64(1, "D")]
  36. )
  37. @pytest.mark.parametrize("loc", [-1, 2])
  38. def test_insert_datetime_into_object(self, loc, val):
  39. # GH#44509
  40. idx = Index(["1", "2", "3"])
  41. result = idx.insert(loc, val)
  42. expected = Index(["1", "2", val, "3"])
  43. tm.assert_index_equal(result, expected)
  44. assert type(expected[2]) is type(val)
  45. @pytest.mark.parametrize(
  46. "pos,expected",
  47. [
  48. (0, Index(["b", "c", "d"], name="index")),
  49. (-1, Index(["a", "b", "c"], name="index")),
  50. ],
  51. )
  52. def test_delete(self, pos, expected):
  53. index = Index(["a", "b", "c", "d"], name="index")
  54. result = index.delete(pos)
  55. tm.assert_index_equal(result, expected)
  56. assert result.name == expected.name
  57. def test_delete_raises(self):
  58. index = Index(["a", "b", "c", "d"], name="index")
  59. msg = "index 5 is out of bounds for axis 0 with size 4"
  60. with pytest.raises(IndexError, match=msg):
  61. index.delete(5)
  62. def test_append_multiple(self):
  63. index = Index(["a", "b", "c", "d", "e", "f"])
  64. foos = [index[:2], index[2:4], index[4:]]
  65. result = foos[0].append(foos[1:])
  66. tm.assert_index_equal(result, index)
  67. # empty
  68. result = index.append([])
  69. tm.assert_index_equal(result, index)