test_copy.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import numpy as np
  2. import pytest
  3. import pandas.util._test_decorators as td
  4. from pandas import DataFrame
  5. import pandas._testing as tm
  6. class TestCopy:
  7. @pytest.mark.parametrize("attr", ["index", "columns"])
  8. def test_copy_index_name_checking(self, float_frame, attr):
  9. # don't want to be able to modify the index stored elsewhere after
  10. # making a copy
  11. ind = getattr(float_frame, attr)
  12. ind.name = None
  13. cp = float_frame.copy()
  14. getattr(cp, attr).name = "foo"
  15. assert getattr(float_frame, attr).name is None
  16. @td.skip_copy_on_write_invalid_test
  17. def test_copy_cache(self):
  18. # GH#31784 _item_cache not cleared on copy causes incorrect reads after updates
  19. df = DataFrame({"a": [1]})
  20. df["x"] = [0]
  21. df["a"]
  22. df.copy()
  23. df["a"].values[0] = -1
  24. tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]}))
  25. df["y"] = [0]
  26. assert df["a"].values[0] == -1
  27. tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))
  28. def test_copy(self, float_frame, float_string_frame):
  29. cop = float_frame.copy()
  30. cop["E"] = cop["A"]
  31. assert "E" not in float_frame
  32. # copy objects
  33. copy = float_string_frame.copy()
  34. assert copy._mgr is not float_string_frame._mgr
  35. @td.skip_array_manager_invalid_test
  36. def test_copy_consolidates(self):
  37. # GH#42477
  38. df = DataFrame(
  39. {
  40. "a": np.random.randint(0, 100, size=55),
  41. "b": np.random.randint(0, 100, size=55),
  42. }
  43. )
  44. for i in range(0, 10):
  45. df.loc[:, f"n_{i}"] = np.random.randint(0, 100, size=55)
  46. assert len(df._mgr.blocks) == 11
  47. result = df.copy()
  48. assert len(result._mgr.blocks) == 1