test_freq_attr.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import pytest
  2. from pandas import TimedeltaIndex
  3. from pandas.tseries.offsets import (
  4. DateOffset,
  5. Day,
  6. Hour,
  7. )
  8. class TestFreq:
  9. @pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []])
  10. @pytest.mark.parametrize("freq", ["2D", Day(2), "48H", Hour(48)])
  11. def test_freq_setter(self, values, freq):
  12. # GH#20678
  13. idx = TimedeltaIndex(values)
  14. # can set to an offset, converting from string if necessary
  15. idx._data.freq = freq
  16. assert idx.freq == freq
  17. assert isinstance(idx.freq, DateOffset)
  18. # can reset to None
  19. idx._data.freq = None
  20. assert idx.freq is None
  21. def test_freq_setter_errors(self):
  22. # GH#20678
  23. idx = TimedeltaIndex(["0 days", "2 days", "4 days"])
  24. # setting with an incompatible freq
  25. msg = (
  26. "Inferred frequency 2D from passed values does not conform to "
  27. "passed frequency 5D"
  28. )
  29. with pytest.raises(ValueError, match=msg):
  30. idx._data.freq = "5D"
  31. # setting with a non-fixed frequency
  32. msg = r"<2 \* BusinessDays> is a non-fixed frequency"
  33. with pytest.raises(ValueError, match=msg):
  34. idx._data.freq = "2B"
  35. # setting with non-freq string
  36. with pytest.raises(ValueError, match="Invalid frequency"):
  37. idx._data.freq = "foo"
  38. def test_freq_view_safe(self):
  39. # Setting the freq for one TimedeltaIndex shouldn't alter the freq
  40. # for another that views the same data
  41. tdi = TimedeltaIndex(["0 days", "2 days", "4 days"], freq="2D")
  42. tda = tdi._data
  43. tdi2 = TimedeltaIndex(tda)._with_freq(None)
  44. assert tdi2.freq is None
  45. # Original was not altered
  46. assert tdi.freq == "2D"
  47. assert tda.freq == "2D"