test_append.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import pytest
  2. from pandas import (
  3. CategoricalIndex,
  4. Index,
  5. )
  6. import pandas._testing as tm
  7. class TestAppend:
  8. @pytest.fixture
  9. def ci(self):
  10. categories = list("cab")
  11. return CategoricalIndex(list("aabbca"), categories=categories, ordered=False)
  12. def test_append(self, ci):
  13. # append cats with the same categories
  14. result = ci[:3].append(ci[3:])
  15. tm.assert_index_equal(result, ci, exact=True)
  16. foos = [ci[:1], ci[1:3], ci[3:]]
  17. result = foos[0].append(foos[1:])
  18. tm.assert_index_equal(result, ci, exact=True)
  19. def test_append_empty(self, ci):
  20. # empty
  21. result = ci.append([])
  22. tm.assert_index_equal(result, ci, exact=True)
  23. def test_append_mismatched_categories(self, ci):
  24. # appending with different categories or reordered is not ok
  25. msg = "all inputs must be Index"
  26. with pytest.raises(TypeError, match=msg):
  27. ci.append(ci.values.set_categories(list("abcd")))
  28. with pytest.raises(TypeError, match=msg):
  29. ci.append(ci.values.reorder_categories(list("abc")))
  30. def test_append_category_objects(self, ci):
  31. # with objects
  32. result = ci.append(Index(["c", "a"]))
  33. expected = CategoricalIndex(list("aabbcaca"), categories=ci.categories)
  34. tm.assert_index_equal(result, expected, exact=True)
  35. def test_append_non_categories(self, ci):
  36. # invalid objects -> cast to object via concat_compat
  37. result = ci.append(Index(["a", "d"]))
  38. expected = Index(["a", "a", "b", "b", "c", "a", "a", "d"])
  39. tm.assert_index_equal(result, expected, exact=True)
  40. def test_append_object(self, ci):
  41. # GH#14298 - if base object is not categorical -> coerce to object
  42. result = Index(["c", "a"]).append(ci)
  43. expected = Index(list("caaabbca"))
  44. tm.assert_index_equal(result, expected, exact=True)
  45. def test_append_to_another(self):
  46. # hits Index._concat
  47. fst = Index(["a", "b"])
  48. snd = CategoricalIndex(["d", "e"])
  49. result = fst.append(snd)
  50. expected = Index(["a", "b", "d", "e"])
  51. tm.assert_index_equal(result, expected)