test_take.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import numpy as np
  2. import pytest
  3. import pandas as pd
  4. import pandas._testing as tm
  5. def test_take(idx):
  6. indexer = [4, 3, 0, 2]
  7. result = idx.take(indexer)
  8. expected = idx[indexer]
  9. assert result.equals(expected)
  10. # GH 10791
  11. msg = "'MultiIndex' object has no attribute 'freq'"
  12. with pytest.raises(AttributeError, match=msg):
  13. idx.freq
  14. def test_take_invalid_kwargs(idx):
  15. indices = [1, 2]
  16. msg = r"take\(\) got an unexpected keyword argument 'foo'"
  17. with pytest.raises(TypeError, match=msg):
  18. idx.take(indices, foo=2)
  19. msg = "the 'out' parameter is not supported"
  20. with pytest.raises(ValueError, match=msg):
  21. idx.take(indices, out=indices)
  22. msg = "the 'mode' parameter is not supported"
  23. with pytest.raises(ValueError, match=msg):
  24. idx.take(indices, mode="clip")
  25. def test_take_fill_value():
  26. # GH 12631
  27. vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]]
  28. idx = pd.MultiIndex.from_product(vals, names=["str", "dt"])
  29. result = idx.take(np.array([1, 0, -1]))
  30. exp_vals = [
  31. ("A", pd.Timestamp("2011-01-02")),
  32. ("A", pd.Timestamp("2011-01-01")),
  33. ("B", pd.Timestamp("2011-01-02")),
  34. ]
  35. expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])
  36. tm.assert_index_equal(result, expected)
  37. # fill_value
  38. result = idx.take(np.array([1, 0, -1]), fill_value=True)
  39. exp_vals = [
  40. ("A", pd.Timestamp("2011-01-02")),
  41. ("A", pd.Timestamp("2011-01-01")),
  42. (np.nan, pd.NaT),
  43. ]
  44. expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])
  45. tm.assert_index_equal(result, expected)
  46. # allow_fill=False
  47. result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
  48. exp_vals = [
  49. ("A", pd.Timestamp("2011-01-02")),
  50. ("A", pd.Timestamp("2011-01-01")),
  51. ("B", pd.Timestamp("2011-01-02")),
  52. ]
  53. expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])
  54. tm.assert_index_equal(result, expected)
  55. msg = "When allow_fill=True and fill_value is not None, all indices must be >= -1"
  56. with pytest.raises(ValueError, match=msg):
  57. idx.take(np.array([1, 0, -2]), fill_value=True)
  58. with pytest.raises(ValueError, match=msg):
  59. idx.take(np.array([1, 0, -5]), fill_value=True)
  60. msg = "index -5 is out of bounds for( axis 0 with)? size 4"
  61. with pytest.raises(IndexError, match=msg):
  62. idx.take(np.array([1, -5]))