zmc
2023-12-22 9fdbf60165db0400c2e8e6be2dc6e88138ac719a
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import numpy as np
import pytest
 
from pandas import (
    CategoricalIndex,
    DatetimeIndex,
    Index,
    NaT,
    Period,
    PeriodIndex,
    period_range,
)
import pandas._testing as tm
 
 
class TestPeriodIndexAsType:
    @pytest.mark.parametrize("dtype", [float, "timedelta64", "timedelta64[ns]"])
    def test_astype_raises(self, dtype):
        # GH#13149, GH#13209
        idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.NaN], freq="D")
        msg = "Cannot cast PeriodIndex to dtype"
        with pytest.raises(TypeError, match=msg):
            idx.astype(dtype)
 
    def test_astype_conversion(self):
        # GH#13149, GH#13209
        idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.NaN], freq="D", name="idx")
 
        result = idx.astype(object)
        expected = Index(
            [Period("2016-05-16", freq="D")] + [Period(NaT, freq="D")] * 3,
            dtype="object",
            name="idx",
        )
        tm.assert_index_equal(result, expected)
 
        result = idx.astype(np.int64)
        expected = Index(
            [16937] + [-9223372036854775808] * 3, dtype=np.int64, name="idx"
        )
        tm.assert_index_equal(result, expected)
 
        result = idx.astype(str)
        expected = Index([str(x) for x in idx], name="idx")
        tm.assert_index_equal(result, expected)
 
        idx = period_range("1990", "2009", freq="A", name="idx")
        result = idx.astype("i8")
        tm.assert_index_equal(result, Index(idx.asi8, name="idx"))
        tm.assert_numpy_array_equal(result.values, idx.asi8)
 
    def test_astype_uint(self):
        arr = period_range("2000", periods=2, name="idx")
 
        with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
            arr.astype("uint64")
        with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
            arr.astype("uint32")
 
    def test_astype_object(self):
        idx = PeriodIndex([], freq="M")
 
        exp = np.array([], dtype=object)
        tm.assert_numpy_array_equal(idx.astype(object).values, exp)
        tm.assert_numpy_array_equal(idx._mpl_repr(), exp)
 
        idx = PeriodIndex(["2011-01", NaT], freq="M")
 
        exp = np.array([Period("2011-01", freq="M"), NaT], dtype=object)
        tm.assert_numpy_array_equal(idx.astype(object).values, exp)
        tm.assert_numpy_array_equal(idx._mpl_repr(), exp)
 
        exp = np.array([Period("2011-01-01", freq="D"), NaT], dtype=object)
        idx = PeriodIndex(["2011-01-01", NaT], freq="D")
        tm.assert_numpy_array_equal(idx.astype(object).values, exp)
        tm.assert_numpy_array_equal(idx._mpl_repr(), exp)
 
    # TODO: de-duplicate this version (from test_ops) with the one above
    # (from test_period)
    def test_astype_object2(self):
        idx = period_range(start="2013-01-01", periods=4, freq="M", name="idx")
        expected_list = [
            Period("2013-01-31", freq="M"),
            Period("2013-02-28", freq="M"),
            Period("2013-03-31", freq="M"),
            Period("2013-04-30", freq="M"),
        ]
        expected = Index(expected_list, dtype=object, name="idx")
        result = idx.astype(object)
        assert isinstance(result, Index)
        assert result.dtype == object
        tm.assert_index_equal(result, expected)
        assert result.name == expected.name
        assert idx.tolist() == expected_list
 
        idx = PeriodIndex(
            ["2013-01-01", "2013-01-02", "NaT", "2013-01-04"], freq="D", name="idx"
        )
        expected_list = [
            Period("2013-01-01", freq="D"),
            Period("2013-01-02", freq="D"),
            Period("NaT", freq="D"),
            Period("2013-01-04", freq="D"),
        ]
        expected = Index(expected_list, dtype=object, name="idx")
        result = idx.astype(object)
        assert isinstance(result, Index)
        assert result.dtype == object
        tm.assert_index_equal(result, expected)
        for i in [0, 1, 3]:
            assert result[i] == expected[i]
        assert result[2] is NaT
        assert result.name == expected.name
 
        result_list = idx.tolist()
        for i in [0, 1, 3]:
            assert result_list[i] == expected_list[i]
        assert result_list[2] is NaT
 
    def test_astype_category(self):
        obj = period_range("2000", periods=2, name="idx")
        result = obj.astype("category")
        expected = CategoricalIndex(
            [Period("2000-01-01", freq="D"), Period("2000-01-02", freq="D")], name="idx"
        )
        tm.assert_index_equal(result, expected)
 
        result = obj._data.astype("category")
        expected = expected.values
        tm.assert_categorical_equal(result, expected)
 
    def test_astype_array_fallback(self):
        obj = period_range("2000", periods=2, name="idx")
        result = obj.astype(bool)
        expected = Index(np.array([True, True]), name="idx")
        tm.assert_index_equal(result, expected)
 
        result = obj._data.astype(bool)
        expected = np.array([True, True])
        tm.assert_numpy_array_equal(result, expected)
 
    def test_period_astype_to_timestamp(self):
        pi = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M")
 
        exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern")
        res = pi.astype("datetime64[ns, US/Eastern]")
        tm.assert_index_equal(res, exp)
        assert res.freq == exp.freq