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