test_copy.py 2.4 KB

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