test_copy.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from copy import (
  2. copy,
  3. deepcopy,
  4. )
  5. import pytest
  6. from pandas import MultiIndex
  7. import pandas._testing as tm
  8. def assert_multiindex_copied(copy, original):
  9. # Levels should be (at least, shallow copied)
  10. tm.assert_copy(copy.levels, original.levels)
  11. tm.assert_almost_equal(copy.codes, original.codes)
  12. # Labels doesn't matter which way copied
  13. tm.assert_almost_equal(copy.codes, original.codes)
  14. assert copy.codes is not original.codes
  15. # Names doesn't matter which way copied
  16. assert copy.names == original.names
  17. assert copy.names is not original.names
  18. # Sort order should be copied
  19. assert copy.sortorder == original.sortorder
  20. def test_copy(idx):
  21. i_copy = idx.copy()
  22. assert_multiindex_copied(i_copy, idx)
  23. def test_shallow_copy(idx):
  24. i_copy = idx._view()
  25. assert_multiindex_copied(i_copy, idx)
  26. def test_view(idx):
  27. i_view = idx.view()
  28. assert_multiindex_copied(i_view, idx)
  29. @pytest.mark.parametrize("func", [copy, deepcopy])
  30. def test_copy_and_deepcopy(func):
  31. idx = MultiIndex(
  32. levels=[["foo", "bar"], ["fizz", "buzz"]],
  33. codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
  34. names=["first", "second"],
  35. )
  36. idx_copy = func(idx)
  37. assert idx_copy is not idx
  38. assert idx_copy.equals(idx)
  39. @pytest.mark.parametrize("deep", [True, False])
  40. def test_copy_method(deep):
  41. idx = MultiIndex(
  42. levels=[["foo", "bar"], ["fizz", "buzz"]],
  43. codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
  44. names=["first", "second"],
  45. )
  46. idx_copy = idx.copy(deep=deep)
  47. assert idx_copy.equals(idx)
  48. @pytest.mark.parametrize("deep", [True, False])
  49. @pytest.mark.parametrize(
  50. "kwarg, value",
  51. [
  52. ("names", ["third", "fourth"]),
  53. ],
  54. )
  55. def test_copy_method_kwargs(deep, kwarg, value):
  56. # gh-12309: Check that the "name" argument as well other kwargs are honored
  57. idx = MultiIndex(
  58. levels=[["foo", "bar"], ["fizz", "buzz"]],
  59. codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
  60. names=["first", "second"],
  61. )
  62. idx_copy = idx.copy(**{kwarg: value, "deep": deep})
  63. assert getattr(idx_copy, kwarg) == value
  64. def test_copy_deep_false_retains_id():
  65. # GH#47878
  66. idx = MultiIndex(
  67. levels=[["foo", "bar"], ["fizz", "buzz"]],
  68. codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
  69. names=["first", "second"],
  70. )
  71. res = idx.copy(deep=False)
  72. assert res._id is idx._id