test_compat.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import numpy as np
  2. import pytest
  3. from pandas import MultiIndex
  4. import pandas._testing as tm
  5. def test_numeric_compat(idx):
  6. with pytest.raises(TypeError, match="cannot perform __mul__"):
  7. idx * 1
  8. with pytest.raises(TypeError, match="cannot perform __rmul__"):
  9. 1 * idx
  10. div_err = "cannot perform __truediv__"
  11. with pytest.raises(TypeError, match=div_err):
  12. idx / 1
  13. div_err = div_err.replace(" __", " __r")
  14. with pytest.raises(TypeError, match=div_err):
  15. 1 / idx
  16. with pytest.raises(TypeError, match="cannot perform __floordiv__"):
  17. idx // 1
  18. with pytest.raises(TypeError, match="cannot perform __rfloordiv__"):
  19. 1 // idx
  20. @pytest.mark.parametrize("method", ["all", "any", "__invert__"])
  21. def test_logical_compat(idx, method):
  22. msg = f"cannot perform {method}"
  23. with pytest.raises(TypeError, match=msg):
  24. getattr(idx, method)()
  25. def test_inplace_mutation_resets_values():
  26. levels = [["a", "b", "c"], [4]]
  27. levels2 = [[1, 2, 3], ["a"]]
  28. codes = [[0, 1, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0]]
  29. mi1 = MultiIndex(levels=levels, codes=codes)
  30. mi2 = MultiIndex(levels=levels2, codes=codes)
  31. # instantiating MultiIndex should not access/cache _.values
  32. assert "_values" not in mi1._cache
  33. assert "_values" not in mi2._cache
  34. vals = mi1.values.copy()
  35. vals2 = mi2.values.copy()
  36. # accessing .values should cache ._values
  37. assert mi1._values is mi1._cache["_values"]
  38. assert mi1.values is mi1._cache["_values"]
  39. assert isinstance(mi1._cache["_values"], np.ndarray)
  40. # Make sure level setting works
  41. new_vals = mi1.set_levels(levels2).values
  42. tm.assert_almost_equal(vals2, new_vals)
  43. # Doesn't drop _values from _cache [implementation detail]
  44. tm.assert_almost_equal(mi1._cache["_values"], vals)
  45. # ...and values is still same too
  46. tm.assert_almost_equal(mi1.values, vals)
  47. # Make sure label setting works too
  48. codes2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
  49. exp_values = np.empty((6,), dtype=object)
  50. exp_values[:] = [(1, "a")] * 6
  51. # Must be 1d array of tuples
  52. assert exp_values.shape == (6,)
  53. new_mi = mi2.set_codes(codes2)
  54. assert "_values" not in new_mi._cache
  55. new_values = new_mi.values
  56. assert "_values" in new_mi._cache
  57. # Shouldn't change cache
  58. tm.assert_almost_equal(mi2._cache["_values"], vals2)
  59. # Should have correct values
  60. tm.assert_almost_equal(exp_values, new_values)