test_shift.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import pytest
  2. from pandas.errors import NullFrequencyError
  3. import pandas as pd
  4. from pandas import TimedeltaIndex
  5. import pandas._testing as tm
  6. class TestTimedeltaIndexShift:
  7. # -------------------------------------------------------------
  8. # TimedeltaIndex.shift is used by __add__/__sub__
  9. def test_tdi_shift_empty(self):
  10. # GH#9903
  11. idx = TimedeltaIndex([], name="xxx")
  12. tm.assert_index_equal(idx.shift(0, freq="H"), idx)
  13. tm.assert_index_equal(idx.shift(3, freq="H"), idx)
  14. def test_tdi_shift_hours(self):
  15. # GH#9903
  16. idx = TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx")
  17. tm.assert_index_equal(idx.shift(0, freq="H"), idx)
  18. exp = TimedeltaIndex(["8 hours", "9 hours", "12 hours"], name="xxx")
  19. tm.assert_index_equal(idx.shift(3, freq="H"), exp)
  20. exp = TimedeltaIndex(["2 hours", "3 hours", "6 hours"], name="xxx")
  21. tm.assert_index_equal(idx.shift(-3, freq="H"), exp)
  22. def test_tdi_shift_minutes(self):
  23. # GH#9903
  24. idx = TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx")
  25. tm.assert_index_equal(idx.shift(0, freq="T"), idx)
  26. exp = TimedeltaIndex(["05:03:00", "06:03:00", "9:03:00"], name="xxx")
  27. tm.assert_index_equal(idx.shift(3, freq="T"), exp)
  28. exp = TimedeltaIndex(["04:57:00", "05:57:00", "8:57:00"], name="xxx")
  29. tm.assert_index_equal(idx.shift(-3, freq="T"), exp)
  30. def test_tdi_shift_int(self):
  31. # GH#8083
  32. tdi = pd.to_timedelta(range(5), unit="d")
  33. trange = tdi._with_freq("infer") + pd.offsets.Hour(1)
  34. result = trange.shift(1)
  35. expected = TimedeltaIndex(
  36. [
  37. "1 days 01:00:00",
  38. "2 days 01:00:00",
  39. "3 days 01:00:00",
  40. "4 days 01:00:00",
  41. "5 days 01:00:00",
  42. ],
  43. freq="D",
  44. )
  45. tm.assert_index_equal(result, expected)
  46. def test_tdi_shift_nonstandard_freq(self):
  47. # GH#8083
  48. tdi = pd.to_timedelta(range(5), unit="d")
  49. trange = tdi._with_freq("infer") + pd.offsets.Hour(1)
  50. result = trange.shift(3, freq="2D 1s")
  51. expected = TimedeltaIndex(
  52. [
  53. "6 days 01:00:03",
  54. "7 days 01:00:03",
  55. "8 days 01:00:03",
  56. "9 days 01:00:03",
  57. "10 days 01:00:03",
  58. ],
  59. freq="D",
  60. )
  61. tm.assert_index_equal(result, expected)
  62. def test_shift_no_freq(self):
  63. # GH#19147
  64. tdi = TimedeltaIndex(["1 days 01:00:00", "2 days 01:00:00"], freq=None)
  65. with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"):
  66. tdi.shift(2)